我正在尝试使用
.htaccess
文件来重定向对 http://example.org/folder/folder/index.php?with=parameters
的请求,
到 http://example.org/index.php?with=parameters
- 从请求网址中删除 folder/folder/
部分。
为了测试我的
.htaccess
文件,我在 example
文件夹中创建了一个 C:\xampp\htdocs
文件夹,其中包含一个仅回显请求 url 的 index.php
文件和一个如下所示的 .htaccess
文件:
RewriteEngine on
RewriteRule ^folder/folder/index\.php(.*) index.php$1 [R=301,L]
如果我现在去
http://localhost/example/folder/folder/index.php?with=parameters
它会重定向到不存在的网址http://localhost/C:/xampp/htdocs/example/index.php?with=parameters
(禁止)。
因此它删除了
folder/folder/
部分,但将 C:/xampp/htdocs/
添加到了网址中。
如何去掉新网址中多余的
C:/xampp/htdocs/
?
抱歉,但这不是捕获请求参数的方式。这里关于 SO 的所有现有答案以及文档都证明了以下内容:
直接:
RewriteEngine on
RewriteRule ^folder/folder/index\.php$ index.php?%{QUERY_STRING} [R=301,L]
或者间接,如果您想操作或过滤查询参数:
RewriteEngine on
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^folder/folder/index\.php$ index.php?%1 [R=301,L]
RewriteRule ^folder/folder/index\.php(.*) index.php$1 [R=301,L]
如果我现在转到
,它会重定向到不存在的网址http://localhost/example/folder/folder/index.php?with=parameters
(禁止)。http://localhost/C:/xampp/htdocs/example/index.php?with=parameters
这是因为 relative 替换字符串 (
index.php$1
) - RewriteRule
指令的第二个参数。它是相对,因为它不以斜杠开头(根相对,例如/index.php
)或不以方案+主机名开头(绝对,例如..https://example.com/...
)。在 .htaccess
中,relative 替换字符串被视为文件路径(而不是 URL 路径),因此 directory-prefix (即本例中的 C:/xampp/htdocs/
)被添加回末尾重写过程(内部重写所必需的) - 在触发外部重定向时暴露。
您基本上只需要一个斜杠前缀即可使其与根目录相关。例如。
/index.php
。
此外,您不需要对查询字符串(URL 参数)执行任何操作。默认情况下,这些会传递给替换。但是,重要的是,
RewriteRule
pattern仅与URL路径匹配,而不是查询字符串,因此您在pattern末尾捕获子模式(即
(.*)
)实际上并没有做任何事情.
所以,您所需要的只是以下内容:
RewriteRule ^folder/folder/index\.php$ /index.php [R=301,L]
请注意在 substitution 字符串上添加斜杠前缀。
原始请求中的查询字符串默认传递到 substitution 字符串。仅当您想以某种方式更改查询字符串(URL 参数)时,您才需要执行任何操作。
请注意,您需要清除浏览器(可能还有任何中间)缓存,因为错误的 301(永久)重定向将被浏览器永久缓存。您应该使用 302(临时)重定向进行测试以避免这些缓存问题。