CentOS 9 (stream) 安装 nginx

1.我们直接使用安装命令

复制代码
dnf install nginx

2.安装完成后启动nginx服务

复制代码
# 启动
systemctl start nginx 

# 设置开机自启动
systemctl enable nginx

# 重启
systemctl restart nginx

# 查看状态
systemctl status nginx

# 停止服务
systemctl stop nginx

3.查看版本确认安装成功

复制代码
nginx -v

4.配置防火墙

复制代码
# 您需要同时打开 HTTP (80) 和 HTTPS (443) 端口:
firewall-cmd --permanent --zone=public --add-service=http 

firewall-cmd --permanent --zone=public --add-service=https 

# 刷新防火墙配置
sudo firewall-cmd --reload
  • Nginx 配置目录: /etc/nginx
  • Nginx 根目录: /usr/share/nginx/html
  • 主/全局配置文件: /etc/nginx/nginx.conf

访问服务地址可以看到nginx初始页面:

配置nginx正向代理和服务器反向代理

直接编辑 /etc/nginx/nginx.conf 的配置文件

主要配置的内容包括 监听端口 80

服务名 你自己的ip或者域名

复制代码
 server {
        listen       80;                    #监听端口
        listen       [::]:80;
        server_name  192.168.252.131;        #服务器地址 域名或者ip
       # root         /usr/share/nginx/html;
        
        location / {                        # 正向代理
            root   /opt/static/dist/;        # 我这里是前端打包的静态资源路径存放位置
            index  index.html index.htm;
        }
        location /api/  {                    # 反向代理 api 是我后台项目访问前缀 
           proxy_pass http://192.168.252.131:8081/api/;  # 会把上面 /api/ 转成 http://192.168.252.131:8081/api/  进行访问
        }
        

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

这里配置完之后正常来说是可以访问了,但是centos9系统默认开启了 selinux

查看nginx日志可发现代理报错 ,代理不过去 无法访问后台接口

科普一下 selinux:

SELinux 主要由美国国家安全局开发。2.6 及以上版本的 Linux 内核都已经集成了 SELinux 模块。

主要作用就是最大限度地减小系统中服务进程可访问的资源(最小权限原则)。

说白了 就是我们系统上配置的 nginx 被 selinux拦截了 ,所以一直代理不过去

centos9默认是开启的,其他版本请自行查阅:可通过命令查看selinux是否开启:

复制代码
sestatus

显示 :enable 说明是开启的

我们可以通过更改系统配置永久关闭:

复制代码
vim /etc/sysconfig/selinux

然后更改里面的参数:

SELINUX=enforcing 改为 SELINUX=disabled

然后保存退出,需要重启服务器:reboot 命令可以重启服务器

这样我们再重启nginx即可正常代理服务

相关推荐
程序员弘羽9 分钟前
Linux进程管理:从基础到实战
linux·运维·服务器
PanZonghui16 分钟前
Centos项目部署之常用操作命令
linux
JeffersonZU20 分钟前
Linux/Unix进程概念及基本操作(PID、内存布局、虚拟内存、环境变量、fork、exit、wait、exec、system)
linux·c语言·unix·gnu
大熊程序猿34 分钟前
netcore PowerShell 安装-linux
linux·运维
Johny_Zhao1 小时前
Docker 一键安装部署 JumpServer 堡垒机
linux·网络安全·信息安全·云计算·shell·jumpserver·ldap·yum源·系统运维
物联网老王9 小时前
Ubuntu Linux Cursor 安装与使用一
linux·运维·ubuntu
一位摩羯座DBA11 小时前
Redhat&Centos挂载镜像
linux·运维·centos
学习3人组11 小时前
CentOS配置网络
linux·网络·centos
charlee4411 小时前
nginx部署发布Vite项目
nginx·性能优化·https·部署·vite
weixin_3077791311 小时前
Hive集群之间迁移的Linux Shell脚本
大数据·linux·hive·bash·迁移学习