0

I have a lot of working mod_rewrite rules already in my httpd.conf file. I just recently found that Google had indexed one of my non-rewritten URLs with a query string in it:

http://example.com/?state=arizona

I would like to use mod_rewrite to do a 301 redirect to this URL:

http://example.com/arizona

The issue is that later on in my rewrite rules, that 2nd URL is being rewritten to pass query variables on to WordPress. It ends up getting rewritten to:

http://example.com/index.php?state=arizona

Which is the proper functionality. Everything I have tried so far has either not worked at all or put me in an endless rewrite loop. This is what I have right now, which is getting stuck in a loop:

RewriteCond %{QUERY_STRING} state=arizona [NC]
RewriteRule .*   http://example.com/arizona [R=301,L]
#older rewrite rule that passes query string based on URL:
RewriteRule ^([A-Za-z-]+)$ index.php?state=$1 [L]

which gives me an endless rewrite loop and takes me to this URL: http://example.com/arizona?state=arizona

I then tried this:

RewriteRule .*   http://example.com/arizona? [R=301,L]

which got rid of the query string in the URL, but still creates a loop.

2 Answers 2

1

Ok, adding the 2nd RewriteCond finally fixed it - now rewriting correctly and no loop:

# redirect dynamic URL: ?state=arizona
RewriteCond %{QUERY_STRING} state=arizona [NC]
RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteRule .*   http://domain.com/arizona? [R=301,L]
# older rewrite rule that passes query string based on URL:
RewriteRule ^([A-Za-z-]+)$ index.php?state=$1 [L]

And here's the code to make it work for any state value, not just arizona:

RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteCond %{QUERY_STRING} ^state=([A-Za-z-]+)$ [NC]
RewriteRule .*   http://domain.com/%1? [R=301,L]
Sign up to request clarification or add additional context in comments.

Comments

0

RewriteCond %{REQUEST_URI} ^/\?state=arizona$ [NC]

should be

RewriteCond %{QUERY_STRING} state=arizona [NC]

The request_uri ends at the ? token.

2 Comments

You probably need to tighten up RewriteRule ^([\w-]+)$ index.php?state=$1 [L] to RewriteRule ^([a-z_]+)$ index.php?state=$1 [L]. index.php won't match that and won't get redirected.
how would the "dot" character match the character class [\w-] ? Anyway, i changed it above, but still have the same loop.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.