我正在尝试设置一个 nginx 配置,如下所示:当收到如下请求时/tile/SteveCountryVic/1/2/3.png
:
- 尝试将其传递给
http://localhost:5005/1/2/3.png
- 如果出现 404 错误,则将其传递到另一台服务器
/tile/SteveCountryVic/1/2/3.png
这是我的配置,但它不太起作用:
server {
listen 80;
server_name localhost; error_log /tmp/nginx.error.log notice;
access_log /tmp/nginx.access.log;
location /tile/SteveCountryVic/ {
rewrite_log on;
#rewrite ^.*/(\d+)/(\d+)/(\d+).*$ /$1/$2/$3.png break;
proxy_intercept_errors on;
error_page 404 = @dynamiccycletour;
#proxy_set_header Host $http_host;
#proxy_pass http://127.0.0.1:5005;
proxy_redirect /tile/SteveCountryVic/ http://localhost:5005/;
location @dynamiccycletour {
rewrite_log on;
#rewrite ^(\d+)/(\d+)/(\d+).*$ /tile/SteveCountryVic/$1/$2/$3.png break;
proxy_pass http://115.x.x.x:20008;
}
location /tile/ {
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:20008;
proxy_cache my-cache;
proxy_cache_valid 200 302 60m;
proxy_cache_valid 404 1m;
}
...
在这种配置下,所有请求似乎都会重定向到代理服务器,但最终还是会提供图像。此外,错误日志包含以下几行:
2013/09/10 09:44:11 [error] 564#0: *138 open() "/etc/nginx/html/tile/SteveCountryVic/13/7399/5027.png" failed (2: No such file or directory), client: 118.x.x.x, server: localhost, request: "GET /tile/SteveCountryVic/13/7399/5027.png?updated=15 HTTP/1.1", host: "mydomain.org"
如果不使用proxy_redirect
,而是使用rewrite
和proxy_pass
:
rewrite ^.*/(\d+)/(\d+)/(\d+).*$ /$1/$2/$3.png break;
proxy_pass http://127.0.0.1:5005;
那么现在我确实在浏览器中看到了 404 消息(即它们没有被拦截)。
我的问题:
- 我究竟做错了什么?
- nginx 到底为什么要在 /etc/nginx/html/... 中寻找文件?
- 有没有办法获取更多的日志信息(具体来说,为了更好地理解 proxy_redirect)?
答案1
替代版本使用rewrite
并proxy_pass
表现完美 - 问题是另一台服务器返回 200 而不是 404。因此,为了完整起见,这里是工作配置:
server {
listen 80;
server_name localhost;
error_log /tmp/nginx.error.log notice;
access_log /tmp/nginx.access.log;
location /tile/SteveCountryVic/ {
rewrite_log on;
rewrite ^.*/(\d+)/(\d+)/(\d+.*)$ /$1/$2/$3 break;
proxy_intercept_errors on;
error_page 404 = @dynamiccycletour;
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:5005;
}
location @dynamiccycletour {
rewrite_log on;
rewrite ^/(\d+)/(\d+)/(\d+.*)$ /tile/SteveCountryVic/$1/$2/$3 break;
proxy_pass http://115.x.x.x:20008;
}
答案2
首先你没有root
正确设置你的 - 指令 -> 这就是你得到 404 的原因 -> 这就是为什么所有请求都被重定向到你的 @dynamiccycletour (openstreetmap?)
顺便问一下,/tile/ 和 /tile/SteveCountryVic/ 之间有什么区别?
因此我们需要先在这里进行一些清理:
server {
....
# define where to find files
# be sure to have it like /path/to/tile
root /path/to/tiles/;
location /tile/SteveCountryVic/ {
# if file not found -> remote server
try_files $uri @dynamiccycletour
rewrite_log on;
# this should cover /1/2/3.png. no?
rewrite /tile/SteveCountryVic/(.*).png$ /$1.png break;
# i'm not sure this will match due the the rewrite
proxy_redirect /tile/SteveCountryVic/ http://localhost:5005/;
location @dynamiccycletour {
rewrite_log on;
# this should cover /1/2/3.png. no?
rewrite /tile/SteveCountryVic/(.*).png$ /$1.png break;
proxy_pass http://115.x.x.x:20008;
}
}