问题描述
我有以下 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 对我来说是新手。
$ 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
,没有记录任何错误。
我做错了什么,导致在向反向代理服务器发出请求后,我的缓存目录中没有任何条目?
解决方法
事实证明我需要添加一个 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; } } }