nginx:将几个目录以外的所有内容redirect到新的主机名

我正在通过nginx提供web服务(API + Webiste),并且最近更改了它的规范域名。 该API是从面向用户的网站的子目录拆分(例如/ api /和/ download /是API的一部分,其余属于该网站)。

我现在想将网站部分redirect到新的域名,但是服务于没有redirect的API请求(以保持服务器负载不变)。

因为networking服务器可以通过多个域来访问,所以我需要redirect与新规范不匹配的所有东西。 就像是

IF request-domain != new-domain AND resource not in (/api/, /download/): redirect to new domain ELSE: # serve site proxy_pass http://app_server; 

我没有find一种合适的方式在nginx中进行(双)否定比较,我不能将它们反转为正比较,因为替代域名和非API资源都非常多,不想在nginxconfiguration中维护。

任何想法将不胜感激!

在nginx中,你通常不希望使用if来改变基于主机头或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; } } 

Nginx不允许多个或嵌套的if语句,但你可以设置variables,如下所示:

  server_name _; if ($http_host !~ new-domain) { set $var D; } if ($request_uri !~ (/api|/download)) { set $var "${var}U"; } if ($var = DU) { rewrite ^(.*)$ http://new-domain$request_uri last; break; } 

关于else条件,你应该在一个分离的虚拟主机中进行。