使用常量查询字符串的所有.php页面重写规则


RewriteRule for all .php pages with constant querystring

我正在处理一个项目,所有页面都需要有一个查询字符串假定的id。 例如以下页面:

  1. example.com/alfa.php?id=1
  2. example.com/beta.php?id=30
  3. exapmle.com/gamma.php?id=50

我使用以下 .htaccess 来使我的 URL 美观。

RewriteEngine On
## BEAUTIFUL URL
DirectoryIndex default.php
Options -Multiviews -Indexes +FollowSymLinks
#RewriteBase /
DirectorySlash off
# remove trailing slash
RewriteRule ^(.*)'/('?.*)?$ $1$2 [R=301,L]
# rewrite /dir/file?query to /dir/file.php?query
RewriteRule ^(['w'/-]+)('?.*)?$ $1.php$2 [L,T=application/x-httpd-php]

此代码将进行以下转换:

example.com/alfa.php?id=1 to example.com/alfa?id=1

假设 X.php 每次都在变化 (X),但 id 始终是恒定的,.htaccess 文件的最佳内容是什么?

我尝试了几种方法,但是什么是最好的?

还有一件事,如何将 URL 转换为 example.com/alfa/1example.com/beta/30

您正在尝试与规则正则表达式模式中的查询字符串(?之后的所有内容)进行匹配。查询字符串不是该匹配项的一部分,只是 URI。但是,由于您不希望触摸查询字符串,因此不要与它匹配,因为它会自动附加:

RewriteEngine On
## BEAUTIFUL URL
DirectoryIndex default.php
Options -Multiviews -Indexes +FollowSymLinks
#RewriteBase /
DirectorySlash off
# remove trailing slash
RewriteRule ^(.*)'/$ $1 [R=301,L]
# rewrite /dir/file?query to /dir/file.php?query
RewriteRule ^(['w/-]+)$ $1.php [L,T=application/x-httpd-php]

对于example.com/alfa/1example.com/beta/30

RewriteCond %{THE_REQUEST} [A-Z]{3,9}' /(['w/-]+)('.php)?'?id=([0-9]+)
RewriteRule ^ /%1/%3 [L,R=301]
RewriteRule ^(['w/-]+?)/([0-9]+)$ $1.php?id=$2 [L,QSA,T=application/x-httpd-php]

您可以尝试做的其他事情是摆脱您的规则并仅使用 Multiviews ,您已经关闭了。 多视图和mod_negotiation就是为这样的东西而制作的。