Mobile app version of vmapp.org
Login or Join
Fox8124981

: How to 301 redirect back to a pretty link without creating an infinite loop in .htaccess I am doing a rewrite from .htaccess file to redirect pretty links to original URLs: RewriteRule ^users/?$

@Fox8124981

Posted in: #301Redirect #Apache #Htaccess #ModRewrite

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?

10.01% popularity Vote Up Vote Down


Login to follow query

More posts by @Fox8124981

1 Comments

Sorted by latest first Latest Oldest Best

 

@Alves908

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.)

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme