'Redirect all urls exactly, just change domain name

I have a website with roughly 1K URLs. The website is moving to a different domain name. The URLs will be the exact same though, otherwise. I'd like to incorporate an htaccess or some kind of rule that does a 301 redirect for all URLs in one fell swoop. It would essentially replace the domain name as a 301 redirect.

Example:

  • Current URL: domain.example/blog/post-1.html
  • Redirect To: newdomain.example/blog/post-1.html

And that performed as a 301 redirect. How would I do that?



Solution 1:[1]

When moving a domain name to a new domain where the only change to the url is the domain name, I use the following redirect in my Apache .htaccess file

  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^domain.example$ [OR]
  RewriteCond %{HTTP_HOST} ^www.domain.example$
  RewriteRule ^(.*)$ http://newdomain.example$1 [R=301,L]

This ensures that all links in the old site are redirected and search engines like Google, Bing etc. are aware that the domain was permanently moved. This has the benefit that any ranking from domain.com is transferred to newdomain.example. Make sure not to include a / after the domain in the rewrite rule or it will double-up.

This is an alternative to the method shown above.

Solution 2:[2]

With www or without

RewriteEngine On
    
RewriteCond %{HTTP_HOST} (w*)domain\.example$ [NC]
RewriteRule ^ http://newdomain.example%{REQUEST_URI} [L,R=301]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephen Ostermiller
Solution 2 Stephen Ostermiller