Our .htaccess
2014 December 5Our 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:
- Emits a single 301 redirect (if necessary) to the canonical version of the resource.
- Only works if you have “honest” folders and files that will pass the
-f
and-d
tests, which will probably only be the case if you’re using a static site generator like Jekyll. - Only makes sense if you’re serving extensionless HTML files under the hood, meaning a request for
/somefolder/foo
needs to map to the HTML filefoo
(with no extension) in the folder/somefolder/
. - Assumes a Directory/.htaccess context and uses as much hard-coding as possible.
- The second rule—adding a trailing slash to requests when the request is for a folder—would normally be handled by mod_dir, but the second rule also implicitly trims the “www”. Adding the trailing slash ourselves ensures everything happens in a single redirect.
The overall scheme looks like this:
Requests for… | Redirect to… |
---|---|
www.ctw.com | ctw.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/archives | ctw.com/archives/ |
ctw.com/archives | ctw.com/archives/ |
And of course, canonical requests don’t get redirected at all:
Requests for… | Redirect to… |
---|---|
ctw.com | 200 OK |
ctw.com/blah/post-title | 200 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