How to Redirect 404 Errors To Another Domain With .htaccess


redirect 404 errors-to another domain

When you move/delete a web page, it will give “404: Page not found” error messages unless you redirect them to their new location. Here’s how you can redirect 404 errors to another domain with .htaccess file in Apache.

 

 

How to Redirect 404 Errors To Another Domain With .htaccess

Here are the steps to redirect 404 errors to another domain with .htaccess. We will look at different use cases. Before we proceed, please ensure you have enabled .htaccess in Apache. Here are the steps to enable .htaccess (mod_rewrite) in Apache for :

  1. On Ubuntu
  2. On CentOS

Basically you need to add the following rule to your .htacess file, depending on your use cases, and restart Apache server to apply the changes. In the following examples, please replace the domain name (example.com) and URL strings (e.g /product-name) with your domain & URLs respectively.

 

Redirect Single URL to another domain

If you want to redirect only a single URL (e.g www.example.com/product-page) to another domain (e.g www.new-example.com/product-page), then add the following rule


Redirect 301 example.com/product-page new-example.com/product-page

 

If you want to redirect single URL (e.g www.example.com/old-url) to a new URL on another domain (e.g www.new-example.com/new-url), then add the following rule:


Redirect 301 example.com/old-url newexample.com/new-url

 

Redirect a Directory to another domain

If you want to redirect directory (e.g /blog) to another domain (e.g new-domain.com/blog) using .htaccess, paste the following command


RedirectMatch 301 ^/blog/(.*)$ http://new-domain.com/blog/$1

 

Using Redirect directive


Redirect 301 /blog http://www.new-domain.com/blog

 

Redirect All Pages to Another domain

If you have moved all your pages to another domain(e.g new-example.com), then add the following rules to your .htaccess file. This will redirect all error pages to new domain


RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://new-example.com/$1 [L,R=301,NC]

This will set up 301 redirect for your entire old domain

 

Using ErrorDocument Directive

Apache also provides an ErrorDocument directive that allows you to direct all 404 error pages to a specific page, such as your new domain’s home page


ErrorDocument 404 http://domainname.com

 

Restart Apache Server

Remember to restart Apache Server after you have made the changes


$ sudo systemctl restart apache2 [Ubuntu/Debian]
$ sudo systemctl restart httpd [RHEL/CentOS]

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!