我如何干掉这个 Nginx 配置?

ja'*_*ja' 5 nginx reverse-proxy

我在Nginx 0.8.54 上尝试尽可能 DRYly 实现以下目标:

  • 直接代理到localhost:8060cookie no_cacheistrue或 if request method is not GET
  • 否则从$document_root/static/$uri.
  • 如果不存在这样的文件,请尝试$document_root/cache/$uri$document_root/cache/$uri.html
  • 如果请求路径是/,请不要尝试静态文件,而只尝试$document_root/cache/index.html.
  • 最后回退到localhost:8060既没有找到静态文件也没有找到缓存文件的情况。

当前配置文件:

server {
    root /srv/web/example.com;
    server_name example.com;

    location @backend { proxy_pass http://localhost:8060; }

    location / {
        if ($cookie_no_cache = true) { proxy_pass http://localhost:8060; }
        if ($request_method != GET) { proxy_pass http://localhost:8060; }
        try_files /static/$uri /cache/$uri /cache/$uri.html @backend;
    }

    location = / {
        if ($cookie_no_cache = true) { proxy_pass http://localhost:8060; }
        if ($request_method != GET) { proxy_pass http://localhost:8060; }
        try_files /cache/index.html @backend;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*rov 4

http {
  map $cookie_no_cache $cacheZone {
    default "";
    true    X;
  }

  server {
    root /srv/web/example.com;
    server_name example.com;

    error_page 405 = @backend;

    location / {
      try_files /cache$cacheZone/$uri.html /static$cacheZone/$uri
                /cache$cacheZone/$uri @backend;
    }

    location @backend {
      proxy_pass http://localhost:8060;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

解释。

  1. 关于“no_cache”cookie 检查。我们将其替换为 Nginx map。变量$cacheZone取决于 的值$cookie_no_cache。默认情况下它是空的,但是如果有“no_cache=true”cookie,我们设置$cacheZone为任何值来修改静态文件搜索路径try_files- 我希望你的服务器根目录下没有/cacheX文件/staticX夹(如果有,请选择另一个值)$cacheZone
  2. Nginx 无法应用 HTTP 方法PUTPOST静态文件(这毫无意义),因此在这种情况下会发出 HTTP 错误 405“不允许”。我们拦截它并将error_page请求传递到@backend位置。

替代方法

否则,使用proxy_cache

http {
  proxy_cache_path example:1m;

  server {
    root  /srv/web/example.com;
    server_name example.com;

    location / {
      proxy_cache example;
      proxy_cache_bypass $cookie_no_cache;
      proxy_cache_valid 200 10s;
      proxy_pass http://localhost:8060;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)