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即可正常代理服务

相关推荐
物联网老王4 小时前
Ubuntu Linux Cursor 安装与使用一
linux·运维·ubuntu
一位摩羯座DBA6 小时前
Redhat&Centos挂载镜像
linux·运维·centos
学习3人组6 小时前
CentOS配置网络
linux·网络·centos
charlee446 小时前
nginx部署发布Vite项目
nginx·性能优化·https·部署·vite
weixin_307779136 小时前
Hive集群之间迁移的Linux Shell脚本
大数据·linux·hive·bash·迁移学习
漫步企鹅7 小时前
【蓝牙】Linux Qt4查看已经配对的蓝牙信息
linux·qt·蓝牙·配对
cui_win7 小时前
【网络】Linux 内核优化实战 - net.core.flow_limit_table_len
linux·运维·网络
梦在深巷、7 小时前
MySQL/MariaDB数据库主从复制之基于二进制日志的方式
linux·数据库·mysql·mariadb
冰橙子id8 小时前
linux系统安全
linux·安全·系统安全
stark张宇8 小时前
VMware 虚拟机装 Linux Centos 7.9 保姆级教程(附资源包)
linux·后端