问题原文
原帖链接 · Eric Wu · CC BY-SA 4.0
If I want to do a rewite rule on nginx :
Visit http://*1.abc.com
* = any single character
will 301 redirect http//*9.abc.com
so I created the following config :
server {
listen 80 ;
server_name ~^(.+?)1\.abc\.com$;
rewrite ^/(.*) http://$19.abc.com permanent;
}
The URL will rewrite to : http//9.abc.com
Any idea?
已采纳解答
原帖链接 · Richard Smith · CC BY-SA 4.0
You have a numeric capture in the server_name statement and a numeric capture in the rewrite statement.
The variable $1 in the rewrite statement represents the value of the numeric capture from the regular expression in the same rewrite statement.
It is always the case that numeric captures are overwritten by the last regular expression to be evaluated.
You can use named captures where one or more regular expressions may be evaluated between the capture and where the value is evaluated. See this document for details.
For example:
server_name ~^(?<prefix>.+?)1\.example\.com$;
rewrite ^ "http://${prefix}9.example.com" permanent;
Or, you can avoid any intervening regular expressions by using a return statement, for example:
server_name ~^(.+?)1\.example\.com$;
return 301 "http://${1}9.example.com$is_args$args";
I prefer to use ${1} rather than $1 where the intent may be ambiguous. In which case the expressions will also need to be quoted. The $is_args$args appends the optional query string, which matches the behaviour of the original rewrite statement.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
