.htaccess RewriteRule 查询字符串的路径

Geo*_*ith 3 .htaccess mod-rewrite

我正在尝试实现这样的网址

example.com/path1到example.com/index.php?p1=path1

example.com/path1/path2到example.com/index.php?p1=path1 & p2 = path2

在我的 .htaccess 中我有:

RewriteEngine On

RewriteRule ^(.*)/(.*)$ /index.php?c=$1&g=$2 [NC,L]

RewriteRule ^([a-zA-Z0-9-_]+)$ /index.php?g=$1 [NC,L]

对于example.com/path1/path2的情况,它效果很好,但对于example.com/path1的情况,只有在 url 中没有点的情况下才有效。例如,我想要 example.com/mydomain.com 工作到 example.com/index.php?g=domain.com 但我无法使其工作。

你能帮我解决这个问题吗?

小智 7

这是我处理这个问题的方法:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1
Run Code Online (Sandbox Code Playgroud)

然后无论您使用什么服务器端语言,我都会使用 PHP 解析 $_GET['param']。

$params = explode('/', $_GET['params']);
Run Code Online (Sandbox Code Playgroud)

  • 实际上,您甚至不需要在重写时传递 `params` var,只需使用 `$_SERVER['REQUEST_URI']` 来获取它 - 这使得规则更加简洁 `RewriteRule 。/index.php [L,QSA]` (4认同)