How to Redirect a Directory Using Htaccess

There is occassion where you want to do a silent redirect (not a 301 redirect) from a directory to another directory.
Doing silent redirect will make browser to assume that this redirection is a brand new URL, not like 301 redirect which tells browser to open (redirected to) another URL.

We can use htaccess to do this 🙂

First, make sure your web server supports mod_rewrite.
Second, create a .htaccess file, or update your .htaccess file if you have had it.
Third, add these lines :

<IfModule mod_rewrite.c>
	RewriteEngine on

	RewriteCond %{REQUEST_FILENAME} !-f
	RewriteCond %{REQUEST_FILENAME} !-d
	RewriteRule ^(hello|you)([a-z0-9]+)\/([a-z0-9\-\_]+)\.(bmp|gif|jpe|jpeg|jpg|png)$ images/$3.$4 [NC,QSA,L]
</IfModule>

The code above will rewrite all requests to :

  • hello* , and
  • you*

To /images/

So these requests :

  • http://example.com/helloworld/logo.jpg
  • http://example.com/helloboys/logo.jpg
  • http://example.com/youarehandsome/logo.jpg

Will be redirected to http://example.com/images/logo.jpg 🙂

Leave a comment

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