Force trailing slash with .htaccess

There are a few reasons to force a trailing slash at the end of URLs including SEO

A quick snippet for your .htaccess is below:

<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</IfModule>

And while I’m here a quick snippet to prevent hotlinking of images. This will redirect all requests to a specified image, simply replace yoursite.com with your own URL, and nohotlinking.jpg with your own image and path.
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?yoursite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlinking.jpg [L]

And finally a snippet to put in your image assets folder (you have images stored separately right?) to prevent malicious code execution and prevent directory listing of all your assets.
Options All -Indexes
AddHandler cgi-script .php .php4 .php5 .pl .jsp .asp .sh .cgi
Options -ExecCGI

2 thoughts on “Force trailing slash with .htaccess”

Comments are closed.