I am trying to use mod_rewrite and modify WordPress' URL handling to allow for passing variables to PHP from the URL while maintaining "pretty permalink" functionality. (on WP 3.2.1)

Something like this:

http:/epiclasers.com/hello-world (normal with permalinks set to /%postname%)

http:/epiclasers.com/state/hello-world (WP should display the same hello-world post as above, but also would pass the state string to PHP as a variable)

http:/epiclasers.com/state/city/hello-world (WP should display the hello-world post, but would pass the state and city strings to PHP as variables)

I added the following mod_rewrite directives to my .htaccess file:

RewriteRule ^(\w+)/(\w+)/ /index.php?state=$1&city=$2 [L]
RewriteRule ^(\w+)/ /index.php?state=$1 [L]

which kind of works. The variables are being passed, and PHP can grab them with:

$state = $_GET['state'];
$city = $_GET['city'];

The problem is that WP is getting confused by the variables in the URL and isn't outputting the correct template file. URL's like these:


are bringing up the 404 page not found template.

How do I modify the WP URL handling code to ignore the /state and /city parts of the URL without also breaking URLs like:




  • Can't you just add a rule earlier for the tag|category (and so on) that you need? You also have the option to do some filtering based on the permalink URL. It's post_rewrite_rule. Checkout codex.wordpress.org/Class_Reference/WP_Rewrite
    – grm
    Dec 2, 2011 at 10:45
  • Sorry, but I'm not sure how what you are suggesting will fix the problems I am having. I also don't have any experience with modifying WP code in this way, unfortunately. I'm really needing some specific help here.
    – meeble
    Dec 2, 2011 at 18:15
  • I was thinking about adding a rule above your rule for e.g. tag, category. Sorry that I can't provide exact rule so you need to try for yourself or hope for answer. Something like RerwriteRule ^(tag|category) index.php [L]
    – grm
    Dec 5, 2011 at 9:58
  • The mod_rewrite directives don't seem to be the problem. The problem seems to be that WordPress is ignoring the mod_rewrite output and processing the request/query based on $_SERVER['REQUEST_URI'].
    – meeble
    Dec 5, 2011 at 23:14

1 Answer 1


I ended up solving this with a little bit of code (in the form of a plugin):

if(isset($_GET['state']) OR isset($_GET['city'])) {
$url = explode("/", $_SERVER['REQUEST_URI']);
$url = end($url);
$_SERVER['REQUEST_URI'] = "/" . $url;

This code in essence removes the "/arizona/" or "/arizona/phoenix/" from the REQUEST_URI global variable and replaces it with "/", which then forces WP to serve up the front page template using index.php. Fixed!

Perhaps a few of you can vote this answer up for me. :)

Your Answer

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

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