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)
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)
解释。
map。变量$cacheZone取决于 的值$cookie_no_cache。默认情况下它是空的,但是如果有“no_cache=true”cookie,我们设置$cacheZone为任何值来修改静态文件搜索路径try_files- 我希望你的服务器根目录下没有/cacheX文件/staticX夹(如果有,请选择另一个值)$cacheZone)PUT或POST静态文件(这毫无意义),因此在这种情况下会发出 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)