Apache – Redirect non www to www using VirtualHost setting

We can use .htaccess to redirect http://example.com to http://www.example.com by using the rewrite engine. But i find another simple way to implement the redirection just by setting up a VirtualHost.

Assume you have the current VirtualHost setting as follow.

<VirtualHost *:80>
  ServerName www.example.com
  DocumentRoot /var/www/<webroot>/
  <Directory /var/www/<webroot>/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    Allow from all


You could setup a new VirtualHost as follow to redirect example.com to http://www.example.com.

<VirtualHost *:80>
  ServerAlias example.com
  RedirectMatch permanent ^/(.*) http://www.example.com/$1


Done =)

Reference: StackOverflow – apache redirect from non www to www

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.