My family has been buying Mac's since I no longer do their Windows tech support. Now I'm Apple Tech support. Can't win.

Redirect directory to index page

I was recently asked by a client to redirect all pages in a directory to the directory index page. They were ending a co-branding service with another company. What they wanted was to keep only a re-worked index page in the directory as being visible, but not show people who may have bookmarked other pages in this directory the 404 page.

I searched and searched Google for this and couldn’t find exactly how to do this via .htaccess anywhere. I found similar information, such as how to redirect from directory to directory, but not how to redirect all pages to just one page in the same directory. After some trial and many errors, I figured it out.

So here I post my .htaccess for posterity, and my own need. Hope this helps others as well.

RewriteEngine On
# don't redirect .css, .jpeg, .jpg, .png or .gif extensions
# the extensions are separated by a pipe ("|")
RewriteRule \.(css|jpe?g|png|gif)$ - [L]
# if the request isn't for index.php then
# redirect to index.php
RewriteRule !^index\.php$ /index.php [R=301,L]

**NOTE: if this is a temporary redirect, you can substitute this for the last line:

RewriteRule !^index\.php$ /index.php [L]

The line RewriteRule \.(css|jpe?g|png|gif)$ - [L] is used so that image and css calls are not redirected.

So basically this will take any page called for in http://www.example.com/something/ and redirect it to http://www.example.com/something/index.php as long as the .htaccess file is in the /something directory.

4 Responses to “Redirect directory to index page”

  1. OMG! You are sooooooooooooooo clever ToddStar 😀

  2. htaccess is like geek voodoo. Just when I think I get it, it sticks me in the leg with a long sharp pin.

  3. It usually sticks me in the eye.

  4. I removed a PHP photo gallery with several hundred photos from my site and moved the images to Picasa. After more than 6 months Google still lists my photos in searches, despite submitting updated sitemaps. This entry:

    RewriteEngine On
    RewriteRule !^index\.php$ /mynew_dir/fotos.html [L]

    in a recreated (but empty!) /gallery2/ directory effectively enabled me to redirect any call to a page in that directory to a static page in a differnet directory (which displays my album list). As it happens, calls to the gallery do not use index.php.

    Thanks for this article, Todd. It enabled me to work out what was needed.