Nginx的反向代理之http(详细版)

您所在的位置:网站首页 反代理配置nginx Nginx的反向代理之http(详细版)

Nginx的反向代理之http(详细版)

2024-07-09 13:56| 来源: 网络整理| 查看: 265

#官方文档:https://nginx.org/en/docs/http/ngx_http_proxy_module.html

#proxy_pass 后直接跟URL url是远处主机或者本机,都可以

proxy_pass http://10.0.0.18:8080;#8080后面无uri,即无 / 符号,需要将location后面 url 附加到proxy_pass指定的url后面,此行为类似于root (指定web的家目录)

proxy_pass http://10.0.0.18:8080/; #8080后面有uri,即有 / 符号,相当于置换,即访问/web时实际返回proxy_pass后面uri内容.此行为类似于alias (定义路径别名,把访问的路径重新定义到其指定路径,文档映射的另一种机制,用于location上下文;)

在这里插入图片描述 实验环境 目标,用户发请求 通过10.0.0.8 转到10.0.0.18上

10.0.0.8 proxy 10.0.0.18 web # 两台centos8的主机; 10.0.0.100 Ubuntu系统做客户端 第一步 :设置

在18 web服务器上 首先 将nginx退出 nginx -s quit

[root@Centos18 conf]#yum -y install httpd [root@Centos18 conf]#echo rs1 server > /var/www/html/index.html #将rs1 server放到网页里 [root@Centos18 conf]#systemctl start httpd #启动httpd服务 [root@centos18 ~]#curl 10.0.0.18 #测试可以连通 rs1 server

在这里插入图片描述 在8 proxy上: 首先要定义子配置文件路径

http { ...... include /apps/nginx/conf.d/*.conf; #在配置文件的最后面添加此行,注意不要放在最前 面,会导致前面的命令无法生效 后续配置文件都放在这里; } [root@Centos8 conf.d]#vim /apps/nginx/conf/nginx.conf

在这里插入图片描述 设置代理功能;

[root@Centos8 conf.d]#vim /apps/nginx/conf.d/pc.conf 设置: proxy_pass http://10.0.0.18; nginx -t nginx -s reload #设置完成后记得检查语法和重新加载;

在这里插入图片描述 脚本;

server { listen 80; server_name www.magedu.org; root /apps/nginx/html/pc; location / { root /apps/nginx/html/pc; proxy_pass http://10.0.0.18; } }

在Ubuntu客户端上设置

vim /etc/hosts 在这里插入图片描述 测试是否可以访问: 在这里插入图片描述 第二步 测试;

为了进一步测试 在18上 创建大文件 因为是apache服务 所以要在这里建设;

[root@Centos18 html]#cd /var/www/html [root@Centos18 html]#dd if=/dev/zero of=f1.img bs=1M count=100

说明 wget --limit-rate=1024 (URL或者ip 或者连接) 从ip地址或者链接上限速下载数据; 在Ubuntu上

wget --limit-rate=1024 http://www.magedu.org/f1.img 在这里插入图片描述 第三步;查看

在8上查看 ss -nt 在这里插入图片描述 以上是一对一的代理;

设置完成;

拓展;同构和异构 在这里插入图片描述 拓展1;支持异构,肯定支持更改端口号

1、在18上;

vim /etc/httpd/conf/httpd.conf #更改端口8080 systemctl restart httpd #然后重启httpd服务

在这里插入图片描述 2、改完端口 没有 更改代理服务器;报错。502 在这里插入图片描述 3.需要在代理服务器8上更改

[root@Centos8 conf.d]#vim /apps/nginx/conf.d/pc.conf nginx -s reload #改完后重启测试

在这里插入图片描述 4.测试 重新下载一个文件 (按老师的说法,文件太小,传输速度太快,测试不了)

[root@Centos18 html]#dd if=/dev/zero of=f1.img bs=1M count=10000 #为了不必要的麻烦,我把之前创建好的 f1.img给删除了;

下载好了以后 在Ubuntu上执行卸载

wget --limit-rate=1024 http://www.magedu.org/f1.img

在这里插入图片描述 5 查看; 可以在8上看到两个连接 ss -nt 在这里插入图片描述 但是在18这proxy上 只能看到 在这里插入图片描述 并且在18上只能看到8在访问

tail -f /var/log/httpd/access_log 在这里插入图片描述 可以确认的是: 这里后端服务器是看不到客户端ip 拓展2;设置iptables 如果18proxy上设置 iptables -A INPUT -s 10.0.0.8 -j DROP

在客户端;过大概1分钟;提示访问超时

curl www.magedu.org -I

在这里插入图片描述 而如果是iptables -A INPUT -s 10.0.0.8 -j REJECT 或者将httpd服务stop 也是一样报错; 在这里插入图片描述 至此 nginx中的http反向代理全部设置完成

谢谢观赏



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3