使用通配符子域时,Nginx 重定向单个子域上的单个页面

Nginx redirect for single page on single subdomain while using wildcard subdomains

我有一个使用通配符子域的服务器块,例如 *.example.com。我需要将单个子域上的单个页面重定向到另一个页面,同时正常处理所有其他请求。处理此问题的最有效方法是什么?

服务器块看起来像这样:

server {
    listen 80;
    server_name *.example.com;
    ....
}

我需要这种行为:

http://baseball.example.com/test.php -> http://baseball.example.com/new-page

http://football.example.com/test.php -> 无重定向

http://basketball.example.com/test.php -> 无重定向

从处理的角度来看,最有效的方法是为特殊情况创建一个单独的 server 块。由于两个服务器块的大部分配置都是相同的,您可以使用 include 语句从单独的文件中读取它。

例如:

server {
    listen 80;
    server_name *.example.com;
    include /path/to/common.config;
}
server {
    listen 80;
    server_name baseball.example.com;
    location = /test.php {
        return 301 /new-page;
    }
    include /path/to/common.config;
}

有关更多信息,请参阅 this document