nginx下根据ua来源判断是启用静态目录还是使用反向代理

需求是这样:

通过nginx匹配ua中的关键字可以得到用户是来自移动设备或者pc,

然后我拿这个变量去做如下判断:

  • 如果是移动端,则指向/usr/local/wwwroot/surmon.me.mobile/dist;静态目录,并做重写规则处理

  • 如果是PC端,则反向代理至3000端口,不做静态处理,一切交给3000

下面是无法使用的代码:

server {
        listen 80;
        listen 443 ssl;
        server_name surmon.me www.surmon.me;
        ssl_session_timeout 5m;
        
        # 对http和非主域名进行重定向
        set $need_rewrite 0;
        if ($scheme = http) {
            set $need_rewrite 1;
        }
        if ($host = "www.surmon.me") {
            set $need_rewrite 1;
        }
        if ($host = "wordpress.surmon.me") {
            set $need_rewrite 1;
        }
        if ($need_rewrite = 1) {
            return 301 https://$server_name$request_uri;
        }
        
        # 是否为移动端请求
        set $mobile_request 0;
        if ($http_user_agent ~* '(iPhone|iPod|Opera Mini|Android.*Mobile|NetFront|PSP|BlackBerry|Windows Phone)') {
          set $mobile_request 1;
        }
        location / {
        
          root /usr/local/wwwroot/surmon.me.mobile/dist;
          # 移动端请求,则指向本地项目目录
          if ($mobile_request = 1) {
            root /usr/local/wwwroot/surmon.me.mobile/dist;
            break;
          }
          
          # PC端请求
          if ($mobile_request != 1) {
            proxy_set_header Host $host;
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:3000;
            proxy_redirect off;
          }
        }
        # 移动端请求,则响应spa重写规则
        # if (!-e $request_filename) {
            # set $mobile_request 2;
        # }
        # if ($mobile_request = 2) {
            # rewrite ^/(.*) /index.html?$1 last;
        # }
        
        # 反代服务
        location ~ "^/proxy/(.*)$" {
          resolver 114.114.114.114 114.114.115.115 8.8.8.8;
          proxy_pass http://$1;
          proxy_redirect off;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $remote_addr;
          expires 7d;
        }
        
        access_log off;
        error_log /usr/local/wwwlogs/nginx/surmon.me.error.log;
    }
查看回复