Apache rewrite string in URL - obstacle is “?” in query

我怕爱的太早我们不能终老 提交于 2019-12-24 07:36:14

问题


Want to rewrite an URL with a given user-prefix ("u-") from

https://example.com/access/check?user=u-abc&pass=123

to an URL without the prefix:

https://example.com/access/check?user=abc&pass=123

I tried several rules, e.g

RewriteBase /
RewriteRule ^access/check?user=u-(.*)$ check?user=$1

I am stuck with the "?"

IF the rewrite had to apply to slightly the same, but without the "?", it indeed works:

https://example.com/access/checkuser=u-abc&pass=123

RewriteRule ^access/checkuser=u-(.*)$ checkuser=$1

and provides the expected outcome (without the user-prefix "u-")

checkuser=abc&pass=123

I tried to match the "?" with [?] or \x3F, and applied the QSA flag as described on mod_rewrite.org , but still not succeeded.


回答1:


The query string is not part of the RewriteRule pattern

What is matched?

  • ...
  • If you wish to match against the hostname, port, or query string, use a RewriteCond with the %{HTTP_HOST}, %{SERVER_PORT}, or %{QUERY_STRING} variables respectively.

So in your case, you must check against QUERY_STRING and use the replacement %1 instead of $1

RewriteCond %{QUERY_STRING} user=u-(.*)
RewriteRule ^access/check$ /access/check?user=%1 [L]



回答2:


To match a "?" which is a query string, you need a RewriteCond, query strings can't be matched with a RewriteRule alone.

By definition a query string is everything after the "?", and you can use them in destination of a RewriteRule but to match them you will need a RewriteCond as I just mentioned.

Example:

RewriteCond %{QUERY_STRING} ^user=u-(.*)
RewriteRule ^access/check check?user=%1

Note captured groups from RewriteCond are referred to with the % symbol.

Play a bit with simple examples and try out.




回答3:


QueryString is not part of match in Rule's pattern, you need to match against %{QUERY_STRING} using RewriteCond

RewriteEngine on
RewriteCond %{QUERY_STRING} ^user=u-([^&]+)&pass=([^&]+)$
RewriteRule ^access/check/?$ /access/check/?user=%1&pass=%2 [L]


来源:https://stackoverflow.com/questions/42953057/apache-rewrite-string-in-url-obstacle-is-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!