nginx propxy_pass / 学习
nginx proxy_pass 是支持带/ 的,同时对于不同的模式,会产生不同的效果,
整体总结(当然还有特殊情况)
- proxy_pass 带/的,使用的是绝对路径,请求格式会变成
http://$domainname:$port/proxy/$resource->http://$upstream/$resource
- proxy_pass 不带/的,使用相对路径,请求格式会变成
http://$domainname:$port/proxy/$resource->http://$upstream/proxy/$resource
注意说明
以上只是一般的,同时proxy_pass 也会可以带url 的,这个就更有意思了,具体可以参考简书
一个哥们的整理,同时一个问题
nginx.conf 配置
worker_processes 1;
user root;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
gzip on;
server {
listen 80;
charset utf-8;
default_type text/html;
location / {
root /opt/demoapps/rong;
index index.html index.htm index;
}
location /test {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $remote_addr;
client_body_buffer_size 10M;
client_max_body_size 10G;
proxy_buffers 1024 4k;
proxy_read_timeout 300;
proxy_next_upstream error timeout http_404;
proxy_pass http://localhost:8080;
}
# 请求格式 http://localhost/dalong/dalong -> http://localhost:8080/dalong
location /dalong {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $remote_addr;
client_body_buffer_size 10M;
client_max_body_size 10G;
proxy_buffers 1024 4k;
proxy_read_timeout 300;
proxy_next_upstream error timeout http_404;
proxy_pass http://localhost:8080/;
}
location /liang/ {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $remote_addr;
client_body_buffer_size 10M;
client_max_body_size 10G;
proxy_buffers 1024 4k;
proxy_read_timeout 300;
proxy_next_upstream error timeout http_404;
proxy_pass http://localhost:8080/liang;
}
error_page 404 /404.html;
# 请求格式 http://localhost/demo1 -> http://localhost:8080/demo1
location ~* ^/demo {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $remote_addr;
client_body_buffer_size 10M;
client_max_body_size 10G;
proxy_buffers 1024 4k;
proxy_read_timeout 300;
proxy_next_upstream error timeout http_404;
proxy_pass http://localhost:8080;
}
# 请求格式 http://localhost/rong/demo1 -> http://localhost:8080/demo1
location /rong/ {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $remote_addr;
client_body_buffer_size 10M;
client_max_body_size 10G;
proxy_buffers 1024 4k;
proxy_read_timeout 300;
proxy_next_upstream error timeout http_404;
proxy_pass http://localhost:8080/;
}
}
server {
listen 8080;
charset utf-8;
default_type text/html;
location / {
root /opt/demoapps;
index index.html index.htm index;
}
error_page 404 /404.html;
}
}
一个有趣的地方
我请求http://localhost/dalong/dalong 会进行一次重定向,但是浏览器的显示如下(效果是对了,但是url显示不太对)
具体配置可以参考github ,这个问题,如果从规则匹配上的确是对的,但是从显示上就不太对了
参考资料
https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass
https://github.com/rongfengliang/nginx-location-learning
https://www.jianshu.com/p/c751250a5112