解析nginx proxy_pass是如何匹配请求的

准备

server config:

#server config
server {
    listen        80;
    server_name   test.com;
}


无正则表达式匹配时

location /app/ {
    proxy_pass      http://192.168.154.102;
}

test.com/app/xxxxx =>  http://192.168.154.102/xxxxx


location /app/ {
    proxy_pass      http://192.168.154.102/maped_dir/;
}

test.com/app/xxxxx =>  http://192.168.154.102/maped_dir/xxxxx


转发host头部信息,默认是不转发的

proxy_set_header Host $host;


使用正则表达式匹配

location  ~ ^/app/(.*)$ {
    # proxy_pass   http://127.0.0.1/some_dir;       # error
    proxy_pass   http://127.0.0.1/some_dir/$1;      # ok
}


location ~ ^/app/(.*)$ {
    proxy_pass       http://192.169.154.102:$1;
}

test.com/app/8081 => http://192.168.154.102:8081


location ~ ^/app/(.*)$ {
    proxy_pass       http://192.169.154.102:9999/some_dir/$1;
}

test.com/app/request/xxxxx => http://192.168.154.102:9999/some_dir/xxxxx


如果先匹配了rewrite规则,则proxy_pass将忽略

location  /app/ {
    rewrite    ^/app/hit/(.*)$ /hit_page.php?path=$1 break;
    proxy_pass   http://192.168.154.102:9999/some_dir/;
}

/app/hit/some/request/?name=xxxxx
=> http://192.168.154.102:9999/hit_page.php?path=some/request/&name=xxxxx
/app/not_hit/some/request/?name=xxxxx
=> http://192.168.154.102:9999/some_dir/not_hit/some/request/?name=xxxxx


 

展开阅读全文