I’m trying to pass a variable via a URL parameter and rewrite + force 'redirect' it.
In other words, I have:
/dir1/dir2/?my_var=123
and I want:
/dir1/dir2/123/
Through the following code in my functions.php file, I am able to achieve that:
function setup_filter_rewrites()
{
add_rewrite_rule('dir1/dir2/([^/]*)/?', 'index.php?pagename=dir1/dir2&my_var=$matches[1]', 'top');
}
add_action( 'init', 'setup_filter_rewrites' );
function setup_filter_query_vars( $query_vars )
{
$query_vars[] = 'my_var';
return $query_vars;
}
add_filter( 'query_vars', 'setup_filter_query_vars' );
However, I'm still able to access the URL via /dir1/dir2/?my_var=123.
Is there a way to force 'redirect' (not sure if this is the right way to call this) the URL so that it always serves only the rewritten version? For instance, the way /?page_id=456 forces /my-page-name/ when pretty permalinks are enabled.
Do I need to do anything via .htaccess or am I just missing something in the code?
Thanks in advance!