How to redirect old domains to a new domain using htaccess

When you migrate a website to a new domain it’s important that you redirect the links that are active on your old domain. Not only does this have huge SEO benefits by retaining your page rankings and updating search engines but it also ensures that visitors to the old domain are forced to use the new domain.

These redirects can be easily achieved by adding a rule to the .htacccess file on your web server – this must be the web server that your old domain is hosted at.

Please note: this example assumes that your web server uses Apache and that you are simply redirecting from an old domain, for example olddomain.com to a new one, for example newdomain.com.

Add the following code to your .htaccess file at the root of your website (this must be the web server that your old domain is hosted at).

    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteCond %{HTTP_HOST} ^olddomain.com$ [OR]
      RewriteCond %{HTTP_HOST} ^www.olddomain.com$
      RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]
    </IfModule>

This rule will redirect all requests to the old domain to the new one, for example if a visitor attempts to open olddomain.com/content they will be redirected to newdomain.com/content.

 

What is and how do I edit the .htaccess file?

The .htaccess file contains directives (instructions) that tell the server how to behave in certain scenarios and directly affect how your website functions.

There are Many Ways to edit the .htaccess file, including:

  1. Edit the file on your computer and upload it to the server via FTP
  2. Use an FTP program’s Edit Mode
  3. Use SSH and a text editor
  4. Use the File Manager in cPanel

The fastest and easiest way to edit .htaccess for most people is to use the File Manager in cPanel. The steps below detail how to do this on a typical cPanel account, the images and steps may be different depending on your host and configuration.

 

  1. Log into your cPanel – if you are unsure how to do this your web host can provide instructions. Some web hosts provide access by adding /cpanel to your domain address, for example domain.com/cpanel
  2. Click on the ‘File Manager’ icon
  3. A pop up will open, ensure that the ‘Show Hidden Files (dotfiles) option is selected then click ‘Go’
  4. apache-redirectnonwww1
  5. Open the root WWW folder for your website. Typically this is the first folder level for the website.
  6. Look for a file titled ‘.htaccess’ . If it does not exist, create it. Note it must be called dot htaccess
  7. Open the .htaccess text file
  8. MAKE A BACKUP by copying the content to another location – misconfigurations can break your website
  9. Make the required changes to the htaccess file then click ‘Save’
  10. Reload your website testing that the change is working. Test a random sample of pages to ensure everything is functional
    .