nginx:将除几个目录之外的所有内容重定向到新主机名

Ste*_*ögl 1 nginx redirect

我正在通过 nginx 提供网络服务(API + Webiste),其规范域名最近发生了变化。API通过子目录从面向用户的网站中分离出来(例如/api/和/download/是API的一部分,其余的属于网站)。

我现在想将网站部分重定向到新域名,但无需重定向即可提供 API 请求(以降低服务器负载)。

因为可以通过多个域访问网络服务器,所以我需要重定向与新规范不匹配的所有内容;就像是

IF request-domain != new-domain
 AND resource not in (/api/, /download/):
   redirect to new domain

ELSE:
   # serve site
   proxy_pass   http://app_server;
Run Code Online (Sandbox Code Playgroud)

我没有在 nginx 中找到合适的方法来进行(双重)负比较,我无法将它们反转为正比较,因为替代域名和非 API 资源都很多,我不知道不想在 nginx 配置中维护。

任何想法将不胜感激!

kol*_*ack 6

在 nginx 中,您通常不想使用 if 来根据 Host 标头或 uri 更改行为。您需要第二台服务器:

server {
  # Make sure this listen matches the one in the second server (minus default flag)
  listen 80;

  server_name new-domain;

  # All your normal processing.  Is it just proxy_pass?
  location / {
    proxy_pass http://app_server;
  }
}

server {
  # If you listen on a specific ip, make sure you put it in the listen here
  # default means it'll catch anything that doesn't match a defined server name
  listen 80 default;

  server_name old-domain; # and everything else, but it's good to define something

  # Everything that doesn't match /api/ or /download/
  location / {
    rewrite ^ http://new-domain$request_uri? permanent;
  }

  # You may want some common proxy_set_header lines here in the server
  # if you need them

  location /api/ {
    proxy_pass http://app_server;
  }

  location /download/ {
    proxy_pass http://app_server;
  }
}
Run Code Online (Sandbox Code Playgroud)