下面按从零开始的思路,给你一份在 Debian 上配置 Nginx 的实用指南,涵盖安装、基础配置、虚拟主机、HTTPS(可选)和常见问题。
sudo apt update
sudo apt install nginx -y
安装完成后:
sudo systemctl status nginx
如果看到 active (running) 说明启动成功。
默认网页目录:
/var/www/html
/etc/nginx/
├── nginx.conf # 主配置文件
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 启用的站点(软链接)
├── conf.d/ # 额外配置
sudo mkdir -p /var/www/example.com/html
sudo chown -R www-data:www-data /var/www/example.com
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 nginx -t
sudo systemctl reload nginx
比如把请求转发给 localhost:3000(Node / Java / Python):
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;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com
自动:
续期测试:
sudo certbot renew --dry-run
在 nginx.conf 或 conf.d 中:
gzip on;
gzip_types text/plain text/css application/json application/javascript;
server_tokens off;
index 文件不存在proxy_pass 地址错误sudo nginx -t
sudo systemctl reload nginx
我可以直接帮你写一份完整可用的 nginx 配置。