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

2019-08-02 17:22发布

问题:

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]