nginx代理转发问题
在nginx中配置proxy_pass时,如果是按照^~匹配路径时,要注意proxy_pass后的url最后的/。当加上了/,相当于是绝对根路径,则nginx不会把location中匹配的路径部分代理走;如果没有/,则会把匹配的路径部分也给代理走
location ^~ /hahashen/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass http://js.test.com/;
}
如上面的配置,如果请求的url是http://servername/hahashen/test.html会被代理成http://js.test.com/test.html
而如果这么配置
location ^~ /hahashen/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass http://js.test.com;
}
则请求的url是http://servername/hahashen/test.html会被代理到http://js.test.com/hahashen/test.html
当然,可以用如下的rewrite来实现/的功能
location ^~ /hahashen/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
rewrite /hahashen/(.+)$ /$1 break;
proxy_pass http://js.test.com;
}
注意一些配置细节
upstream app {
server 192.168.20.40:9081 max_fails=3 fail_timeout=15s;
server 192.168.20.39:9081 max_fails=3 fail_timeout=15s;
}
server {
listen 80;
server_name image.hahashen.com;
access_log /data/nginx/logs/hahashen-access.log main;
error_log /data/nginx/logs/hahashen-error.log;
location / {
proxy_pass http://app;
proxy_redirect off ;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 600;
proxy_buffer_size 256k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_temp_file_write_size 256k;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 http_404;
proxy_max_temp_file_size 128m;
}
location /api/ {
proxy_pass http://blog.hahashen.com;
}
}
location /sub/ {
proxy_pass http://dt.hahashen.com/;
}
}
解释说明:
(1)访问http://image.hahashen.com的请求负载分发到192.168.20.40:9081和192.168.20.39:9081
(2)访问http://image.hahashen.com/api/ 代理跳转到http://blog.hahashen.com/api/
(3)访问http://image.hahashen.com/sub/代理跳转到http://dt.hahashen.com/
----------------------end---------------------
推荐阅读: