Concrete5 Mod Rewrite to Add Request Trailing Slash

I recently had the need to add a trailing slash to http requests in a Concrete5 application (that did not have pretty urls enabled).  The issue stemed from clients adding links that did not include the trailing slash.  In the interest of keeping things clean, here are the rules I wanted to follow:

  1. Only rewrite urls that contain index.php
  2. Only rewrite urls where the above is satisfied and is followed by at least 1 trailing slash
  3. Only rewrite urls where the above is satisfied and the url ends with at least one valid character (defined below)
  4. Only rewrite urls where the above is satisfield and does not already end with a trailing slash

Valid characters include: upper and lower a-z, 0-9, forward slashes, and underscores and dashes.  Here is what I came up with.  If you see a fault, or can improve what is here, please do so.

 
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # If the request contains index.php
    RewriteCond %{REQUEST_FILENAME} index.php

    # index.php must be preceeded by a forward slash
    # and one or more word characters including forward slashes and dashes
    # If the pattern contains questions marks, periods, etc, than this condition
    # will not be satisfied.  The pattern should not contain a trailing
    # forward slash
    RewriteCond %{REQUEST_URI} index\.php[\/]{1}[a-zA-Z0-9\/_-]+[^\/]$

    # Append a trailing forward slash to the request and redirect
    RewriteRule ^(.*)$ http://%{SERVER_NAME}/$1/ [L,R=301]
</IfModule>

1 Comment for "Concrete5 Mod Rewrite to Add Request Trailing Slash"

Comment 1 Jeffrey Brown - Gravatar Jeffrey Brown

Concrete5, love it

Sat, 24 Oct 2009 03:25:00 +0000 Link

Comments have been disabled for this post.