如何干这个Nginx的configuration?

我在Nginx 0.8.54试图尽可能实现以下DRYly:

  • 代理直接到localhost:8060如果cookie no_cachetrue或者请求方法不是GET
  • 否则,从$document_root/static/$uri提供静态文件。
  • 如果不存在这样的文件,请尝试$document_root/cache/$uri$document_root/cache/$uri.html
  • 如果请求path是/ ,请尝试不使用静态文件,只使用$document_root/cache/index.html
  • 最后回退到localhost:8060如果找不到静态文件和caching文件。

当前configuration文件:

 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; } } 

 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; } } } 

说明。

  1. 关于“no_cache”cookie检查。 我们用Nginx map来取代它。 variables$cacheZone取决于$cookie_no_cache的值。 默认情况下它是空的,但如果有一个“no_cache = true”的cookie,我们将$cacheZone设置$cacheZone任何值来修改try_files静态文件searchpath – 我希望你的服务器根目录下没有/cacheX/staticX文件夹如果是的话,为$cacheZoneselect另一个值)
  2. Nginx无法将HTTP方法PUTPOST应用于静态文件(这是毫无意义的),因此在这种情况下,它会发出HTTP错误405“不允许”。 我们通过error_page拦截它, 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; } } }