用于页面处理的重写规则,提供目标页面名称而不是请求



我有这个代码:

RewriteEngine on
RewriteRule api/v2/([^/]+)/?$ api/v2/api.php?request=$1 [L]
RewriteRule api/v2 api/v2/api.php [L]
RewriteRule ^$ handler.php?request=main [L]
RewriteRule ^(.*)$ handler.php?request=$1 [L]


...在我的根目录中的 .htaccess 文件中。其目的是用https://example.org/handler.php?request=hello/world重写https://example.org/hello/world

每当我导航到现有目录时,它都会在末尾添加?request。例如:如果我导航到https://example.org/foo(foo是一个目录(,它将重定向到https://example.org/foo/?request=foo

为什么会发生这种情况,我该如何解决?

更新 1
我添加了以下行,这些行根据需要工作:

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !(/$|.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]

但这又造成了另一个问题,当我去处理程序.php并回显$_GET["request"]时,我得到了handler.php

更新 2
我将.htaccess缩短为:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !(/$|.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]
RewriteRule ^(.*)$ handler.php?request=$1 [L]

但仍然有同样的问题,$_GET["request"]返回handler.php

更新 3
我为这个问题增加了一个赏金,更多的是出于好奇。

问题是您的规则正在循环模式下重写请求.php由于无条件规则和 catch-all 模式而重写目标文件处理程序

您需要修复规则的模式,使其与目标文件不匹配。

rewrite engine on
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !(/$|.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]
RewriteRule ^((?!handler.php).*)$ handler.php?request=$1 [L]

我会以相反的方法使用它。如果请求的文件不是现有文件或目录,则使用请求为处理程序文件设置重写规则。

测试了以下代码,它似乎有效。

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ handler.php?request=$1 [L]
</IfModule>

处理程序.php

var_dump($_GET);

http://localhost/hello/world

输出:

array(1) { ["request"]=> string(11) "hello/world" }

http://localhost/example(确实存在(

输出:

Directory parent

http://localhost/a.php(确实存在(

输出:

File a exists //Something that is written in a.php

相关内容

最新更新