mod_rewrite删除.php无效

时间:2011-06-21 05:03:18

标签: apache mod-rewrite

RewriteEngine on
RewriteCond %{http_HOST} ^domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

第一条规则正在运行,因此它正确地重定向浏览器。但是,第二个应该剥离.php的规则,以便访问者可以访问domain.com/services而不是domain.com/services.php。第三个添加/到最后的条件是有效的。

任何想法为什么剥离.php给我一个404错误:

The requested URL /s/p/domain.com/public/packing-tips.php was not found on this server?

有什么建议吗?

4 个答案:

答案 0 :(得分:0)

亲爱的尝试:

 RewriteRule ^([^/]+)/$1
希望能帮助你。

答案 1 :(得分:0)

请尝试删除此行并再次检查:

RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php

答案 2 :(得分:0)

要剥离.php扩展名,请使用此.htaccess代码:

Options +FollowSymlinks -MultiViews
RewriteEngine on

RewriteCond %{THE_REQUEST} ^GET\s.+\.php [NC]
RewriteRule ^(.+)\.php$ /$1 [NE,R=301,L,NC]

RewriteCond %{REQUEST_URI} !\.php$ [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php [L]

答案 3 :(得分:0)

RewriteEngine on
# force canonical name
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,QSA]

# Add .php to requested resource (if such php file does exist)
# e.g. www.example.com/services/ => www.example.com/services.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)/$ /$1.php [QSA,L]

# Force trailing slash to be present (only if such file does not exist)
# e.g. www.example.com/services => www.example.com/services/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*[^/])$ /$1/ [R=301,QSA]

如果您请求此网址domain.com/services,如果此类文件/文件夹不存在,则会将其重定向到domain.com/services/。然后,如果(仅)如果domain.com/services.php确实存在,则将其重写为domain.com/services.php。如果没有这样的php文件,那么你应该看到404错误。

理论上你可以在“强制规范名称”规则之后添加这些行,然后你可以在以后删除一些RewriteCond规则(如果你有相当多的重写规则很有用),但你必须在你的网站上验证这一点 - - 它对我来说很好,但你可能有特定的情况:

# Do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]