gtr1971
gtr1971

Reputation: 2732

.htaccess redirect loop when Redirect and RewriteRule together

I'm attempting the following in an HTACCESS file:

I want to 301 redirect this --> http://www.domain.com/somepage.php?page=foo

to this --> http://www.domain.com/my-pretty-url/

This works fine when I alter internal links on the site to read how I want and I DO NOT use the R=301 flag:

RewriteRule ^my-pretty-url/$ /index\.php?page=foo [L]

BUT... the hitch here is I also want to 301 Redirect any external requests to the server, which when I handle that it puts me in a redirect loop.

RewriteCond %{REQUEST_URI} /index.php$
RewriteCond %{QUERY_STRING} ^page=foo$
RewriteRule ^.*$ http://www.domain.com/my-pretty-url/? [R=301,L]

RewriteRule ^my-pretty-url/$ /index\.php?page=foo [L]

The RewriteCond rules don't work by themselves, only the single RewriteRule at the bottom works by itself for internal rewrites, but it doesn't handle outside requests.

Obviously, if I have both together, it's creating a loop. How do I get around this??

Thanks!

Upvotes: 4

Views: 4067

Answers (1)

Ulrich Palha
Ulrich Palha

Reputation: 9509

Try the following to prevent the looping

#prevent internal redirects, and prevent loop
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteCond %{REQUEST_URI} /index.php$
RewriteCond %{QUERY_STRING} ^page=foo$
RewriteRule ^.*$ http://www.domain.com/my-pretty-url/? [R=301,L]

RewriteRule ^my-pretty-url/$ /index\.php?page=foo [L]

Upvotes: 5

Related Questions