Our .htaccess

2014 December 5

Our current .htaccess setup to redirect to the non-“www” version of the resource while adding or removing a trailing slash:

# Remove the trailing slash (from files only) and trim "www"
# http://www.ctw.com/archives/some-post/ becomes 
# http://ctw.com/archives/some-post
RewriteCond %{REQUEST_FILENAME} '-f'
RewriteRule ^(.*)/$ http://codingthewheel.com/$1 [R=301,L]
# Add the trailing slash (for folders only) and trim "www"
# http://www.ctw.com/archives becomes
# http://ctw.com/archives/
RewriteCond %{REQUEST_FILENAME} '-d'
RewriteRule ^(.*[^/])$ http://codingthewheel.com/$1/ [R=301,L]
# Categorically remove "www"
RewriteCond %{HTTP_HOST} ^www [NC]
RewriteRule ^(.*)$ http://codingthewheel.com/$1 [R=301]

Notes:

The overall scheme looks like this:

Requests for…Redirect to…
www.ctw.comctw.com
www.ctw.com/blah/post-title/ctw.com/blah/post-title
ctw.com/blah/post-title/ctw.com/blah/post-title
www.ctw.com/archives/ctw.com/archives/
www.ctw.com/archivesctw.com/archives/
ctw.com/archivesctw.com/archives/

And of course, canonical requests don’t get redirected at all:

Requests for…Redirect to…
ctw.com200 OK
ctw.com/blah/post-title200 OK
ctw.com/archives/200 OK

Being master programmers, it usually only takes us a few dozen revisions and definitely no more than 60 to 120 hours of nail-biting pain and frustration to get a simple trailing-slash non-www redirect nailed down properly with mod_rewrite. At six revisions and counting I’d say we’re well ahead of schedule.

Leave a comment