删除. php并保留查询字符串


Remove .PHP and keep query string

我的代码:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example'.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteRule ^(.*).php(.*) $1$2 [NC]

我正在尝试使用它,所以

www.example.com/test.php?a=not&b=23

在url中显示为:

www.example.com/test?a=not&b=23

,也没有WWW重定向到WWW .

我的错误是: 404 not found. The URL /test not found on this server

任何想法?

您需要将标志QSA添加到rewriterrule指令中:

RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,QSA,L]

QSA代表"Query String Append"

RewriteRule ^(.*).php(.*) $1$2 [NC]

你有点搞反了。您的规则采用URL x.php并将其重写为x。而x不存在。

相反,您需要分两个阶段完成:

  1. x.php上,要求浏览器重新请求x(使用[R=301])。
  2. x重写为真实的URL x.php(就像你现在一样,但使用[QSA]而不是尝试自己匹配查询字符串)

所以,也许可以这样写:

# Force browser to use condensed URL form
# (and matches will not fall through to the next rule)
RewriteRule ^(.*)'.php$ http://www.example.com/$1 [R=301,QSA,L,NC]
# Make condensed URL form work
RewriteRule ^(.*)$ $1.php [QSA]

您的重写规则做的正好相反:当用户请求index.php时,他们将被重定向到index.

试试这样:

RewriteEngine On
Options +FollowSymLinks
# for the non-www to www
RewriteRule %{HTTP_HOST} !^www'.example'.com$ [NC]
RewriteRule ^ http://www.example.com/
# for the non-php to php (if no other file extension supplied)
RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteCond %{REQUEST_URI} !'.[A-Z]{3}$ [NC]
RewriteRule ^(.+)$ $1.php [R,L,QSA]