Monday, April 2, 2012

Permanent Redirect in Apache


If you would like to redirect all traffic to an apache web server to the server's FQDN, e.g. redirecting http://myserver/ to http://myserver.example.com, you can easily achieve this using a two VirtualHost entries in your Apache config file.

On Ubuntu, the file to edit is /etc/apache2/sites-enabled/000-default. Find your original declaration, and add a ServerName field with the server's FQDN (fully qualified domain name):


        ServerAdmin webmaster@localhost
        ServerName myserver.example.com
        # rest of real config



 Now create another VirtualHost entry below this one, with the local name of the server (e.g. myserver) and a Redirect statement that redirects to the FQDN:


        ServerName myserver
        Redirect permanent / http://myserver.example.com/


After applying these changes, restart apache using service apache2 restart. Now when visiting http://myserver you should be automatically redirected to http://myserver.example.com.