Using .htaccess to add trailing slashes to all URIs or URLs
Apache’s Rewrite Module allows developers to define extensive URL Rewriting and Redirecting Conditions & Rules, one of which could be to add trailing slashes to Representational State Transfer (RESTful) URLs.
RESTful URLs are Uniform Resource Indicators (URIs) that are more user- and SEO-friendly than standard GET-based URIs. For example (GET vs. REST):
http://www.geekology.co.za/blog/article.php?id=1 http://www.geekology.co.za/blog/index.php/article/1
…or (GET vs. REST):
http://www.geekology.co.za/blog/article.php?slug=this-is-the-article-title http://www.geekology.co.za/blog/index.php/article/this-is-the-article-title
To use URL Rewriting to add a trailing slash to all RESTful URIs, create a .htaccess file in your website’s root folder (if it doesn’t exist yet), open it, and add this content:
<ifModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . / [L] RedirectMatch 301 (.*)/(.*).php/(.*)([^\/])$ $1/$2.php/$3$4/ </ifModule>
The RewriteEngine, RewriteBase, RewriteCond, and RewriteRule lines tell Apache to enable the Rewrite Module, set the base directory to the website’s root directory, and redirect all requests for non-existant files or directories to the website root directory.
The RedirectMatch line uses a regular expression (all mod_rewrite regular expressions have to be perl-compatible regular expressions) to break the URL into 4 sections, reassemble them, and redirect the browser to the reassembled URI via a 301 Redirect (which tells the browser and search engines that the page has moved permanently).
The first three sections mean “any characters repeated any amount of times” whereas the fourth section means “any single character except for a forward slash“.
So, if the URL was “http://www.geekology.co.za/blog/index.php/article/this-is-the-article-title/“, the sections would be:
$1: http://www.geekology.co.za/blog $2: index $3: article/this-is-the-article-title $4:
… and if the URL was “http://www.geekology.co.za/blog/index.php/article/this-is-the-article-title“, the sections would be:
$1: http://www.geekology.co.za/blog $2: index $3: article/this-is-the-article-titl $4: e
These four sections are then reassembled into “$1/$2.php/$3$4/“, which from both of the above examples translate to:
http://www.geekology.co.za/blog/index.php/article/this-is-the-article-title/
Related posts:
- Creating shortened URLs from the command line
- Validating and sanitizing URLs, Emails, and other inputs with PHP’s filter_* functions
- Changing the default MySQL root (or other user) password
- Using Regular Expressions – Part 2 of 3 – Regex in PHP
- Mac OS X Quick Tip: Using Spotlight to search from the command line



11 May 2009 








author
Thank you so much for writing this. You rock! I’m testing it out today
Sure thing! Let me know if you pick up any problems with it.