如何干掉这个Nginx配置?

前端之家收集整理的这篇文章主要介绍了如何干掉这个Nginx配置?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用Nginx 0.8.54尝试以尽可能的方式实现以下目标:

>代理直接到localhost:8060如果cookie no_cache为true或者请求方法不是GET.
>否则从$document_root / static / $uri提供静态文件.
>如果不存在此类文件,请尝试$document_root / cache / $uri和$document_root / cache / $uri.html.
>如果请求路径为/,请尝试不使用静态文件,只需$document_root / cache / index.html.
>如果找不到静态文件或缓存文件,最后回退到localhost:8060.

当前配置文件

  1. server {
  2. root /srv/web/example.com;
  3. server_name example.com;
  4. location @backend { proxy_pass http://localhost:8060; }
  5. location / {
  6. if ($cookie_no_cache = true) { proxy_pass http://localhost:8060; }
  7. if ($request_method != GET) { proxy_pass http://localhost:8060; }
  8. try_files /static/$uri /cache/$uri /cache/$uri.html @backend;
  9. }
  10. location = / {
  11. if ($cookie_no_cache = true) { proxy_pass http://localhost:8060; }
  12. if ($request_method != GET) { proxy_pass http://localhost:8060; }
  13. try_files /cache/index.html @backend;
  14. }
  15. }
最佳答案
  1. http {
  2. map $cookie_no_cache $cacheZone {
  3. default "";
  4. true X;
  5. }
  6. server {
  7. root /srv/web/example.com;
  8. server_name example.com;
  9. error_page 405 = @backend;
  10. location / {
  11. try_files /cache$cacheZone/$uri.html /static$cacheZone/$uri
  12. /cache$cacheZone/$uri @backend;
  13. }
  14. location @backend {
  15. proxy_pass http://localhost:8060;
  16. }
  17. }
  18. }

说明.

>关于“no_cache”cookie检查.我们正在用Nginx地图替换它.变量$cacheZone取决于$cookie_no_cache的值.默认情况下它是空的,但是如果有一个“no_cache = true”cookie,我们将$cacheZone设置为任何值来修改try_files中的静态文件搜索路径 – 我希望你的服务器根目录下没有/ cacheX和/ staticX文件夹(如果是,请为$cacheZone选择另一个值)
> Nginx无法将HTTP方法PUT或POST应用于静态文件(这没有意义),因此在这种情况下它会发出HTTP错误405“Not Allowed”.我们通过error_page拦截它并将请求传递给@backend位置.

替代方法

否则,使用proxy_cache:

  1. http {
  2. proxy_cache_path example:1m;
  3. server {
  4. root /srv/web/example.com;
  5. server_name example.com;
  6. location / {
  7. proxy_cache example;
  8. proxy_cache_bypass $cookie_no_cache;
  9. proxy_cache_valid 200 10s;
  10. proxy_pass http://localhost:8060;
  11. }
  12. }
  13. }

猜你在找的Nginx相关文章