Need help with .htaccess redirection for WordPress websites

I am changing the domain of my website.

But, I am struggling with the domain redirection. I need to implement this wildcard redirection.

So that I visit.

https://www.oldomain.com/page1

It should go to

https://newdomain.com/page1

Note: The new domain is without www.

Can anyone help me how to implement this?

Go to Source
Author: Nirmal Kumar

ANSWER

A 301 Redirect, or permanent redirect, is recommended when dealing with something similar to this one.

If you just want to hard redirect anything hitting oldomain.com to newdomain.com then a simple Redirect should do like so:

<VirtualHost *:443>
	ServerName oldomain.com
        ServerAlias www.oldomain.com
	Redirect 301 / https://newdomain.com
</VirtualHost>

The above example is also something that you will want to write in a server config like httpd.conf but not in a .htaccess file somewhere on your site directory. It is also clumsy since your old site’s pages – e.g https://www.domain.com/some/page/123 – will redirect only to https://newdomain.com which is the index page of the site.

So the other option would be Rewrite. It is also in case you don’t have root access to the server, and/or other sites that are not yours are sharing it as well. It would look like the following:

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

The above considers whether the request is written with or without the www subdomain in it. The old links or pages will also get carried over to the new one.