WordPress.org

Ready to get started?Download WordPress

Forums

WP ignores querystring variables when using Mod_Rewrite? (2 posts)

  1. Matt van Andel
    Member
    Posted 3 years ago #

    Weird problem. I have this RewriteRule in my htaccess file:

    RewriteRule ^participants/profile/([^/]*)/([^/]*)/? /index.php?page_id=83&profile=$1&title=$2 [NC,L]

    If the condition is matched, I'll be sent to page 83 correctly, but the extra querystring variables are GONE (I've printed out $wp_query->query_vars to make sure).

    Here's why I'm stumped... entering something like www.mysite.com/index.php?page_id=83&profile=42&title=deep-thought directly into the browser WORKS... just not when using the htaccess RewriteRule.

    $wp_query->query_vars grabs the extra variables exactly as expected... but only when you enter the URL directly. When using a RewriteRule, the extra variables are lost.

    Any ideas on how to get around this?

  2. Matt van Andel
    Member
    Posted 3 years ago #

    Problem solved.

    I commented out the RewriteRule in my .htaccess file and created a new WP_Rewrite rule in my WP theme's functions.php file. This effectively accomplishes the same thing, but ensures that WordPress is aware of the 'extra' querystring variables (so they're not lost or ignored).

    /**
     * Handle URL rewrites for profiles page
     **/
    function ctx_rewrite_participant_profiles() {
    
        //Add the new rule before any other WP rules
        add_rewrite_rule('^participants/profile/([^/]*)/([^/]*)/?','index.php?page_id=83&profile=$matches[1]&title=$matches[2]','top');
    
        //Let WP know about our custom querystring variables
        add_rewrite_tag('%profile%','([^&]+)','profile=');
        add_rewrite_tag('%title%','([^&]+)','title=');
    }
    //Hook this into init
    add_action('init', 'ctx_rewrite_participant_profiles');

    I then saved the blog's permalink settings to rebuild the rules and... MAGIC!

    I also left the following in my .htaccess to force-redirect users from the old URL to the new pretty one.

    #Redirect querystring requests
      RewriteCond %{QUERY_STRING} profile=([^&]*)&title=([^&]*) [NC]
      RewriteRule ^participants/profile/ /participants/profile/%1/%2/? [R=301,NC,L]

    I should note (for the curious) that the above .htaccess code only works when placed BEFORE WordPress's rewrites, and the L is critical (else WP rewrites your newly redirected URL and you get a WP 404).

    :-D

Topic Closed

This topic has been closed to new replies.

About this Topic