Apache: Simple way to Force a Domain Redirect Tips, Tricks and Tutorials 22 JUL 2014

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

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don’t have time for myself any more.