Search code examples
regexapache.htaccesshttp-redirectmod-rewrite

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

  • 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