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

Rewrite uri to remove www in nginx

· 52CE 我爱测

I have an unknown number of domains that match a pattern like www.abc123.example.com . Where the number after "abc" is unknown. I thought perhaps I could use a rewrite rule with the regex ~*(www\.abc\w+) Something like: server_na…

问题原文

原帖链接 · LK86 · CC BY-SA 4.0

I have an unknown number of domains that match a pattern like www.abc123.example.com. Where the number after "abc" is unknown. I thought perhaps I could use a rewrite rule with the regex ~*(www\.abc\w+)

Something like:

server_name ~*(www\.abc\w+)
rewrite ~*(www\.abc\w+)\.example\.com (abc\w+)\.example\.com;

Unfortunately, that does not seem to work, and the uri does not change. My other thoughts were perhaps attempting to set/rewrite the $uri value but I have been unsuccessful with that as well.

I am not sure if I am failing to match the uri value or failing to rewrite the uri (or both).

I was able to fine this:

if ($host ~* ^www\.(.*)) {       
set $host_without_www $1;
rewrite ^(.*) http://$host_without_www$1 permanent;
}

Unfortunately, that rewrites all 'www' traffic and not just www.abc123. Any help is appreciated. Thank you.

已采纳解答

原帖链接 · Tero Kilkanen · CC BY-SA 4.0

Try the following approach:

server {
    server_name ~ ^www\.(?<newdomain>abc[0-9]+\.example\.com)$;

    return 301 https://$newdomain$request_uri;
}

This will match domains www.abcN.example.com, where N is one or more digits. The regular expression will capture the part abcN.example.com into variable $newdomain.

Then in the return statement we build the destination URL using the variable captured earlier and the URI part of the request.

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

资料来源与适用范围

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

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

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