How to exclude a sub directory from .htaccess 301 redirects

So, here’s something that comes up all the time – you have a sub-directory you want to exclude from a global .htaccess redirect. Often this is due to installing another application within the document-relative paths of an existing website or web application.

e.g.

  • You want to install a copy of WordPress within an existing Drupal website.
  • or maybe you have an application framework like Cake PHP and you need to exclude a directory from the error handling that occurs across all 404s.

There’s a really easy way to do this if all you need to do is exclude a single directory while globally redirecting all other pages.

RewriteEngine on
RewriteRule !^your-directory($|/) http://www.domain.com%{REQUEST_URI} [L,R=301]

Anything that matches the sub-directory /your-directory/ gets redirected to the domain.com example – while all other REQUEST_URI go to the equivalent on the re-directed domain.

REQUEST_URI stands for “Uniform Resource Identifier” and is in almost every case you will deal with under “normal” circumstances a web url and follows the standard syntax rules of Web URLs.

How to exlude a directory or sub-directory for Drupal’s .htaccess

To exclude a directory from being processed under Drupal’s .htaccess rulesets first locate the following lines in your default Drupal .htaccess file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

The above conditions direct that all URLs are to be rewritten except for existing files, directories and /favicon.ico – which is just the standard favicon that appears in your browser or when you bookmark the site.

To exclude a sub-directory from being processed you just add in a REQUEST_URI for the directory you want to exlucde.

Again, in our example we would like to exclude the /your-directory/ example. To do so you would want to change your code like so:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} !^/your-directory/.*$
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Stay tuned for more complex .htaccess / 301 redirects and rewrites for WordPress, CAKE PHP, Joomla! and more.

 

Want to discuss a project?

  • This field is for validation purposes and should be left unchanged.