我想转换这个url:
module-apple-get.html?term=st
至
file.php?module=apple&func=get&term=st
我在.htaccess文件中写了这段代码:
RewriteRule ^module-apple-get.html?term=([^-]+)$ file.php?module=apple&func=get&term=$1 [L,NC,NS]
但它不起作用。它错了吗?
RewriteRule
指令不能直接与查询字符串一起工作,因此您的规则永远不会工作。
以下是几种方法。
1(如果请求/module-apple-get.html
,这将进行重写,并将现有查询字符串附加到新URL。这意味着,如果您请求/module-apple-get.html?term=st&some=another_param
,它将被重写为file.php?module=apple&func=get&term=st&some=another_param
。这是一种更安全且值得推荐的方法。
RewriteRule ^module-apple-get.html$ file.php?module=apple&func=get [QSA,L]
2(另一种方法是仅在请求的URL具有term=st
PRESENT:时重写
RewriteCond %{QUERY_STRING} (^|&)term=st
RewriteRule ^module-apple-get.html$ file.php?module=apple&func=get&term=st [L]
如果您请求/module-apple-get.html?term=st
,它将重写,但如果您请求/module-apple-get.html?some=another_param
,它将不执行任何操作。
3(另一种方法是只有在整个请求的URL匹配时才重写:
RewriteCond %{QUERY_STRING} ^term=st$
RewriteRule ^module-apple-get.html$ file.php?module=apple&func=get&term=st [L]
如果您请求/module-apple-get.html?term=st
,它将重写,但如果您请求/module-apple-get.html?term=st&some=another_param
,它将不执行任何操作。
p.S.
- 如果需要,您可以添加任何其他标志(
[NC]
、[NS]
等( - 您可能需要在
file.php
之前添加前导斜杠/
(取决于您的设置、.htaccess的位置等(