温馨提示×

Nginx在Ubuntu中怎么配置

小樊
32
2025-12-07 04:05:54
栏目: 智能运维

Ubuntu 上配置 Nginx 的实用步骤

一 安装与启动

  • 更新索引并安装:sudo apt update && sudo apt install -y nginx
  • 启动并设置开机自启:sudo systemctl start nginx && sudo systemctl enable nginx
  • 验证:在浏览器访问服务器的 IP 或域名,应看到 Nginx 欢迎页;或执行:sudo systemctl status nginx

二 配置文件结构与目录

  • 主配置:/etc/nginx/nginx.conf(顶层包含 events、http 等)
  • 站点配置:/etc/nginx/sites-available/(存放各站点配置)
  • 启用站点:/etc/nginx/sites-enabled/(通过符号链接启用)
  • 默认根目录:/var/www/html
  • 日志:/var/log/nginx/error.log/var/log/nginx/access.log
  • 常用操作:编辑站点后先测试语法 sudo nginx -t,再应用 sudo systemctl reload nginx

三 创建第一个站点 Server Block

  • 新建配置: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;
    }
    
    error_page **404** /404.html;
    location = /404.html { root /var/www/example.com; }
    
    error_page **500 502 503 504** /50x.html;
    location = /50x.html { root /var/www/example.com; }
    

    }

  • 创建目录与测试页: sudo mkdir -p /var/www/example.com/html echo “Hello World” | sudo tee /var/www/example.com/html/index.html

  • 启用站点并验证: sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t && sudo systemctl reload nginx

  • 权限建议:sudo chown -R www-data:www-data /var/www/example.com && chmod -R 755 /var/www/example.com

四 防火墙与端口放行

  • 使用 UFW:sudo ufw allow ‘Nginx Full’(同时放行 80/443
  • 查看状态:sudo ufw status
  • 云服务器注意:在控制台安全组放行 80/443

五 可选配置 SSL 与常用排错

  • 申请并自动配置 Let’s Encrypt 证书: sudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com
  • 常用排错:
    • 语法检查:sudo nginx -t
    • 重载服务:sudo systemctl reload nginx
    • 查看错误日志:sudo tail -f /var/log/nginx/error.log
    • 服务状态:sudo systemctl status nginx

0