带参数的特定 url 缓存的 Nginx 位置

Niginx location with cache for a specific url with params

我只想为特定的 url 使用 nginx 缓存 url 是 /ajax/airport 并且必须包含参数 ?geoloc=1.

缓存工作正常,我面临的唯一问题是让它为包含给定参数的 url 工作。

这是我的 nginx site.conf 文件:

    server {
          listen 80;
          server_name _;
          server_tokens off;

          location /ajax/airport.php {
             if ($args_geoloc = 1) {
                  proxy_pass              http://127.0.0.1:8080/ajax/airport.php;
                  proxy_set_header        Host                    $host;
                  proxy_set_header        X-Real-IP               $remote_addr;
                  proxy_set_header        X-Forwarded-For         $proxy_add_x_forwarded_for;
                  proxy_cache  my-cache;
                  proxy_cache_valid 300s;
                  #proxy_no_cache $cookie_PHPSESSID;
                  #proxy_cache_bypass $cookie_PHPSESSID;
                  proxy_cache_key         "$scheme$host$request_uri";
                  add_header X-Cache $upstream_cache_status;
                  add_header LEM airport;
             }
         }

         location / {
             proxy_pass              http://127.0.0.1:8080/; 
             proxy_set_header        Host                    $host;
             proxy_set_header        X-Real-IP               $remote_addr;
             proxy_set_header        X-Forwarded-For         $proxy_add_x_forwarded_for;
             add_header LEM all;
         }
  }


    server {
          listen 8080;
          .. usual location handeling ...

我得到的错误是:

nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /etc/nginx/sites-enabled/site.com.conf:8

感谢您的帮助!

只需使用 proxy_no_cache and proxy_cache_bypass instead of if, testing the value of $arg_geoloc (not $args_geoloc) with map 指令。

map $arg_geoloc $bypass {
    default    1;
    1          0;
}

server {
    ...
    location /ajax/airport.php {
        ...
        proxy_no_cache $bypass;
        proxy_cache_bypass $bypass;
        ...
        # No need to add /ajax/airport.php in proxy_pass
        proxy_pass http://127.0.0.1:8080;
    }
    ...
}

Nginx 还允许使用 proxy_no_cacheproxy_cache_bypass 测试多个参数。如果您需要类似的东西,只需将参数一个接一个地输入即可:

proxy_no_cache $cookie_PHPSESSID $bypass_cache;
proxy_cache_bypass $cookie_PHPSESSID $bypass_cache;