Forum Moderators: phranque

Message Too Old, No Replies

Avoiding duplicate content: Problem with rewrite rules

         

redox

12:17 pm on Mar 7, 2011 (gmt 0)

10+ Year Member



Hello,

I'm using this rewrite rule in my .htaccess to create a SEO friendly URL:

RewriteRule ^tools$ http://www.example.com/focus/tools.php [L]

My problem:
The script URL has been published before the rewrite rule was created. How can I avoid duplicate content, since the content can be reached by http://www.example.com/tools AND by http://www.example.com/focus/tools.php

MY first idea was to put the following rule BEFORE the above rule:
RewriteRule ^focus/tools\.php$ http://www.example.com/tools [R=301,L]
This won't work, and I admit I'm stuck for now. Any help would be greatly appreciated.

Thank you
Oliver

g1smd

1:55 pm on Mar 7, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm using this rewrite rule in my .htaccess to create a SEO friendly URL

The .htaccess rule cannot "create" anything. URLs are created in the links you publish on the pages of your site. Only once that link is clicked is anything sent to the server.

The mod_rewrite rules deal with that incoming request. They either respond with a redirect to a different URL, or internally rewrite the request to get the content from an internal non-default location inside the server, or in the case of not matching the pattern mod_rewrite does nothing at all for the current request.


RewriteRule ^tools$ http://www.example.com/focus/tools.php [L]

When user asks for
example.com/tools
the above rule creates an external 302 redirect to the new URL
http://www.example.com/focus/tools.php
.

What you actually needed was an internal rewrite:
RewriteRule ^tools$ /focus/tools.php [L]



RewriteRule ^focus/tools\.php$ http://www.example.com/tools [R=301,L]

The code for the redirect is correct. However, when both rules are used on the site, you will get an infinite redirect loop.


The solution is to let the redirect happen only for direct client requests and not when the filepath has already been rewritten.

# External redirect
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /focus/tools\.php\ HTTP/
RewriteRule ^focus/tools\.php$ http://www.example.com/tools [R=301,L]
#
# non-www to www canonicalisation redirect
RewriteCond %{HTTP_HOST} !^(www\.example\.com)?$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
#
# Internal Rewrite
RewriteRule ^tools$ /focus/tools.php [L]

redox

2:47 pm on Mar 7, 2011 (gmt 0)

10+ Year Member



Thank you very much!

This is the second time I posted a question and the second time I got an immediate perfect response. I thought best way to show my appreciation is to subscribe for a membership and this is what I did a few minutes ago.

Thanks again :-)
Oliver