下面给你一个从零开始在 Debian 上配置 Nginx 的实用指南,涵盖安装、基础配置、虚拟主机、HTTPS,适合新手和服务器部署。
sudo apt update
sudo apt install nginx -y
安装后常用命令:
sudo systemctl status nginx # 查看状态
sudo systemctl start nginx # 启动
sudo systemctl enable nginx # 开机自启
sudo systemctl restart nginx # 重启
sudo systemctl reload nginx # 平滑重载配置
/etc/nginx/
├── nginx.conf # 主配置文件
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 启用的站点(软链接)
├── conf.d/ # 额外配置
网站根目录默认:
/var/www/html
编辑:
sudo nano /etc/nginx/sites-available/default
示例(静态网站):
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;
}
}
测试配置:
sudo nginx -t
重载:
sudo systemctl reload nginx
sudo nano /etc/nginx/sites-available/site1.conf
server {
listen 80;
server_name site1.com;
root /var/www/site1;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
sudo ln -s /etc/nginx/sites-available/site1.conf /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com
Certbot 会自动:
sudo certbot renew --dry-run
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;
}
}
在 nginx.conf 或站点中:
gzip on;
gzip_types text/css application/javascript image/svg+xml;
location ~ /\. {
deny all;
}
sudo ufw allow 'Nginx Full'
sudo nginx -t
journalctl -u nginx
tail -f /var/log/nginx/error.log
如果你愿意,可以告诉我:
我可以直接帮你写完整可复制的配置文件。