htaccess重定向删除index.php

时间:2012-03-19 03:54:09

标签: php regex apache .htaccess mod-rewrite

我希望用户能够使用$_SERVER['PATH_INFO']作为占位符来处理哪个文件,并在地址栏中删除index.php

例如,我想将me.com/index.php/settings1作为me.com/settings1提供,等等,以便用户访问任何PATH_INFO。

我如何将其写为htaccess规则?我甚至不知道从哪里开始

如果有帮助,我正在使用hostgator的共享主机方案。

根据@EddyFreddy的建议,我尝试了在这个问题中提到的两种方法都没有运气。以下是目前文件的样子:

suPHP_ConfigPath /home/user/php.ini
    <Files php.ini>
        order allow,deny    
        deny from all   
    </Files>

RewriteEngine On
RewriteBase /   

RewriteCond %{HTTP_HOST} ^www.mysite.com$ [NC]
RewriteRule .? http://mysite.com%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L] # tried with and without the `?`

2 个答案:

答案 0 :(得分:8)

这可以通过mod_rewrite轻松处理。在DOCUMENT_ROOT:

下的.htaccess中使用此代码
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# external redirect from /index.php/foo to /foo/
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php(/[^\s\?]+)? [NC]
RewriteRule ^ %1/ [L,R]

# external redirect to add trailing slash
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+((?!.+/[\s\?])[^\s\?]+) [NC]
RewriteRule ^ %1/ [L,R]

# internal forward from /foo to /index.php/foo
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ index.php%{REQUEST_URI} [L,NC]

确认一切正常后,请将R更改为R=301

答案 1 :(得分:1)

经过长期评估后我发现,anubhava的版本在所有情况下对我都不起作用。所以我试过这个修改过的版本。它将处理现有dirs中的现有文件,并且不会产生双斜线。

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

###### Add trailing slash (optional) ######
RewriteCond %{REQUEST_URI} ^/[^\.]+[^/]$
RewriteRule ^(.*)$ $1/ [R=301,L]

###### external redirect from /index.php/foo to /foo ######
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php(/.+)?[\s\?] [NC]
RewriteRule ^ %1 [L,R=301]

###### internal forward from /foo to /index.php/foo ######
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ index.php%{REQUEST_URI} [L]