You can use template_redirect. Here a simple redirection function.
add_action( 'template_redirect', 'se219663_template_redirect' );
function se219663_template_redirect()
{
global $wp_rewrite;
if ( is_search() && ! empty ( $_GET['s'] ) )
{
$s = sanitize_text_field( $_GET['s'] ); // or get_query_var( 's' )
$location = "https://wordpress.stackexchange.com/";
$location .= trailingslashit( $wp_rewrite->search_base );
$location .= user_trailingslashit( urlencode( $s ) );
$location = home_url( $location );
wp_safe_redirect( $location, 301 );
exit;
}
}
Rule without search query, like this ( don’t forget go to Permalink Settings to flush the rules ):
add_filter( 'search_rewrite_rules', 'se219663_search_rewrite_rules', 10, 1 );
function se219663_search_rewrite_rules( $rewrite )
{
global $wp_rewrite;
$rules = array(
$wp_rewrite->search_base . '/?$' => 'index.php?s=",
);
$rewrite = $rewrite + $rules;
return $rewrite;
}
and redirect with empty search query, just use isset, modified from the code above.
add_action( "template_redirect', 'se219663_template_redirect' );
function se219663_template_redirect()
{
global $wp_rewrite;
if ( is_search() && isset ( $_GET['s'] ) )
{
$s = sanitize_text_field( $_GET['s'] ); // or get_query_var( 's' )
$location = "https://wordpress.stackexchange.com/";
$location .= trailingslashit( $wp_rewrite->search_base );
$location .= ( ! empty ( $s ) ) ? user_trailingslashit( urlencode( $s ) ) : urlencode( $s );
$location = home_url( $location );
wp_safe_redirect( $location, 301 );
exit;
}
}