如何在Nginx配置中使用正则表达式检查子字符串?

时间:2019-02-21 10:04:03

标签: nginx

我尝试检查请求中的某些参数。这是我的网址:

http://localhost:8080/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=004C0000064F&
     STYLES=&WIDTH=256&HEIGHT=256&FORMAT=image%2fjpeg&CRS=EPSG%3a100000&DPI=96&
 MAP_RESOLUTION=96&FORMAT_OPTIONS=dpi%3a96&
BBOX=1530569.52624839870259166%2c524135.21126760687911883%2c1531064.27656850102357566%2c524629.96158770937472582

我试图获取REQUEST参数。这是我的Nginx 1.12.1配置:

server {
  listen      8080;
  server_name 127.0.0.1 localhost;

  set $site_backend localhost:56297;

  proxy_set_header  Host            $host;
  proxy_set_header  X-Real-IP       $remote_addr;
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;

  location /favicon.ico {
      error_page 403 404  =  @tomcat_static_mapping;
  }

  location ~* /wms {

      internal;
      add_header URI $request_uri;
      add_header X-debug-message1 "$request_uri" always;

      if ($request_uri ~* REQUEST=([^&]*)) {
          add_header X-debug-message2 "hi" always;
          set $requesttype $1;
      } 
  }
}

在浏览器中,我得到了标题:

X-debug-message1: /wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=004C0000064F&STYLES=&WIDTH=256&HEIGHT=256&FORMAT=image%2fjpeg&CRS=EPSG%3a100000&DPI=96&MAP_RESOLUTION=96&FORMAT_OPTIONS=dpi%3a96&BBOX=1530569.52624839870259166%2c524135.21126760687911883%2c1531064.27656850102357566%2c524629.96158770937472582

但没有获得X-debug-message2标头。我在这里https://rubular.com/检查正则表达式,发现匹配并按我的意愿返回GetMap
这里有什么问题吗?

1 个答案:

答案 0 :(得分:1)

信息不完整/与您的帖子匹配。我得到X-debug-message2: hi ,它确实与nginx的行为方式相符:

  

仅当当前级别上没有定义add_header指令时,这些指令才从上一级继承

要获得更直观的结果,请使用Headers-More模块。

 more_set_headers "URI: $request_uri";
 more_set_headers 'X-debug-message1: "$request_uri"';
 location ~* /wms {
     if ($request_uri ~* REQUEST=([^&]*)) {
         more_set_headers 'X-debug-message2: hi';
         set $requesttype $1;
     }
 }