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

Correct way to redirect multiple domains on one host - NGINX

· 52CE 我爱测

In this example I have 4 websites on 2 different CMS's and 5 different domains. a.com sub.a.com b.com c.com are on CMS1 d.com is on CMS2 http should redirect to https a.com www.a.com www.sub.a.com to sub.a.com www.b.com to b.com …

问题原文

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

In this example I have 4 websites on 2 different CMS's and 5 different domains.

a.com sub.a.com b.com c.com are on CMS1
d.com is on CMS2

http should redirect to https
a.com www.a.com www.sub.a.com to sub.a.com
www.b.com to b.com
www.c.com to c.com
www.d.com to d.com

Each domain has their own separate website which is handled by their common CMS. For example, this means that even though b.com and c.com use the same CMS, admin panel and root directory; the pages which are served frontend are completely different. This functionality is handled by the CMS.

Due to this configuration I have 2 .conf files for NGINX, one for domains a-c and one for d.

Here comes the problem. Below is what I have come up with so far but doesn't work the way I have outlined above. Domains www.a.com-www.c.com seem to all redirect to sub.a.com. www.sub.a.com doesn't redirect to sub.a.com. Am I looking at this all wrong?

a.com.conf

server {
  listen 80;
  server_name a.com www.a.com sub.a.com www.sub.a.com b.com www.b.com c.com www.c.dom;
  return 301 https://$server_name$request_uri;
}

server {
  listen 443 ssl;
  server_name www.a.com www.sub.a.com;
  return 301 https://sub.a.com$request_uri;
}

server {
  listen 443 ssl;
  server_name www.b.com;
  return 301 https://b.com$request_uri;
}

server {
  listen 443 ssl;
  server_name www.c.com;
  return 301 https://c.com$request_uri;
}

server {
  listen 443 ssl;
  server_name a.com sub.a.com b.com c.com;
  root /srv/a.com/www;
  include snippets/ssl-a.com.conf;
  include snippets/ssl-params.conf;
  # REST OF CONFIG
}

d.com.conf

server {
  listen 80;
  server_name d.com www.d.com;
  return 301 https://$server_name$request_uri;
}

server {
  listen 443 ssl;
  server_name www.d.com;
  return 301 https://d.com$request_uri;
}

server {
  listen 443 ssl;
  server_name d.com;
  root /srv/d.com/www;
  include snippets/ssl-d.com.conf;
  include snippets/ssl-params.conf;
  # REST OF CONFIG
}

社区高分解答

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

You should use $host rather than $server_name if you want nginx to pick the name that was used to make the request. See this document for more.

For example:

server {
    listen 80;
    server_name a.com www.a.com sub.a.com www.sub.a.com b.com www.b.com c.com www.c.dom;
    return 301 https://$host$request_uri;
}

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

资料来源与适用范围

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

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

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