SEO Egghead by Jaimie Sirovich: A blog about SEO, written for nerds, by a nerd.

Choose a Topic:

» Suggest a topic or buzz to cover; if I write about it, you'll get credit with a link in the post!

Thu
31
Aug '06

ROTD: Mod_rewrite Rule To Remove Trailing "index.php"

This handy set of rules for mod_rewrite automatically redirects any URL ending in "/index.php" to the same URL ending in "/."  It works for the root directory as well as subdirectories.

RewriteCond %{THE_REQUEST} ^GET\ /.*/index\.(php|html)\ HTTP
RewriteRule (.*)index\.(php|html)$ /$1 [R=301,L]

For example, "http://www.example.com/subdirectory/index.php" would be redirected to "http://www.example.com/subdirectory/."

This eliminates one of the peskier canonicalization issues with relative ease.  It's a bit tricky because of the way mod_rewrite updates its variables during execution -- hence the odd use of the variable {THE_REQUEST}.  If anyone knows an easier way or finds a problem with it, leave a comment. 

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • Furl
  • Reddit
  E-Mail This Post/Page

4 Responses to “ROTD: Mod_rewrite Rule To Remove Trailing "index.php"”

  1. Gemme Says:

    Thankks. I have been looking for something like this for some time. I'll implement it and in case I run into any trouble, I'll let you know.

    Cheers

  2. esoos Says:

    Nice, I've been using something similar:

    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(([^/]+/)*)index\.html\ HTTP/
    RewriteRule index\.html$ http://www.domain.com/%1 [R=301,L]

    (hopefully that formats ok.) I think the one you have may be a bit better because it works for subdirectories and php files too.

  3. http://bonrouge.com/home php Says:

    Hello,

    I have a webpage : http://bonrouge.com/br.php?page=home

    I want it to be viewed as http://bonrouge.com/home php using the mod rewrite rule. I have tried both of the above codes, but to no avail.

  4. steve Says:

    This doesnt work for me.
    For example, "http://www.example.com/subdirectory/index.php" would be redirected to "http://www.example.com/."

    Everything gets redirected to / without the subdirectory. I'm using wamp 1.7.0.

Leave a Reply