在 CentOS 服务器上配置 Nginx 可以分为以下几个步骤:
首先,确保你的 CentOS 系统是最新的,然后安装 Nginx:
# 更新系统
sudo yum update -y
# 安装 EPEL 仓库(Extra Packages for Enterprise Linux)
sudo yum install epel-release -y
# 安装 Nginx
sudo yum install nginx -y
安装完成后,启动 Nginx 并设置为开机自启:
# 启动 Nginx
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
确保 Nginx 正在运行:
sudo systemctl status nginx
如果一切正常,你应该能看到 active (running)
的状态。
如果你的服务器启用了防火墙(如 firewalld
),需要开放 HTTP(80)和 HTTPS(443)端口:
# 开放 80 端口(HTTP)
sudo firewall-cmd --permanent --add-service=http
# 开放 443 端口(HTTPS)
sudo firewall-cmd --permanent --add-service=https
# 重新加载防火墙配置
sudo firewall-cmd --reload
在浏览器中输入你的服务器 IP 地址,如果看到 Nginx 的默认欢迎页面,说明安装成功。
Nginx 的主要配置文件位于 /etc/nginx/nginx.conf
,而站点配置文件通常放在 /etc/nginx/conf.d/
目录下。
创建一个新的配置文件(例如 example.conf
):
sudo vi /etc/nginx/conf.d/example.conf
添加以下内容(替换 your_domain
和 root_path
):
server {
listen 80;
server_name your_domain.com www.your_domain.com;
root /var/www/example;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
sudo mkdir -p /var/www/example
sudo chown -R nginx:nginx /var/www/example
sudo chmod -R 755 /var/www/example
echo "<h1>Welcome to Nginx!</h1>" | sudo tee /var/www/example/index.html
sudo nginx -t
如果没有错误,重新加载 Nginx:
sudo systemctl reload nginx
使用 Let's Encrypt 免费 SSL 证书:
sudo yum install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your_domain.com -d www.your_domain.com
sudo certbot renew --dry-run
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx
sudo nginx -t
/var/log/nginx/access.log
/var/log/nginx/error.log
通过以上步骤,你应该已经成功在 CentOS 上配置了 Nginx。如果有其他需求(如负载均衡、反向代理等),可以进一步修改配置文件。