【问题标题】:nginx - response based on the requested headernginx - 基于请求标头的响应
【发布时间】:2012-02-28 09:58:51
【问题描述】:

我安装了 nginx 1.0.8。 这是我的问题: 我有 2 个文件:file1.jsfile2.js。请求的路径是这样的:

www.mysite.com/files_dir/%user%/file.js

如果请求的标头:“X-Header”存在且值为“OK”,则响应的内容应为 file1.js,否则为 file2.js。

文件位于“html/files_dir”中,%user% 是一组目录,代表通过我的服务注册的用户名。

如何在 nginx 中进行配置?我对 php、asp 或类似技术不感兴趣,只有在 nginx 有可能的情况下。

谢谢

【问题讨论】:

    标签: nginx server-configuration


    【解决方案1】:

    map 允许您根据另一个变量定义一个变量的值。 map 应该在http 级别声明(即在server 之外):

    map $http_x_header $file_suffix {
      default "2";
      OK      "1";
    };
    

    那么下面的location 应该使用你的新变量$file_suffix 来解决问题

    location ~ ^(/files_dir/.+)\.js$ {
      root html;
      try_files $1$file_suffix.js =404;
    }
    

    【讨论】:

      【解决方案2】:

      你可以很容易地用 nginx 做到这一点。这是一个例子:

      location /files_dir/ {
      
          set $file = file2.js;
          if ( $http_x_header = OK ) {
              set $file = file1.js;
          }
          rewrite ^(/files_dir/.*)/file.js$ $1/$file last;
      
      }
      

      您可以阅读有关 NGINX 中的 HTTP 变量 here 以及有关 nginx 重写模块 here 的信息

      【讨论】:

      • 谢谢你的回答也很好,但是 set $file = file2.js;没有“=”..只需设置 $file file2.js;
      猜你喜欢
      • 2016-05-06
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 2015-11-13
      • 2021-07-08
      • 2023-03-08
      相关资源
      最近更新 更多