Code Like Clockwork - Elegant, dependable, efficient online services.

How to use ModRewrite and .htaccess to add trailing slashes to all URIs and URLs

11 May 2009

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/
Do you like this? Share it:

Copyright © Geekology 2012. All Rights Reserved.