I was decommissioning an old server the other day, and in the process of moving the system to a new server I learned that the old domain was in fact one that we didn’t directly control. In other words, time to enforce a new domain on our clients! Of course, getting anyone to change URLs or domains on their personal machines is never an easy thing, so of course there has to be a small period of playing nice, in which you need to seamlessly redirect from one domain to the other. In other words, if an old URL is oldserver.com/about/ then I want anyone hitting that URL to be redirected to the new URL at newserver.com/about/.

To do this on your LAMP server is pretty easy thanks to the powerful mod_rewrite Apache module. Simply open up your relevant vhost declaration file in /etc/apache2/sites-available and add the following to the bottom of it (obviously using your own domains in place of the sample ones):

<IfModule mod_rewrite.c>
rewriteEngine on
rewriteCond %{HTTP_HOST} ^oldserver.com$
rewriteRule ^(.*) http://newserver.com$1 [L,R=301]
</IfModule>

Reload your apache configuration with

sudo service apache2 reload

and try to hit “oldserver.com/about” now.

Works well, doesn’t it? (And it wasn’t even difficult to do!)

apache-logo-banner

[UPDATE: Lately I’ve switch to placing this in the virtual host file:]

<VirtualHost *:80>
Options +FollowSymLinks
RewriteEngine on
RewriteRule .? http://newserver.com%{REQUEST_URI} [L,R=301]
....