Redirect all but selected sub-directories using .htaccess rules

I have an old website which is almost defunct, and I wanted to redirect all the traffic from it to my new website – APART from a few selected directories. This is how I managed to get the redirects working using a .htaccess file.

For this example the directory containing the material that I don’t want to redirect is called ‘goodstuff’. The RewriteCond conditions are setting up the excluded directories (the exclamation mark means ‘not’).

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/goodstuff/.*
RewriteCond %{REQUEST_URI} !^/goodstuff$
RewriteRule .* [R=301,L]

The reason I have two RewriteCond lines is because the web address could either be written with the trailing slash or without. E.g. goodstuff/ and goodstuff are the same, but I use two lines to cope with both cases.

The first RewriteCond matches all files and folders within this directory. The second is only matching the directory name without the trailing slash added.

The RewriteRule is telling the web server where to redirect the traffic to. The traffic is being redirected permanently (301 code), and the L states that this is the final rule for anything that matches our conditions.

Here’s another way of doing it which works, but it isn’t as precise. It redirects all addresses which start with ‘goodstuff’. This means it would match all the files that the first example matched. But it could match others as well.

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/goodstuff.*
RewriteRule .* [R=301,L] 

As well as matching a /goodstuff and /goodstuff/ directory, it could also match a /goodstuffhere/ directory, and a /goodstufffile.html.

3 Comments on “Redirect all but selected sub-directories using .htaccess rules”

Leave a Reply

Your email address will not be published. Required fields are marked *

Do NOT fill this !