I have been pulling my hair trying to figure this out but nothing is working. I have a webpage at mysite.com/test.php I want to do a simple URL rewrite a
mod_rewrite won't automatically enforce redirecting browsers from rewritten URLs. The rule you have simply says "if someone asks for /testRewrite/
, internally change it to /test.php
". It does nothing to handle actual requests for /test.php
, which is why when you try to access mysite.com/test.php, it gives you /test.php
.
Now, the problem with mod_rewrite is if you simply add that rule:
RewriteRule ^test.php$ /testRewrite/ [L,R=301]
which will redirect the browser when it asks for /test.php
to /testRewrite/
, the first rule will be applied after the browser redirects, and the URI gets rewritten to /test.php
, then it goes back through the entire rewrite engine and the above rule gets applied again, thus redirecting the browser, thus the first rule rewrites to /test.php
, and the above rule redirects again, etc. etc. You get a redirect loop. You have to add a condition to ensure the browser *actually requested /test.php
and that it's not a URI that's been churned through the rewrite engine:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /test\.php [NC]
RewriteRule ^test.php$ /testRewrite/ [L,R=301]
This way, after the 301 redirect happens, this rule won't get applied again because the actual request will be GET /testRewrite/ HTTP/1.1
, and the condition won't be met.