I’m trying to pass a variable via a URL parameter and rewrite + force 'redirect' it.

In other words, I have:


and I want:


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!

  • 1
    Why don't you use rewrite endpoints instead of complete rewrite rules? This would terminate the whole problem.
    – David
    Feb 7, 2016 at 9:58

1 Answer 1


You could force the redirect this way by checking for the get_var query value:

function my_redirect_check() {
    if (isset($_GET['my_var'])) {
        if ($_GET['my_var'] != '') {
            if ($_SERVER["HTTPS"]) {$location = 'https://';}
            else {$location = 'http://';}
            $location .= $_SERVER['SERVER_NAME'];   
            $location .= strtok($_SERVER['REQUEST_URI'],'?');
            $location = trailingslashit($location);
            $location .= $_GET['my_var'];
            $location = trailingslashit($location);                          
            wp_redirect($location); exit;

Note: you will lose any other querystring values this way, but you could always rebuild and append those also if needed.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.