NGINX:重写、代理和缓存文件夹

NGINX:重写、代理和缓存文件夹

我是 NGINX 新手,需要知道如何在特殊位置(文件夹)执行此操作

  • 删除所有查询参数
  • 代理请求到另一台服务器
  • 在本地将结果缓存 x 分钟

配置片段:

location /cache {
    rewrite /cache/([^/\?]) /cache/$1 break;
    proxy_pass http://foo.bar/original/;
    expire 5m;
}

$args我已经看到了关于覆盖和使用参数删除的不同想法?。但我无法让任何事情按预期工作。

例如

1. Request
---
Request: http://foo.bar/cache/text.css?abc=123
Rewrite: http://foo.bar/cache/text.css
Cache miss
Proxy:   http://fuzzu.buzzi/original/text.css
(store in local cache)
Expire:  http://foo.bar/cache/text.css (after 5min)

2. Request
---
Request: http://foo.bar/cache/text.css?abc=123
Rewrite: http://foo.bar/cache/text.css
Cache hit

答案1

所以最后我自己找到了解决方案:

proxy_cache_path /tmp/nginx levels=1:2 keys_zone=foo_bar:1m inactive=10m;

server {
    listen 80;
    server_name foo.bar;

    # DNS lookup
    resolver 8.8.8.8;
    resolver_timeout 1s;

    # use regex to not forward query string
    location ~ ^/cache/(.*)$ {
        proxy_cache foo_bar;

        # cache key only with host + path but without query string
        proxy_cache_key $host$uri;

        # nginx should ignore cache headers but forward them
        proxy_ignore_headers Cache-Control;

        proxy_cache_valid 5m;
        proxy_pass http://fuzzu.buzzi/original/$1;

        add_header X-Proxy-Cache $upstream_cache_status;
    }

}

相关内容