Redirect all urls exactly, just change domain name

With www or without

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

Place this redirect rule in your DOCUMENT_ROOT/.htaccess file of domain.example:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)?domain\.example$ [NC]
RewriteRule ^ http://newdomain.example%{REQUEST_URI} [L,R=301,NE]

Details:

  • Condition RewriteCond %{HTTP_HOST} ^(?:www\.)?domain\.example$ matches when host name in request is either www.domain.example or domain.example.
  • RewriteRule redirect all the URLs to newdomain.example with the URI exactly same as in the original request.
  • R=301 sets HTTP status code to 301 (permanent redirect)
  • NE is for no escaping to avoid encoding of special characters (if any) from original requests
  • L is for last rule

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.example 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.