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

Nginx - listen on multiple domains, serve only some content on one domain

· 52CE 我爱测

I have a web application that serves 2 different domains, let's call them eu.example.com and us.example.com . I have set up nginx in front of the application, listening on both domains: server { listen 443 ssl; server_name eu.exa…

问题原文

原帖链接 · decibyte · CC BY-SA 3.0

I have a web application that serves 2 different domains, let's call them eu.example.com and us.example.com.

I have set up nginx in front of the application, listening on both domains:

server {
    listen 443 ssl;
    server_name eu.example.com us.example.com;

    ...
}

Now the US team decided they want to have a blog on us.example.com/blog, which should point to WordPress on another server.

I can achieve this by adding a new location directive to my nginx server configuration:

location /blog {
   proxy_pass https://us-wordpress.example.com/blog;
}

The problem is that the US blog is now also available from eu.example.com/blog. I tried wrapping it in an if:

location /blog {
   if ($hostname = us.example.com) {
       proxy_pass https://us-wordpress.example.com/blog;
   }
}

But then I get an error from nginx saying: "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block.

I could achieve the same by having separate server { ... } directives per domain, but that would be duplicating most of the configuration, and I'd prefer to avoid that.

Is there a way to achieve this in a sensible way?

已采纳解答

原帖链接 · Peter · CC BY-SA 3.0

You should achieve it like you said, with separate server blocks, and another included file for both servers to avoid duplication.

server{ 
    listen 443 ssl;
    server_name us.example.com;
    include commonfile;
    location /blog {
        ...
    }
}
server {
    listen 443 ssl;
    server_name eu.example.com;
    include commonfile;
}

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

资料来源与适用范围

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

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

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