zl程序教程

您现在的位置是:首页 >  系统

当前栏目

Linux(centos7)安装nginx并配置代理

2023-09-27 14:25:57 时间
本文介绍一下如何在linux下安装nginx,并配置反向代理,使我们可以通过子域名访问不同的接口。
前言

本文介绍一下如何在linux下安装nginx 并配置反向代理 使我们可以通过子域名访问不同的接口。


安装并启动nignx

通过yum进行安装


[root server ~]# yum install nginx

[root server ~]# service nginx start

复制代码


然后进入浏览器 访问服务器ip 如果看到


Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.

Commercial support is available at nginx.com.

Thank you for using nginx.


恭喜你 你成功了

如果不成功 检查防火墙是否放过了80端口 放开80端口即可。


配置文件

当你执行nginx -t得时候 nginx会去测试你得配置文件得语法 并告诉你配置文件是否写得正确 同时也告诉了你配置文件得路径


# nginx -t

nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok

nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful

复制代码


反向代理

编辑nginx.conf文件


vim nginx.conf

复制代码


在文件中添加或修改:


server {

 listen 80; //监听80端口

 server_name www.xxx.xxx; //请求地址

 location / {

 proxy_pass http://localhost:8081; //代理的地址和端口

 proxy_set_header Host $host;

 proxy_set_header X-Real-IP $remote_addr;

 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

复制代码


这样设置后 凡是www.xxx.xxx这个域名的请求都会代理到8081端口上。

可以在conf文件中有多个server 这样就能实现不同的二级域名代理到不同的端口上。


重启nginx
[root server ~]# service nginx restart

复制代码


如果重启出错 如下 重启nginx出错


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


终端中输入nginx -t命令就可以查看具体问题了。


日志

nginx日志地址为/var/log/nginx/目录下

如果想下载日志到本地查看 可以


scp root [服务端ip]:/var/log/nginx/xxx.xxx [本地目录 如 ~/Downloads/]

复制代码


无法访问

配置代理后依然访问不了

这里指的是ping不通 报错Unknown host的情况

这是因为代理的域名没有加入DNS解析 在阿里云中添加二级域名DNS解析即可

添加完需要等一段时间才行