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

Nginx redirect wildcard subdomain with www prefix to non-www wildcard subdomain

· 52CE 我爱测

If you're serving an application at *.example.tld , how would you set it up so that http and https traffic for www.*.example.tld gets redirected correctly to *.example.tld ? Current nginx config looks like: server { listen 80; li…

问题原文

原帖链接 · Chris G. · CC BY-SA 4.0

If you're serving an application at *.example.tld, how would you set it up so that http and https traffic for www.*.example.tld gets redirected correctly to *.example.tld?

Current nginx config looks like:

server {
    listen 80;
    listen [::]:80;
    server_name *.example.tld;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name *.example.tld;

    #ssl stuff ...
    #location stuff...
}

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

You will need to use a regular expression server_name to capture the part of the domain name following the www. prefix. From this document you will notice that wildcard server_name statements are higher precedence, which means that they do not mix well with regular expressions.

The order of server blocks with regular expression server_name statements is significant, as they are evaluated in order until a match is found.

There are a number of ways to organise this, depending on how strict you need it to be and whether this IP address only needs to handle *.example.com.

The following example does not include any SSL configuration statements.

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name  ~^www\.(?<domain>.+)$;
    return 301 https://$domain$request_uri;
}
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    return 301 https://$host$request_uri;
}
server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    return 301 https://example.com$request_uri;
}
server {
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name  ~(^|\.)example\.com$;

    #ssl stuff ...
    #location stuff...
}

The first block matches any domain beginning with www. and redirects to the same domain without the www. prefix.

The second block is a generic http to https redirection.

The third block is probably unnecessary as it only matches domains that are not *.example.com.

The final block matches example.com and anything that ends with .example.com which has not already matched the first block.

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

资料来源与适用范围

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

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

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