Configuring Drupal Sites in Apache

Rod Tatham's picture
Rod Tatham

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 '' rather than '' or

I'd also noticed that in some circumstances, the user was seeing a doubling up of forward slashes - for example, '' or ''.
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:

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 '' (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 ^/(.*)$1 [L,R=301,QSA]

And there you have it. Hope it helps!

Here's the Virtual Host definition in full:-

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 ^/(.*)$1 [L,R=301,QSA]
ErrorLog /var/log/apache2/
    CustomLog /var/log/apache2/ "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: