May 25 2009

Using an .htaccess file to standardize your URL

Published by at 4:48 pm under Programming,Usability

When creating a new site it’s a good idea to standardize on your domain name (www or no www?) and to gracefully handle HTTPS/SSL requests (do you have an SSL site, or should you redirect users off of it?). It’s also a good idea to compress the text files your server returns (like HTML, CSS and JavaScript pages).

You can do all this with an .htaccess file.

The great power of .htaccess files is that they can include rewrite rules via Apache’s mod_rewrite module. There are loads of things rewrite rules can do, so we decided to create a standard file that would handle a few things:

  1. Redirect all HTTPS/SSL traffic to the same URL but to HTTP;
  2. Redirect all traffic without a “www” entered to the same URL but with a “www.” added; and,
  3. Compress all HTML, CSS and JavaScript files (to speed up website browsing).

The goal is that requests to:

https://example.com/some/page

will be gracefully redirected to

http://www.example.com/some/page

A clean, standard URL with no risk of SSL confusion.

The .htaccess file

# Standard .htaccess file
# - Compress text documents for speed
# - Rewrite https to http and no www to www

<IfModule mod_rewrite.c>
RewriteEngine on
# move off of https
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301]

#move to www if no www is entered
RewriteCond %{HTTP_HOST} !^(www\.).*
RewriteRule (.*) http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

# compress stuff for faster delivery
AddOutputFilterByType DEFLATE text/css text/javascript application/x-javascript text/html
Header append Vary User-Agent

No responses yet

Trackback URI | Comments RSS

Leave a Reply