Redirect if the URL does not match with .htaccess

301 redirect with Apache .htaccessThis blogpost will briefly explain how you can redirect your website if the domain name does (not) match a certain word or words.

For example: you want to redirect to and of course, because you take SEO into consideration, you want all of your pages to redirect from one domain to the other one with a 301 redirect.

In the root of the domain, edit (or create) the .htaccess file and paste the following code at the top of that file:

# enable mod_rewrite
RewriteEngine On
# check for the old domain
RewriteCond %{HTTP_HOST} ^old\.example\.com$ [NC]
# rewrite the URL
RewriteRule ^((?!Library).*)$$1 [R=301,L]

What happens here is these three things:

  • First, we enable the mod_rewrite engine for your Apache webserver
  • The rewrite happens only on one condition: if the HTTP host equals
  • If the above statement is true, we redirect (with a 301 redirect, great for search engines!) the user to the new domain, including what comes after the domain (e.g.

In Google Search Console, you can notify Gooogle of the address change. Open up the dashboard, go to the old domain you want to redirect to a new one. Then, go to settings and choose Change of Address.

GSC will guide you through these steps in order to successfully complete your domain name change from the old to the new (redirected) domain:

  1. Pick your new site from the list: Choose the new domain ( or just
  2. Confirm that 301-redirects work properly: click check and let Google verify your old site properly redirects to the new one (you should be good to go if you followed the above guide, it uses the permanent 301 redirect).
  3. Check that verification methods are still present: again, click confirm here and ensure your new and old sites are properly verified before the move, and will remain so afterwards.
  4. Submit the change of address request: Transition your site indexing from to

If you followed all these steps, you successfully redirected a domain with a specific name in the URL, to the new domain! You are greeted with this  message on the dashboard upon completing the four steps:

Your request for a site move has succeeded.
If you believe this is an error, you can withdraw the request.


Author Bio

Thank you for your interest in my blog! On this miniblog, I write mostly short (technical) blog posts that might interest other people. Read more about me or feel free to contact me.


Leave a Reply

Your email address will not be published. Required fields are marked *