Redirect an old domain while keeping its page paths

Move an Apache-hosted domain to a fixed HTTPS destination, preserve useful URLs and test before making redirects permanent.

A domain move should send /about/ to the new /about/, not send every old link to the homepage. This works only where the path really has an equivalent on the destination site.

Apache: a rule for the old hostname only

In the old site's root .htaccess, before its CMS rules, use:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?old-example\.com$ [NC]
RewriteCond %{REQUEST_METHOD} ^(?:GET|HEAD)$
RewriteRule ^ https://new-example.com%{REQUEST_URI} [R=302,L]

Replace both example domains. The host condition prevents a loop if old and new domains share an application. The target hostname is fixed; the requested path and existing query string are retained. Restricting this example to GET/HEAD avoids pretending that an existing form, API or payment callback can safely move with the same rule.

Use 302 while checking, then 301 after approving the permanent mappings. Permanent redirects can be cached, so testing with 301 immediately makes mistakes harder to unwind. Apache must have mod_rewrite enabled and permit these directives in .htaccess.

The other half of a domain move

Keep HTTPS working on the old hostname too: a browser needs to complete that TLS connection before it can read the redirect. Check deep links, query strings, missing pages and both old host variants. Where paths changed, add specific mappings before the broad domain rule. Preserve mail and DNS records that are unrelated to the website.

Nginx does not read .htaccess. Use its server configuration—or your host's redirect facility—with the same explicit host, path and method decisions. Cloudflare rules likewise have their own syntax.

References: Apache redirect handling, rewrite conditions and Nginx return directives.

Original version19 February 2014

Kept here for reference and earlier links. The updated guide above is the recommended starting point; older code may depend on retired services or different software versions.

If you ever change your website URL/Domain, you will want to 301 your old address so that links remain intact that people may have bookmarked/saved, and to transfer the power from Google search results.

The easiest way to do this is with the .htaccess file:

The very simplest code that will 301 your whole site is as follows.


Redirect 301 / http://www.MyNewSite.com

However on shared hosting the above can play up sometimes, so I generally prefer the following as it is more declarative:


RewriteEngine on

RewriteCond %{HTTP_HOST} ^oldsiteaddress\.co\.uk$ [OR]
RewriteCond %{HTTP_HOST} ^www\.oldsiteaddress\.co\.uk$
RewriteRule ^(.*)$ "http\:\/\/www\.MyNewSite\.com\/$1" [R=301,L]

Keep exploring

A couple more useful notes.