Redirect One Directory To Another With .htaccess

19th May 2008 - 1 minute read time

To stop access to a directory (and anything in that directory) all you need is a simple RewriteRule.

  1. RewriteEngine on
  2. RewriteBase /
  3. RewriteRule ^exampledirectory/(.*)$ / [R=301,L]

In this example, if this .htaccess file resides in the root directory of the site and you try to access anything within /exampledirectory you will be redirected back to the root folder. To redirect to another folder (like anotherdirectory) on your web server use the following rule.

  1. RewriteEngine on
  2. RewriteBase /
  3. RewriteRule ^exampledirectory/(.*)$ /anotherdirectory [R=301,L]

Comments

Permalink
This helped me a lot. Thanks!

Infidel (Sun, 03/07/2010 - 19:12)

Permalink

I have a question
When a user opens the url www.domain.com/param
I want it redirected to www.domain.com?param while masking the new url (the URL address displayed remains unchanged)
So that instead of accessing param as a folder, it accesses it as a url GET parameter
Is that possible using .htaccess?
 

Eric (Wed, 09/08/2021 - 10:56)

Permalink

Hi Eric, I think what you want is possible, you need to rewrite the url from one form to the other.

If you look at systems like Drupal and WordPress you'll see that all of their traffic gets re-written by this rule.

  1. RewriteEngine on
  2. RewriteCond %{REQUEST_FILENAME} !-f
  3. RewriteCond %{REQUEST_FILENAME} !-d
  4. RewriteCond %{REQUEST_URI} !=/favicon.ico
  5. RewriteRule ^ index.php [L]

The !-f condition will trigger if the file being requested actually exists. The same thing applied for the !-d condition. Then, all traffic will be routed to the main index.php file, without redirecting away from the current path. You might need to make a couple of modifications to get what you want working, but this should cover most of it.

Add new comment

The content of this field is kept private and will not be shown publicly.