.htaccess重写帮助,从URL中删除.php

时间:2013-11-08 18:37:49

标签: php regex apache .htaccess mod-rewrite

我的mod_rewrite没有遇到另一个问题,首先,时间是我的.htaccess文件:

Options +FollowSymlinks
RewriteEngine on

RewriteRule ^news/([0-9]+)/?$ /news?id=$1 [L,QSA]
RewriteRule ^contact/([0-9]+)/?$ /contact?do=$1 [L,QSA]
RewriteRule ^account/([a-zA-Z]+)/?$ /account?action=$1 [L,QSA]
RewriteRule ^admin/([a-zA-Z]+)/?$ /admin?action=$1 [L,QSA]
RewriteRule ^login/([a-zA-Z]+)/?$ /login?action=$1 [L,QSA]
RewriteRule ^register/([a-zA-Z]+)/?$ /register?action=$1 [L,QSA]


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L] <- This line doesn't work
RewriteRule ^([\w\d~%.:_\-]+)$ index.php?page=$1 [L,QSA]

所有行都在工作,除了 RewriteRule ^([^。] +)$ $ 1.php [NC,L] 当我使用这一行时,所有其他规则都会被中断。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要在有问题的规则中使用L标记。

要删除.php扩展名,这是更好的规则:

Options +FollowSymlinks -MultiViews

RewriteEngine on

## If the request is for a valid directory
RewriteCond %{REQUEST_FILENAME} -d [OR]
## If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} -f [OR]
## If the request is for a valid link
RewriteCond %{REQUEST_FILENAME} -l
## don't do anything
RewriteRule ^ - [L]

RewriteRule ^news/([0-9]+)/?$ /news?id=$1 [L,QSA]
RewriteRule ^contact/([0-9]+)/?$ /contact?do=$1 [L,QSA]
RewriteRule ^account/([a-zA-Z]+)/?$ /account?action=$1 [L,QSA]
RewriteRule ^admin/([a-zA-Z]+)/?$ /admin?action=$1 [L,QSA]
RewriteRule ^login/([a-zA-Z]+)/?$ /login?action=$1 [L,QSA]
RewriteRule ^register/([a-zA-Z]+)/?$ /register?action=$1 [L,QSA]

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

RewriteRule ^(.+?)/?$ index.php?page=$1 [L,QSA]

答案 1 :(得分:1)

尝试类似

的内容
#Preventing loop 
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]

RewriteCond %{REQUEST_URI} !^.+\.php.*$
RewriteRule .* - [L]

将此内容放在RewriteRule ^register/([a-zA-Z]+)/?$ /register?action=$1 [L,QSA]

之后