为什么我的 Nginx 配置不缓存响应?

时间:2021-06-21 15:47:55

标签: nginx reverse-proxy nginx-reverse-proxy

我有以下 Nginx 配置,我们可以从 nginx -T 的输出中看到它在语法上是正确的。我加粗输出的一些相关部分如下:

$ sudo nginx -T
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# configuration file /etc/nginx/nginx.conf:
events {}

http {
    proxy_cache_path /tmp/cache keys_zone=one:10m levels=1:2 inactive=2M max_size=100g;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Static file server
    server {
        listen 127.0.0.1:8080;

        root /opt/nginx-test-data;

        location / {
        }
    }

    # Reverse proxy that talks to server defined above
    server {
        listen 127.0.0.1:8081;
        proxy_cache_min_uses 1;

        location / {
            proxy_pass http://127.0.0.1:8080;
            proxy_cache one;
        }
    }
}

我知道通常情况下服务器和代理服务器在不同的主机上。目前我只是想学习如何使用内容缓存配置 Nginx 代理服务器,因为 Nginx 对我来说是新手。

我有以下 2MB 的随机字节文件:

$ ls -lh /opt/nginx-test-data/random.bin 
-rw-rw-r-- 1 shane shane 2.0M Jun 21 11:39 /opt/nginx-test-data/random.bin

当我卷曲反向代理服务器时,我得到 200 响应:

$ curl --no-progress-meter -D - http://localhost:8081/random.bin --output local-random.bin
HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Date: Mon, 21 Jun 2021 15:50:07 GMT
Content-Type: text/plain
Content-Length: 2000000
Connection: keep-alive
Last-Modified: Mon, 21 Jun 2021 15:39:54 GMT
ETag: "60d0b2ca-1e8480"
Accept-Ranges: bytes

然而,我的缓存目录是空的:

$ sudo ls -a /tmp/cache/
.  ..

我检查了 /var/log/nginx/access.log/var/log/nginx/error.log,没有记录任何错误。

我做错了什么,导致在向反向代理服务器发出请求后,我的缓存目录中没有任何条目?

1 个答案:

答案 0 :(得分:0)

事实证明我需要添加一个 proxy_cache_valid directive(虽然我不清楚为什么这是必要的 - 我假设简单地在 proxy_cache_valid 中使用 location 会打开缓存靠自己)。

我的nginx.conf有效(注意粗体中的新行):

events {}

http {
    proxy_cache_path /tmp/cache keys_zone=one:10m levels=1:2 inactive=2M max_size=100g;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Static file server
    server {
        listen 127.0.0.1:8080;

        root /opt/nginx-test-data;

        location / {
        }
    }

    # Reverse proxy that talks to server defined above
    server {
        listen 127.0.0.1:8081;
        proxy_cache_min_uses 1;

        location / {
            proxy_pass http://127.0.0.1:8080;
            proxy_cache one;
            proxy_cache_valid 200 10m;
        }
    }
}
相关问题