Question

I can't seem to get my 301 redirect working, mod_alias is enabled along with mod_rewrite.

My rewrites work fine, but the 301s do not work. Basically what I am trying to do is setup "clean" URLs from dynamic php pages, which works fine...

The other part for each of these dynamic pages, I would like them to redirect to the right "clean" url.

Here is my .htaccess

#
# Options below ensure that all traffic is directed to www.mydomain
#
Options +FollowSymlinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^mydomain.com
RewriteRule (.*) http://www.mydomain.com/$1 [R=301,L]
RewriteRule ^index.php$ http://www.mydomain.com/ [R=301,L]

#
# URL Rewrites
#
RewriteRule videos page.php?id=1 [L]

#
# Custom redirects from OLD URLs
#
redirect 301 /page.php?id=1 /videos

Trying to achieve...

mydomain.com/videos

(this works - redirect does not)  

If someone visits the dynamic page (page.php?id=1) they're automatically redirected to the clean URL.

mydomain.com/page.php?id=1 -> mydomain.com/videos

I tried using R=301 in the RewriteRule but a fatal error occurs. So that's why I created the redirect 301, but it just does not work period.

Était-ce utile?

La solution

Okay, so if a visitor requests /videos then you want the request to be silently rewritten to the actual path /page.php?id=1 so that you can advertise the "clean" URL /videos and hide the query string ugliness.

But you also want to force a visitor who actually requests /page.php?id=1 to be permanently redirected to the "clean" URL /videos so that they get the message that query string ugliness is no longer for their eyes.

The problem is that even rewritten requests have to run through your Apache directives all over again, which means that clean will rewrite to actual, which will then redirect to clean, which will rewrite to actual, and so on infinitely. Which is why you're getting a fatal error.

The only way to break this loop is to change the actual path or insert a dummy variable which allows the RewriteEngine to stop once the rewrite has been done once.

For example, you could use the following:

RewriteCond %{QUERY_STRING} !&redirect=done$
RewriteCond %{QUERY_STRING} ^id=1
RewriteRule /page.php /videos [R=permanent]
RewriteRule /videos /page.php?id=1&redirect=done

This will always silently rewrite /videos to /page.php?id=1&redirect=done, but it will only redirect /page.php to /videos if the request for page.php does not have a query string which ends with redirect=done (and also does have a query string which begins with id=1).

It's convoluted, but it's the only way I can think to break the infinite loop.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top