【问题标题】:How to simplify nginx config when handling outdated browsers?处理过时的浏览器时如何简化 nginx 配置?
【发布时间】:2022-01-21 22:32:15
【问题描述】:

示例 nginx.conf,我想从位置指令中移动条件重写,但不知道如何:

# https://user-agents.net/browsers
map $http_user_agent $outdated {
    default 0;
    ...
}

server {
    ...
    location ~ (not-supported) {
        # empty
    }

    location / {
        if ($outdated = 1) {
            rewrite ^ /not-supported/index.html break;
        }
        try_files $uri $uri/ /index.html =404;
    }

    ...
}

【问题讨论】:

    标签: nginx nginx-config


    【解决方案1】:

    您可以在serverlocation 上下文中使用rewrite 指令。不同之处在于request processing phase 将处理rewrite 指令(NGX_HTTP_SERVER_REWRITE_PHASE 用于最火的情况,NGX_HTTP_REWRITE_PHASE 用于第二种情况)。尽可能避免使用正则表达式。当您在location 上下文中使用rewrite 指令时,您应该为rewrite 指令使用last 标志而不是break 一个强制重新搜索重写URI 的位置。我还建议将其设置为内部以防止直接访问/not-supported/ 目录。所以使用任一

    location /not-supported/ {
        internal;
    }
    
    location / {
        if ($outdated = 1) {
            rewrite ^ /not-supported/index.html last;
        }
        try_files $uri $uri/ /index.html;
    }
    

    if ($outdated = 1) {
        rewrite ^ /not-supported/index.html;
    }
    
    location /not-supported/ {
        internal;
    }
    
    location / {
        try_files $uri $uri/ /index.html;
    }
    

    您可以将non-supported 目录与index.html 文件放在您的Web 根目录下或其他任何地方(对于最后一种情况,您需要为location /not-supported/ { ... } 定义一个自定义根)。确保重写规则不会干扰server 上下文中可能存在的任何其他规则。

    【讨论】:

      【解决方案2】:

      通过以下方式使其工作:

      http {
      # https://user-agents.net/browsers
      map $http_user_agent $outdated {
          default 0;
          "~Opera"                                                    1; # Opera all
          "~MSIE"                                                     1; # MSIE all
          "~Trident/[1-7]\."                                          1; # MSIE all
          "~Chrome/(([1-9]{1})|([0-7]{1}[0-9]{1})|(8[0-6]{1}))\."     1; # Chrome 1.* - 86.*
          "~YaBrowser/(([1-9]{1})|([1-9]{1}[0-8]{1}))\."              1; # Yandex 1.* - 18.*
          "~Firefox/(([1-9]{1})|([0-7]{1}[0-9]{1})|(8[0-3]{1}))\."    1; # Firefox 1.* - 83.*
          "~EdgA?/(([1-9]{1})|([0-7]{1}[0-9]{1})|(8[0-6]{1}))\."      1; # Edge/MobileEdge 1.* - 86.*
          "~Version/(([1-9]{1})|([1-9]{1}[0-1]{1}))\."                1; # Safari 1.* - 11.*
      }
      
      server {
          listen       8080 default_server;
          root         /opt/app-root/src;
      
          if ($uri ~ /not-supported) {
              set $outdated 0;
          }
      
          if ($outdated = 1) {
              rewrite ^ /not-supported/index.html last;
          }
      
          location / {
          .......
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-12
        • 2015-02-15
        • 1970-01-01
        • 2017-09-09
        • 1970-01-01
        • 2014-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多