When you own a website, changing domain can occur for various reasons: branding changes, shift in the activity, or legal reasons. If you have been running the website for a long time, it is a pretty big deal to change your domain name, as it can potentially make you lose some of your traffic if you don’t handle it properly.
In this small tutorial, I will explain you how to redirect to a new domain with a few simple lines of code in your .htaccess file.
For this tutorial, we will assume that your web host uses Apache, as most websites do. On Apache web servers, the .htaccess file is used for configuration purpose. In order to make changes, you will need to find the .htaccess file located at the root of your old domain.
In your .htaccess, we will then add the following code. You must customize the domaine names included in the example: yourolddomain.com should be replaced by the old domaine you were using, and yournewdomain.com should be replaced by the new one.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourolddomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.yourolddomain.com$
RewriteRule (.*)$ http://www.yournewdomain.com/$1 [R=301,L]
</IfModule>
This is enough to handle a regular redirect, assuming that you didn’t change the site structure and URLs. If you did change the URL structure, you will need to add more complex regular expressions that will not be covered here.