如何强制将 get 参数添加到已经有 get 参数的 url? 例如:
对于像这样的url,它必须有一个参数,值无关紧要:
example.com/?a=value
像这样,值 2 硬编码:
example.com/?a=value&b=value2
我试过了,是的,它用于索引.php全部:
RewriteRule index.php/?a$ /index.php/?b=value2 [L,R,QSA]
RewriteRule index.php/?a$ /index.php/?b=value2 [L,R,QSA]
RewriteRule
模式(第一个参数(与查询字符串不匹配。如果特别需要检查查询字符串是否以a
参数开头,则需要一个单独的条件来检查QUERY_STRING
服务器变量。
假设您的URL实际上包含index.php
(您的示例不包含?(并且URL路径不以斜杠结尾(即包含路径信息(,那么您可以执行以下操作:
# Check that query string contains the "a" URL parameter anywhere
# but does not contain the "b" URL parameter already (avoid redirect loop)
RewriteCond %{QUERY_STRING} ba=
RewriteCond %{QUERY_STRING} !bb=
RewriteRule ^index.php$ /index.php?b=value2 [QSA,R,L]
b
匹配单词边界,因此a
只能在查询字符串的开头或 URL 参数的开头(&
之后(匹配。
QSA
标志从请求中追加(即合并(原始查询字符串。因此,它将从/index.php?a=value
重定向到/index.php?b=value2&a=value
- 请注意,将附加原始查询字符串。
如果您特别希望将 URL 参数保持原始顺序并将新值附加到末尾,则可以将RewriteRule
更改为以下内容:
RewriteRule ^index.php$ /index.php?%{QUERY_STRING}&b=value2 [R,L]
现在结果将是/index.php?a=value&b=value2
.