下面给你一个在 Linux 上部署 Nginx 的通用流程,以 Ubuntu / CentOS 常见发行版为例,适合新手从零开始。
sudo apt update
sudo apt install nginx -y
sudo yum install epel-release -y
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
查看状态:
sudo systemctl status nginx
浏览器访问服务器 IP:
http://你的服务器IP
看到 Welcome to nginx 说明成功。
/etc/nginx/ # 配置目录
├── nginx.conf # 主配置
├── sites-available/ # 可用站点(Ubuntu)
├── sites-enabled/ # 启用站点(软链接)
├── conf.d/ # 额外配置(CentOS)
/var/www/html/ # 默认网站目录
/var/log/nginx/ # 日志
sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/example.com
nano /var/www/example.com/html/index.html
内容:
<h1>Hello Nginx!</h1>
sudo nano /etc/nginx/sites-available/example.com
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
启用站点:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nano /etc/nginx/conf.d/example.conf
内容同上。
sudo nginx -t
sudo systemctl reload nginx
sudo ufw allow 'Nginx Full'
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
示例(反向代理):
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com
✅ 403 Forbidden
→ 目录权限 or index 文件不存在
✅ 502 Bad Gateway
→ 后端没启动 / 端口错
✅ 配置文件错误
→ nginx -t 看报错
如果你愿意,可以告诉我:
我可以直接给你一份可用的 nginx 配置。