2010-06-01

nginx真是个怪东西

这几天和nginx杠上了

我的网络情况是 browser => proxy => nginx
proxy ip: 192.168.10.204
nginx ip: 192.168.10.10

proxy是用iptables做了个端口转发

iptables -t nat -A PREROUTING -d 192.168.10.204 -p tcp -m tcp --dport 22080 -j DNAT --to-destination 192.168.10.10:80
iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -d 192.168.10.10/32 -p tcp -m tcp --dport 80 -j SNAT --to-source 192.168.10.204 

理想的情况下,访问 http://192.168.10.204:22080 会被iptables转发到 http://192.168.10.10:80

然后我这里情况是:
访问 http://192.168.10.204:22080/index.html 正常
访问 http://192.168.10.204:22080/foo/index.html 正常
访问 http://192.168.10.204:22080/foo/ 正常
访问 http://192.168.10.204:22080/foo 被转向到 http://192.168.10.204/foo/

首先我排除是iptables的问题,认定是nginx配置的问题

官方的文档里提到有一个 port_in_redirect 的设置,on off我都试过,貌似都无效。

原来 nginx 很怪,据说是nginx不会自动在请求的最后加上一个slash,不会自动判断请求的是一个文件还是一个目录。这个我搜了一下没有找到官方文档的说法,但是搜索 nginx 斜线,都会提到需要 rewrite 一下,在请求的最后加上这个斜杠。

网上的资料都会提到是这样 rewrite 滴:

if (-d $request_filename) {
    rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}

但是呢,我这里死活都不起作用,转向的时候还是把端口丢了。

最后还是 @cnhacktnt 帮我调好了,就是 $host 变量把端口弄没了,改成了 $http_host 变量即可。

也就是变成了

if (-d $request_filename) {
    rewrite ^/(.*)([^/])$ http://$http_host/$1$2/ permanent;
}

感谢 cnhacktnt ,头痛了几天终于心情舒畅

没有评论: