晨风

-------------------- 业精于勤,荒于嬉;行成于思,毁于随

导航

nginx location proxy_pass详解

Posted on 2020-04-16 12:49  shenyixin  阅读(2875)  评论(0编辑  收藏  举报

在nginx中配置proxy_pass时,如果在proxy_pass后面的url加/,相当于是绝对根路径,则nginx不会把location中匹配的路径部分代理走;如果没有/,则会把匹配的路径部分给代理走。 

下面四种情况分别用http://106.12.74.123/abc/index.html进行访问。

# 第一种
location  /abc
    {
        proxy_pass http://106.12.74.123:83/;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
 
# 结论:会被代理到http://106.12.74.123/index.html 这个url
 
 
 
# 第二种(相对于第一种,最后少一个 /)
location  /abc
    {
        proxy_pass http://106.12.74.123:83;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
 
# 结论:会被代理到http://106.12.74.123/abc/index.html 这个url
 
 
 
第三种:
location  /abc
    {
        proxy_pass http://106.12.74.123:83/linux/;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
 
# 结论:会被代理到http://106.12.74.123/linux/index.html 这个url。
 
 
 
# 第四种(相对于第三种,最后少一个 / ):
location  /abc
    {
        proxy_pass http://106.12.74.123:83/linux;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
 
# 结论:会被代理到http://106.12.74.123/linuxindex.html 这个url

下面我们验证一下:

环境准备:nginx的配置如下

主配置文件:

server {
    listen       80;
    server_name  localhost;
 
    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
 
  
    location  /abc
    {
        proxy_pass http://106.12.74.123:83/;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

副配置文件,上面是代理到83端口了,我们看一下83端口的配置为文件,之前做其他实验,现在我们就在这个上面简单修改下。

[root@master conf.d]# cat 83.conf 
server
{
   listen 83;
   server_name 106.127.74.123;
   root /usr/share/nginx/83;
}

查看静态文件地址:

[root@master nginx]# tree 83/
83/
├── abc
│   └── index.html
├── index.html
└── linux
    └── index.html
 
[root@master nginx]# cat 83/index.html 
83
 
[root@master nginx]# cat 83/abc/index.html 
83  abc
 
[root@master nginx]# cat 83/linux/index.html 
linux

第一种:当我们http://106.12.74.123/abc/index.html时候,页面出现的是83

第二种:当我们http://106.12.74.123/abc/index.html时候,页面出现的是83  abc的内容

第三种:当我们http://106.12.74.123/abc/index.html时候,页面出现的是linux的内容

第四种:当我们http://106.12.74.123/abc/index.html时候,页面出现的是404  因为83目录下并没有linxuindex.html的文件
————————————————
原文链接:https://blog.csdn.net/wyl9527/article/details/89671506