2

I am doing a rewrite from .htaccess file to redirect pretty links to original URLs:

RewriteRule ^users/?$ /?status=users [NC,L,QSA]

which redirects my SEO/pretty link:

example.com/users

to the real URL

example.com/?status=users

Then again I want any search engine bot (or anyone else) who tries to get to

example.com/?status=users

to be 301 redirected to the pretty link

example.com/users

I know I could get the later part done using

RewriteCond %{QUERY_STRING} (^|&)status=users($|&)
RewriteRule ^$ /users? [L,R=301]

But I can't use these two together as it gets into a never ending loop and the browser displays "redirected you too many times".

I think I get what the problem is here, but what is the solution? How do I achieve both?

1 Answer 1

2
RewriteCond %{QUERY_STRING} (^|&)status=users($|&)
RewriteRule ^$ /users? [L,R=301]

You just need an additional condition (ie. RewriteCond directive) on your external redirect that detects whether it is a direct/initial request from the user, as opposed to a rewritten request by your other rewrite directive.

One way to do this is to check the REDIRECT_STATUS environment variable. This is not set on the initial request, but is set to "200" (as in 200 OK) after the first successful rewrite. So, you can check to see whether REDIRECT_STATUS is empty in order to detect the direct request and prevent a redirect loop.

For example:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} (^|&)status=users($|&)
RewriteRule ^$ /users? [L,R=301]

Another way is to check against THE_REQUEST server variable, which contains the first line of the initial request and does not change when the URL is rewritten. So, when requesting example.com/?status=users directly, THE_REQUEST would contain a string of the form:

GET /?status=users HTTP/1.1

This would allow you to have just one condition, as opposed to two as in the above, at the expense of perhaps a more complex regex. (Implementation is left as an exercise for the reader.)

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.