大网数据广告活动
服务器运维问答

Nginx rewrite server name rule

· 52CE 我爱测

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 ^/(.*)…

问题原文

原帖链接 · 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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-03-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。