温馨提示×

debian nginx怎么配置

小樊
46
2026-09-03 11:34:59
栏目: 智能运维

下面给你一个从零开始在 Debian 上配置 Nginx 的实用指南,涵盖安装、基础配置、虚拟主机、HTTPS,适合新手和服务器部署。


一、安装 Nginx(Debian)

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      # 平滑重载配置

二、Nginx 目录结构(Debian)

/etc/nginx/
├── nginx.conf            # 主配置文件
├── sites-available/      # 可用站点配置
├── sites-enabled/        # 启用的站点(软链接)
├── conf.d/               # 额外配置

网站根目录默认:

/var/www/html

三、基础站点配置(单站点)

1️⃣ 修改默认站点

编辑:

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

四、配置多个网站(虚拟主机)

1️⃣ 新建站点配置

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;
    }
}

2️⃣ 启用站点

sudo ln -s /etc/nginx/sites-available/site1.conf /etc/nginx/sites-enabled/

3️⃣ 禁用默认站点(可选)

sudo rm /etc/nginx/sites-enabled/default

五、配置 HTTPS(Let’s Encrypt 免费证书)

1️⃣ 安装 Certbot

sudo apt install certbot python3-certbot-nginx -y

2️⃣ 自动申请并配置

sudo certbot --nginx -d example.com -d www.example.com

Certbot 会自动:

  • 申请证书
  • 修改 Nginx 配置
  • 配置 80 → 443 跳转

3️⃣ 自动续期测试

sudo certbot renew --dry-run

六、常见实用配置

✅ 反向代理(如 Node / Java)

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;
    }
}

✅ 开启 Gzip

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

如果你愿意,可以告诉我:

  • ✅ 是 静态网站 / 反向代理 / API
  • ✅ 是否用 Docker
  • ✅ Debian 版本(11 / 12)

我可以直接帮你写完整可复制的配置文件

0