Redirect an entire site with .htaccess but exclude one or more directories

Thoughts from the team
By    | January 9, 2012 | Code Snippets,

We recently wanted to move a website to a new domain and automatically send visitors and Googlebot to the new content, but certain resources had to remain on the current domain.  This meant we needed to redirect all requests to the site, except for the contents of a couple of directories, to a new domain.  After some head scratching we decided the simplest answer was a RewriteRule in our .htaccess file.

We used the following mod_rewrite rule:

RewriteEngine on
RewriteCond %{REQUEST_URI}!^/test/
RewriteCond %{REQUEST_URI}!^/my-folder/
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

This redirects (permanently with a 301 redirect) all traffic to the site to http://www.newdomain.com, except requests to resources in the /test and /my-folder directories.  We transfer the user to the exact resource they requested by using the (.*) capture group and then including $1 in the new URL.

More like this