联系QQ 284710375
首页 > 技术分享 > LNMP|WAMP
收藏

Nginx配置反向代理2022-09-03 21:23:39

大潇博客 原创文章,转载请标明出处

划重点:

Nginx通过在location中配置proxy_pass,实现反向代理服务器,proxy_pass和root目录二选一,如:

location / {

root   html; #反向代理状态下,失效

index  index.html index.htm;

proxy_pass http://www.daxiao.show; #加入proxy_pass后,root失效,直接返回代理服务器给的信息

}


补充:

Nginx反向代理服务器关键字:proxy_pass


在location下面使用,和root目录二选一

root目录帮我们寻找静态文件,反向代理时不需要再执行此步,故root失效


proxy_pass关键字后面接的形式有两种

一种是直接放代理的地址,可以是ip或网址

一种是配一组服务器


proxy_pass使用方法:

location / {

proxy_pass http://www.daxiao.show;

root   html;

index  index.html index.htm;

}

浏览器访问当前的ip地址,即可在地址栏不变的情况下,加载到接入地址返回的信息

proxy_pass代理效果展示.png


可能遇到的问题:

Nginx的反向代理默认不支持https,配置https后,reload重载nginx配置时可能会报错:

Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.

通过journalctl -xe查看详情会发现:

nginx: [emerg] https protocol requires SSL support in /usr/local/nginx...

出现这种错误,说明编译nginx时,大概率没有添加ssl模块,所以先安装ssl模块


进入编译安装的目录,使用以下命令,为Nginx添加ssl模块

./configure  --prefix=/usr/local/nginx  --with-http_ssl_module

添加ssl模块时,可能会报错:

./configure: error: SSL modules require the OpenSSL library.

You can either do not enable the modules, or install the OpenSSL library

into the system, or build the OpenSSL library statically from the source

with nginx by using --with-openssl=option.

这是因为缺少OpenSSL环境,需要手动安装

# CentOS:

yum -y install openssl-devel

# Ubuntu:

apt -y install openssl openssl-devel


添加OpenSSL库后,再次执行:

./configure  --prefix=/usr/local/nginx  --with-http_ssl_module

./configure执行完成后,再次执行:

make && make install

全部完成后,启动nginx


注意:有的代理https需要在服务器上“增加客户端证书和私钥”,有的证书无需配置,即可通过ssl模块实现https的反向代理


配置好反向代理后,浏览器访问当前反向代理服务器的ip地址,即可在地址栏不变的情况下,加载到接入地址返回的信息

这只是实现反向代理,在代理多台服务器时,还需要负载均衡策略,让被代理的服务器实现“雨露均沾”


还有一个细节:

如果proxy_pass后面为一级主域名,如:http://baidu.com, 浏览器地址会发生变更,查看浏览器header状态,发生了301或302跳转,如图:

一级域名代理.png

实际测试中,只有使用“http://主域名”时会发生跳转, “https://二级域名”正常经过nginx代理服务器,不会跳转,如图:

二级域名代理.png


博客维护不易,请点个赞再走吧!


打赏

阅读排行

大家都在搜

博客维护不易,感谢你的肯定
扫码打赏,建议金额1-10元
  • 15601023311