2

I had this url on my website example.com/foo.php and I changed it to example.com/foo by doing this in my htaccess:

RewriteRule ^foo$ foo.php [NC,L]

And it works fine. However I'd like to do a 301 redirect from the old url to the new url. So I added this line in my htaccess:

RewriteRule ^foo.php$ http://example.com/foo [L,NC,R=301]

And I get an infinite loop of redirects... How to fix that?

Amit Verma
  • 40,709
  • 21
  • 93
  • 115

2 Answers2

0

You can avoid the loop error using THE_REQUEST variable :

RewriteCond %{THE_REQUEST} /foo\.php [NC]
RewriteRule ^foo\.php$ http://example.com/foo [L,R=301]
RewriteRule ^foo$ foo.php [NC,L]

Or if you are on apache 2.4, you can use the END flag

RewriteRule ^foo\.php$ http://example.com/foo [L,R=301]
RewriteRule ^foo$ foo.php [NC,END]
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
  • 2
    The END tag solved my problem, thanks! Care to explain what it does? –  May 02 '16 at 15:23
  • 1
    END flag ends the rewrting process immideatly. otherwise without the END the target path foo.php matchs pattern of the first rule again and creates an infinite internal redirect. – Amit Verma May 02 '16 at 15:45
0

If you change the order it shouldn't loop work. Try the bellow works fine:

RewriteEngine on
RewriteRule ^foo.php$ http://example.com/foo [L,NC,R=301]
RewriteRule ^foo$ foo.php [NC,L]
Helton Malambane
  • 1,147
  • 11
  • 12