温馨提示×

Debian Nginx 如何安装配置

小樊
34
2025-12-25 18:14:33
栏目: 智能运维

Debian 上安装与配置 Nginx 的完整步骤

一 安装与启动

  • 更新索引并安装:sudo apt update && sudo apt install nginx -y
  • 启动并设置开机自启:sudo systemctl start nginx && sudo systemctl enable nginx
  • 查看运行状态:sudo systemctl status nginx(看到 active (running) 即正常)
  • 如启用防火墙,放行 HTTP/HTTPS:sudo ufw allow ‘Nginx Full’(或仅 HTTP:sudo ufw allow ‘Nginx HTTP’)
  • 浏览器访问服务器 IP 或域名,出现 Nginx 欢迎页表示安装成功。

二 基本站点配置

  • 配置文件路径与启用方式
    • 主配置:/etc/nginx/nginx.conf
    • 站点配置:在 /etc/nginx/sites-available/ 创建文件,使用符号链接到 /etc/nginx/sites-enabled/ 启用
    • 示例站点(/etc/nginx/sites-available/example.com):
      server {
          listen 80;
          server_name example.com www.example.com;
      
          root /var/www/example.com;
          index index.html index.htm;
      
          location / {
              try_files $uri $uri/ =404;
          }
      
          error_page 404 /404.html;
          location = /404.html { internal; }
      
          error_page 500 502 503 504 /50x.html;
          location = /50x.html { internal; }
      }
      
    • 启用站点:sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
  • 检查与生效
    • 语法检查:sudo nginx -t
    • 重新加载:sudo systemctl reload nginx
  • 默认站点
    • 也可直接编辑 /etc/nginx/sites-available/default 并 reload 使其生效。

三 启用 HTTPS 与自动续期

  • 安装 Certbot:sudo apt install certbot python3-certbot-nginx
  • 获取并自动配置证书:sudo certbot --nginx -d example.com -d www.example.com
  • 按提示选择是否重定向 HTTP→HTTPS,完成后自动续期(certbot 会创建 systemd 定时任务)。

四 常用管理与排错命令

  • 服务管理
    • 停止/启动/重启:sudo systemctl stop|start|restart nginx
    • 热重载(不中断连接):sudo systemctl reload nginx
    • 开机自启/禁用:sudo systemctl enable|disable nginx
  • 配置与日志
    • 语法检查:sudo nginx -t
    • 查看完整生效配置:sudo nginx -T
    • 实时查看日志:tail -f /var/log/nginx/access.log;tail -f /var/log/nginx/error.log。

五 进阶配置示例

  • 反向代理到本地应用(示例将 /app 代理到 127.0.0.1:3000
    location /app {
        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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
  • 配置文件结构要点
    • Nginx 配置由 main(全局)events(事件)http(HTTP 全局)server(虚拟主机)location(路径匹配) 等块组成,通常将多个 server 配置拆分到 /etc/nginx/sites-available/ 并通过 /etc/nginx/sites-enabled/ 管理,便于维护。

0