Wednesday, January 26, 2011

How to rewrite index.php (and other valid default files) to the document root using mod_rewrite?

Hello,

I would like to redirect index.php, as well as any other valid default file (e.g. index.html, index.asp, etc.) to the document root (which contains index.php) with something like this:

RewriteRule ^index\.(php|htm|html|asp|cfm|shtml|shtm)/?$ / [NC,L]

However, this is of course giving me an infinite redirect loop. What's the right way to do this?

If possible, I'd like to have this work in both the development and production environment, so I don't want to specify an explicit url like http://www.mysite.com/ as the target.

Thanks!

  • I think something like this should work. Running off to a meeting, so i don't have time to test it, but basically you have to set condition not to redirect main www.site.com/index.php

    RewriteEngine On
    RewriteCond !^/index.php
    RewriteRule ^index\.(php|htm|html|asp|cfm|shtml|shtm)/?$ / [NC,L]
    
    TMG : @solefald - Thanks for the shot, that still doesn't seem to work. (I get a server 500 error with the following: RewriteCond !^index.php RewriteRule ^index\.(php|htm|html|asp|cfm|shtml|shtm)/?$ /ri2/ [NC,L] (/ri2 is my development directory). I also tried escaping the . and using ^/index\.php but still get 500. Also, how would I rewrite for index.php itself? Thanks for any advice.
    solefald : Try adding `$1` after `/ri2/`. `RewriteRule ^index\.(php|htm|html|asp|cfm|shtml|shtm)?$ /ri2/$1`. Also you may want to enable mod_rewrite logging, but it wont work out of .htaccess, you need to put it into `httpd.conf` or whatever config your apache is using. `RewriteEngine on RewriteLog /tmp/rewrite.log RewriteLogLevel 3`
    From solefald
  • You can try 301 redirecting it. This should be theoretically search engine friendly.

    RewriteRule ^index\.(php|htm|html|asp|cfm|shtml|shtm)/?$ / [R=301,L]
    
    TMG : Well, I don't know very much about server configuration (that's why I need you guys), but I do know SEO. Your statement is inaccurate; 301s DO LOSE PR: (see matt cutts interview with Eric Enge 1/25/10: "There is some loss of PR through a 301". http://www.stonetemple.com/articles/interview-matt-cutts-012510.shtml)
    Karol Piczak : Probably not all Google employees are unanimous (http://tinyurl.com/adam-lasnik-on-301) ;-) But I'm not a SEO specialist, so I won't argue here. The point is - even if you lose some PR (it's same domain here, so I'm not sure if that's what Eric meant), what's the correct way to do it? I supposed your goal is to redirect all requests to root - not to allow access to the main page through .htm/.html/... (duplicate content?). Maybe I misunderstood you here.

0 comments:

Post a Comment