在CentOS Stream 8上配置Nginx涉及几个步骤,包括安装Nginx、配置防火墙以及启动和启用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
安装完成后,启动Nginx服务并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
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
确保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
打开浏览器,访问你的服务器IP地址或域名,你应该能看到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
为了提高安全性,你可以考虑以下配置:
你可以使用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。