How-To Redirect All Directories of oldsite to newsite in htaccess

By | 2013/04/30

Here is a quick tip to help redirect an existing url structure from an old domain to a new domain. Scenario is two domains are both pointed at same server and web root. Need to substitute old domain for new domain and keep all existing URL structure in tack.

Ex:

http://oldsite.com/stuff/ -> http://newsite.com/stuff
http://oldsite.com/stuff/and/stuff -> http://newsite.com/stuff/and/stuff


Here is an example mod_rewrite rule for .htaccess that will do the trick. The resulting redirects are 301 redirects (Moved Permanently).

RewriteEngine  On
RewriteBase   /
RewriteCond   %{HTTP_HOST} ^oldsite\.com [OR]
RewriteCond   %{HTTP_HOST} ^www\.oldsite\.com
RewriteRule   ^(.+[^/])$  http://www.newsite.com/$1/  [R]

Test with curl:

$ curl -v http://oldsite.com/this/directory/

* About to connect() to oldsite.com port 80 (#0)
*   Trying 192.168.1.205...
* connected
* Connected to oldsite.com (192.168.1.205) port 80 (#0)
> GET /this/directory/ HTTP/1.1
> User-Agent: curl/7.27.0
> Host: oldsite.com
> Accept: */*
> 
* additional stuff not fine transfer.c:1037: 0 0
* HTTP 1.1 or later with persistent connection, pipelining supported
< HTTP/1.1 301 Moved Permanently
< Date: Tue, 30 Apr 2013 17:34:31 GMT
< Server: Apache
< Location: http://newsite.com/this/directory/
< Content-Length: 295
< Connection: close
< Content-Type: text/html; charset=iso-8859-1
<