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

Redirect many domains to different locations of other domain with nginx without having to define many server blocks

· 52CE 我爱测

Say i have multiple variations on a domain name, one brandname registered at multiple top-level domains; and they all need to go to one specific domain + append a dedicated custom uri that relates to the originally requested doma…

问题原文

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

Say i have multiple variations on a domain name, one brandname registered at multiple top-level domains; and they all need to go to one specific domain + append a dedicated custom uri that relates to the originally requested domain.

For example i have:

  • domain.tld
  • domain.net
  • domain.org
  • domain.com

Where domain.com is the one where all requests need to land after appending an extra uri like this:

  • domain.com/tld
  • domain.com/net
  • domain.com/org

I came up with this working setup:

# (www.)domain.tld
server {

        listen 80;
        server_name domain.tld www.domain.tld;
        return 301 $scheme://www.domain.com/tld$request_uri;
}

# (www.)domain.net
server {

        listen 80;
        server_name domain.net www.domain.net;
        return 301 $scheme://www.domain.com/net$request_uri;
}

# (www.)domain.org
server {

        listen 80;
        server_name domain.org www.domain.org;
        return 301 $scheme://www.domain.com/org$request_uri;
}


# (www.)domain.com
server {

        listen 80;
        server_name domain.org www.domain.org;

        location / {
               proxy_set_header        Host $host;
               proxy_set_header        X-Real-IP $remote_addr;
               proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
               proxy_pass              http://backend.host:port;
          }

}

But the declaration of multiple server blocks, although logical, looks over-verbose.

TL;DR Are there ways to accomplish this kind of redirecting without having to define a server block for each domain?

已采纳解答

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

A regular expression server_name directive can capture the last element of the domain name for use in the redirect. For example:

server {
    listen 80;
    server_name ~\.(?<tld>[^.]+)$;
    return 301 $scheme://www.domain.com/$tld$request_uri;
}

See this document for details.

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

资料来源与适用范围

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

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

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