Force trailing slash with .htaccess
Posted on June 3rd, 2010
Forcing a trailing slash onto your URLs using a .htaccess file is a simple and useful way of ensuring that your web sites pages are accessible only via a single URL meaning there’s less chance that Google or any other search engine will see them as being duplicate pages. The problem is that having two URLs – one with a trailing slash and one without means that Google and others will treat the two URLs as completely different pages. This means that you may be penalised for having what appears to be duplicate content.
This can be fixed with a few lines inside your .htaccess file placed at the root of your web site. The lines required to force a trailing slash onto your web site URLs using .htaccess looks like this.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)$ http://www.wmtutorials.com/$1/ [R=301,L]The first two lines of the above .htaccess snippet are rewrite conditions. The first specifies that the URL must not be a file (it would be silly to have ‘wmtutorials.com/file.jpg/’) and the second specifies that the URL must not be an existing directory.
The third line is where the magic happens with a simple rewrite rule. It redirects every ‘non-trailing-slashed’ URL to the one with the trailing slash – simple!
And that’s all there is to it. Now you have forced a trailing slash using htaccess.