Configuring Drupal Sites in Apache

Setting up Drupal as an Apache Virtual Host is not much more complex than configuring any other website. But my goal today was to get rid of a few niggles. I wanted to force all traffic to a single URL - for example, always load 'www.example.co.uk' rather than 'example.co.uk' or anotherexample.co.uk.

I'd also noticed that in some circumstances, the user was seeing a doubling up of forward slashes - for example, 'www.example.co.uk//' or 'www.example.co.uk//page-name'.
I've spent a while ironing these out, and thought I'd pass it on. The trick is to set up Apache rewrite rules correctly.

You'll need Apache's rewrite module enabled, but on Ubuntu that's as simple as:-
#> sudo a2enmod rewrite
#> sudo apache2ctl graceful

In your Virtual Host definition, set up any alias for any domains that you want Apache to handle for the site. Next, you'll need to check some conditions, and rewrite the hostname if they are tripped:
ServerName example.co.uk
ServerAlias www.example.co.uk example.com www.example.com

Now sort out your rewrite conditions and rules. These 3 lines in your virtual host definition should suffice:
#check the first condition - if the hostname isn't 'www.example.co.uk' (NC or 'no case', makes the condition case insensitive)
RewriteCond %{HTTP_HOST} !^www\.example\.co\.uk [NC]
#check a second condition - is the hostname empty?
RewriteCond %{HTTP_HOST} !^$
#if either of the above conditions are TRUE, Apache should rewrite the hostname to what we want.
#   'L', or 'last', stops any following rules being processed
#    'R=301' redirects to the new URL with a 'moved permanently' 301 code
#    'QSA' will add any existing querystring from the old URL to the new URL:
RewriteRule ^/(.*) http://www.example.co.uk/$1 [L,R=301,QSA]

And there you have it. Hope it helps!

Here's the Virtual Host definition in full:-

    ServerAdmin rod@example.co.uk
    ServerName example.co.uk
    ServerAlias www.example.co.uk example.com www.example.com
DocumentRoot /var/www/example/drupal
LogLevel warn
# force everyone to a single base URL, inc. 'www.', on a single domain
    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\.example\.co\.uk [NC]
    RewriteCond %{HTTP_HOST} !^$
    RewriteRule ^/(.*) http://example.co.uk/$1 [L,R=301,QSA]
ErrorLog /var/log/apache2/example.co.uk-error_log
    CustomLog /var/log/apache2/example.co.uk-access_log "combined"
    Options FollowSymLinks
    AllowOverride None
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    allow from all

Here's some extra homework for the keen or fool-hardy:

http://www.cheatography.com/davechild/cheat-sheets/mod-rewrite
http://httpd.apache.org/docs/2.0/misc/rewriteguide.html