centos

如何在CentOS Stream 8上配置Nginx

小樊
42
2025-07-02 13:33:31
栏目: 智能运维

在CentOS Stream 8上配置Nginx涉及几个步骤,包括安装Nginx、配置防火墙以及启动和启用Nginx服务。以下是详细的步骤:

1. 安装Nginx

首先,确保你的系统是最新的,并且已经安装了EPEL仓库(Extra Packages for Enterprise Linux),因为Nginx可能不在默认的CentOS仓库中。

sudo dnf update -y
sudo dnf install epel-release -y

接下来,安装Nginx:

sudo dnf install nginx -y

2. 启动和启用Nginx服务

安装完成后,启动Nginx服务并设置开机自启:

sudo systemctl start nginx
sudo systemctl enable nginx

3. 配置防火墙

CentOS Stream 8默认使用firewalld作为防火墙管理工具。你需要允许HTTP和HTTPS流量通过防火墙。

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

4. 验证Nginx配置

确保Nginx配置文件没有语法错误:

sudo nginx -t

如果配置文件没有问题,你会看到类似以下的输出:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

5. 访问Nginx默认页面

打开浏览器,访问你的服务器IP地址或域名,你应该能看到Nginx的默认欢迎页面。

6. 自定义Nginx配置(可选)

如果你需要自定义Nginx配置,可以编辑/etc/nginx/nginx.conf文件或创建一个新的配置文件并将其包含在/etc/nginx/conf.d/目录下。

例如,创建一个新的配置文件:

sudo nano /etc/nginx/conf.d/example.conf

添加以下内容:

server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    location = /404.html {
        root /var/www/html;
    }
}

保存并退出编辑器,然后重新加载Nginx配置:

sudo systemctl reload nginx

7. 安全配置(可选)

为了提高安全性,你可以考虑以下配置:

启用HTTPS

你可以使用Let’s Encrypt免费获取SSL/TLS证书:

sudo dnf install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

按照提示完成证书的安装和配置。

通过以上步骤,你应该能够在CentOS Stream 8上成功配置Nginx。

0
看了该问题的人还看了