Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess RewriteRule works but the URL isn't changing in the address bar?

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 and change it to mysite.com/testRewrite/ The code to do implement this should be:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^testRewrite/$ test.php [NC,L]

For whatever reason it's just not working. When you go to the new URL - mysite.com/testRewrite/ it works.

However, if you type in the original URL mysite.com/test.php it doesn't change the address to the new URL in the browser.

like image 439
denvdancsk Avatar asked Dec 28 '22 03:12

denvdancsk


1 Answers

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.

like image 155
Jon Lin Avatar answered Jan 13 '23 16:01

Jon Lin