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

In nginx in which variable do I get the main domain

· 52CE 我爱测

I want to forward all these subdomains in any scheme to the respective main domain in https. I don't want to have several server directives. server { server_name *.autocosts.info *.autocouts.info *.autocostos.info *.autocosti.inf…

问题原文

原帖链接 · João Pimentel Ferreira · CC BY-SA 4.0

I want to forward all these subdomains in any scheme to the respective main domain in https. I don't want to have several server directives.

server {
    server_name *.autocosts.info
                *.autocouts.info
                *.autocostos.info
                *.autocosti.info
                *.autocustos.info
                *.autocosturi.info
                *.autokoszty.info;

    listen 80;
    listen 404;
    listen 443 ssl;

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

This does not seem to work. Does $host include subdomain? How can I get just the main domain (without subdomain)?

I know that I can get the main domain using server_name ~^(www\.)?(?<domain>.+)$; but that it is not restricted to the list of above domains.

已采纳解答

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

Regex to the rescue!

^(\*\.)?([a-z\d][a-z\d-]*[a-z\d]\.)(?<maindomain>auto[a-z\d-]*[a-z\d]\.info)+$

^(\*\.)?([a-z\d][a-z\d-]*[a-z\d]\.) matches subdomains.

?<maindomain> stores the naked domain in a variable called $maindomain

auto matches ‘auto’ which is present in all your domains.

[a-z\d-]*[a-z\d]\ matches the rest of your domain

\.info+ matches the .info part of your domains

(untested in nginx, but should work as regex).

Documentation used: from the nginx.org website

So lets fix your server block:

server {
    server_name  ~^(\*\.)?([a-z\d][a-z\d-]*[a-z\d]\.)(?<maindomain>auto[a-z\d-]*[a-z\d]\.info)+$;

    listen 80;
    listen 404;
    listen 443 ssl;

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

This produces the following result when accessing the site:

curl -I oi3j2.autocostos.info

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 17 Jul 2019 15:48:54 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive
Location: https://autocostos.info

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

资料来源与适用范围

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

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

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