Force the trailing slash on your urls with mod_rewite and .htaccess

Comments (2)

If you use Google's Webmaster Tools, you may notice the occasional duplicate content error pointing to the same page, the only apparent difference is one URL is without the trailing slash. i.e.

· http://www.mdj.us/themes
· http://www.mdj.us/themes/

Same page, right? Well Google and other search engines treat this as two separate URLs, and some search engines (Yahoo, that means you) even go as far as to remove the trailing slash on some links, actually creating this problem.

While it won't hurt anything, and shows the visitor the same page in your site, in some cases it's best to simply force the trailing slash. Fortunately this is easy with mod_write and .htaccess, just add the following to your .htaccess mod_rewrite rules. If you're using sNews, add it above the final cond/rule, i.e. add the highlighted code below;

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*) $1 [L]
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L,R=301] 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?category=$1

The first line checks that the URL ends with a slash and if not executes the next line, which redirects with the slash and gives a "301 permanently moved" header so the search engine will know to update the URL to use the trailing slash.

bookmark / share this: Bookmark and Share
rated 2.67/5 (3 votes)

2 comments

Add a new comment »

Sven Sven said:
Mar 3rd, 2009 at 7:04 pm

Neat and useful trick, as always at your site.

Thanks a lot Matt :)


Poppoll Poppoll said:
Mar 6th, 2009 at 6:44 pm

Matt rules!!



Write a comment

* = required field

:

:

:

:

You may insert urls in plain text, urls will be automatically linkified for trusted users and on seasoned posts only. All first comments are moderated, so use your email if you want to be remembered.


Back to top