nginx在反向代理的时候,proxy_pass需要指定路径,有无"/"的区别,如下:
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"> location /lile {
配置一: proxy_pass http://192.168.0.37/;
配置二: proxy_pass http://192.168.0.37;
} </pre>
环境说明:
反向代理服务器:192.168.0.224
真实数据机器:192.168.0.37
1:先配置真实数据机的nginx配置文件
[](javascript:void(0); "复制代码")
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
root /web1
location /lile {
root /data;
index index.html;
}
}
}</pre>
[](javascript:void(0); "复制代码")
创建对应的文件夹:
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">mkdir /web1 echo "My location is /web1" > index.html mkdir -p /data/lile echo "My location is /data/lile" > index.html</pre>
2:反向代理的配置文件为
[](javascript:void(0); "复制代码")
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location /lile {
配置一:proxy_pass http://192.168.0.37;
配置二:proxy_pass http://192.168.0.37/
}
}
}</pre>
](javascript:void(0); "复制代码")
3:测试
当proxy_pass为:http://192.168.0.37 的时候,返回的数据如下:
1)浏览器请求访问http://192.168.0.224/lile/
2)到达192.168.0.224后,location /lile 匹配到之后,转发的地址为:http://192.168.0.37/lile/
3)然后到达192.168.0.37,匹配到了location /lile,所以就去/data目录下取数据
当proxy_pass为: http://192.168.0.37/**** 的时候,返回的数据如下:
1)浏览器请求访问http://192.168.0.224/lile/
2)达192.168.0.224后,location /lile 匹配到之后,转发的地址为:http://192.168.0.37/,这里在proxy_pass的 http://192.168.0.37/**** 的“/”会把/lile给替换掉
3)然后到达192.168.0.37,直接匹配到的是root /web1,所以就去/web1目录下取数据
4:其他
在上面的location若为/,没有其他的具体匹配值,那么这两个的访问无区别
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">location / {
配置一: proxy_pass http://192.168.0.37/;
配置二: proxy_pass http://192.168.0.37;
}</pre>
配置一转发的时候,新的URI替换原有的得到的还是 http://192.168.0.37/
配置二转发的时候,不会发生改变 http://192.168.0.37/
5:总结
proxy_pass URL(http://192.168.0.224/uri/)
当URL中含有URI时,Nginx服务器会使用新的URI替换原有的URI(这里的新的URI理解为proxy_pass URL里的URI)
当URL中不含URI时,Nginx服务器不会改变原有地址的URI
这里的URI与URL暂且不去讨论它是怎么定义的,就理解为域名或者IP地址之后的路径(暂时还没弄清楚他们两个的区别)