Nginx多重if判断的实现

首先

Nginx不支持 and、or、&&、|| 这类语法;且不支持if的多重嵌套,例如:

if (aaa) {
    if (bbb) {
       exec @ccc;
   }
}

多重判断如何实现呢?

最近要做个配置,将移动设备访问网页时跳转到手机版面。需要判断2个部分才做跳转:一、客户端来源为移动设备;二、访问指定域名业务时。

实现方法一

每个域名配置单独的server{},这样配置比较简明;但缺点是配置文件会写很长,要修改多次。(比较啰嗦)

实现方法二

全部域名配置一个server{},进行多重判断;这样配置可能稍微复杂一点,但配置文件不会那么啰嗦。

server {
    listen 80;
    server_name _;
    set $domain $host;
    root /webapp/$domain;

    ...其它略

    if ($http_user_agent ~* "UCBrowser|Android|Iphone|Ipad|Ipod|BlackBerry|Windows Phone|Symbian(.*)Series60/3|Symbian(.*)Series60/5") {
        set $mobile '1';
    }

    if ($host !~* ^(app1|app2|app3).google.com) {
        set $mobile '0';
    }

    if ($mobile = 1) {
        rewrite "^/index.html$" /mobile/index.html last;
    }

    ...其它略

}

后续

移动设备的 http_user_agent 还不全,慢慢收集~

原文地址:https://www.cnblogs.com/tutuye/p/4499403.html