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

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.

Share or Bookmark This Post:

Comments

RSS Comments Feed


Sven's Avatar

Sven

Neat and useful trick, as always at your site.

Thanks a lot Matt :)

Poppoll's Avatar

Poppoll

Matt rules!!

arohatech1's Avatar

arohatech1

Thanks for sharing the piece of information...

M Jehanzeb's Avatar

M Jehanzeb

Excellent code. Appreciate your help




(optional, not publicly displayed)


(optional)

Subscribe

RSS Feed

Archives

Powered by HTML5

HTML5 Powered with CSS3 / Styling, Multimedia, and Semantics