1. Ubuntu 下 Nginx 的完整安装与配置指南
在 Linux 服务器环境中,Nginx 凭借其高性能、低资源占用和灵活的配置特性,已成为最受欢迎的 Web 服务器之一。作为一名长期使用 Ubuntu 部署 Web 应用的老手,我将分享从安装到生产环境配置的完整流程,特别是针对前后端分离项目的优化设置。
2. Nginx 安装与基础配置
2.1 安装 Nginx 的正确姿势
在 Ubuntu 上安装 Nginx 非常简单,但有几个关键细节需要注意:
bash复制# 更新软件包索引(首次安装前必须执行)
sudo apt update
# 安装 Nginx 主程序
sudo apt install nginx -y
安装完成后,系统会自动创建 nginx 服务并启动。验证安装是否成功:
bash复制# 检查服务状态
systemctl status nginx
# 测试访问(应返回默认欢迎页)
curl -I 127.0.0.1
注意:如果服务器启用了防火墙(如 ufw),需要放行 HTTP/HTTPS 端口:
bash复制sudo ufw allow 'Nginx Full'
2.2 目录结构与配置文件解析
Nginx 的配置文件主要分布在以下位置:
- 主配置文件:
/etc/nginx/nginx.conf - 模块配置:
/etc/nginx/modules-enabled/*.conf - 站点配置:
/etc/nginx/sites-available/(可用配置) - 启用站点:
/etc/nginx/sites-enabled/(实际加载的配置)
生产环境最佳实践是:
- 在
sites-available中创建配置文件 - 通过软链接到
sites-enabled启用配置 - 使用
nginx -t测试配置语法 - 重载配置
systemctl reload nginx
3. 前后端分离项目配置实战
3.1 基础前端项目部署
假设前端项目构建产物位于 /var/www/html,典型配置如下:
nginx复制server {
listen 80;
server_name yourdomain.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
关键点说明:
try_files指令处理前端路由的 404 问题- 对于 Vue/React 等 SPA 应用必须包含
/index.html回退 - 静态资源应设置适当的缓存头
3.2 后端 API 代理配置
前后端分离架构中,Nginx 需要代理后端 API 请求:
nginx复制location /api/ {
proxy_pass http://localhost:8080/;
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_connect_timeout 60s;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
}
经验之谈:
proxy_pass结尾的/决定 URL 重写行为- 必须设置正确的
Host头,否则后端可能无法识别域名 - 文件上传接口需要调整
client_max_body_size(默认仅 1M)
3.3 生产环境完整配置示例
结合参考文章中的配置,优化后的生产级配置如下:
nginx复制server {
listen 80;
server_name example.com;
# 前端配置
root /var/www/dist;
index index.html;
# 前端路由处理
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# 后端API代理
location /prod-api/ {
proxy_pass http://127.0.0.1:8080/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
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;
# 文件上传大小限制
client_max_body_size 20M;
}
# 上传目录特殊处理
location /profile/upload/ {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
4. 性能调优与安全加固
4.1 基础性能优化参数
在 /etc/nginx/nginx.conf 的 http 块中添加:
nginx复制http {
# 启用gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 连接优化
keepalive_timeout 65;
keepalive_requests 1000;
# 静态文件缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
4.2 安全加固措施
-
隐藏 Nginx 版本信息:
nginx复制server_tokens off; -
禁用不必要的 HTTP 方法:
nginx复制if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; } -
预防常见攻击:
nginx复制# 禁止iframe嵌入 add_header X-Frame-Options "SAMEORIGIN"; # XSS防护 add_header X-XSS-Protection "1; mode=block"; # 内容类型嗅探防护 add_header X-Content-Type-Options "nosniff";
5. 常见问题排查指南
5.1 403 Forbidden 错误
可能原因及解决方案:
-
权限问题:确保 Nginx 用户(通常为 www-data)对 web 目录有读取权限
bash复制chown -R www-data:www-data /var/www/html chmod -R 755 /var/www/html -
SELinux 限制(如果启用):
bash复制chcon -R -t httpd_sys_content_t /var/www/html
5.2 502 Bad Gateway
排查步骤:
-
检查后端服务是否运行:
bash复制
systemctl status your-backend-service -
检查端口是否正确:
bash复制
netstat -tulnp | grep 8080 -
调整 Nginx 超时设置:
nginx复制proxy_connect_timeout 60s; proxy_read_timeout 600s;
5.3 静态资源加载异常
典型问题:
- 路径错误:检查
root指令位置,相对路径基于location匹配 - MIME 类型错误:确保配置中包含:
nginx复制include /etc/nginx/mime.types; default_type application/octet-stream;
6. 进阶配置技巧
6.1 多站点配置管理
专业做法是为每个站点创建独立配置文件:
bash复制# 创建站点配置
sudo nano /etc/nginx/sites-available/example.com
# 启用配置
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
# 测试并重载
sudo nginx -t && sudo systemctl reload nginx
6.2 HTTPS 配置最佳实践
使用 Let's Encrypt 免费证书:
bash复制# 安装 certbot
sudo apt install certbot python3-certbot-nginx
# 获取证书(交互式)
sudo certbot --nginx -d example.com -d www.example.com
自动续期配置:
bash复制# 测试续期
sudo certbot renew --dry-run
# 添加定时任务(每天检查)
(crontab -l ; echo "0 12 * * * /usr/bin/certbot renew --quiet") | crontab -
6.3 日志分析与监控
-
自定义日志格式:
nginx复制log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; -
使用 GoAccess 实时分析:
bash复制sudo apt install goaccess goaccess /var/log/nginx/access.log --log-format=COMBINED
7. 维护与管理命令速查
| 操作 | 命令 | 说明 |
|---|---|---|
| 测试配置 | sudo nginx -t |
检查语法错误 |
| 重载配置 | sudo systemctl reload nginx |
不中断服务加载新配置 |
| 完全重启 | sudo systemctl restart nginx |
强制重新启动 |
| 查看状态 | systemctl status nginx |
检查运行状态 |
| 查看错误 | journalctl -u nginx -xe |
排查启动问题 |
| 监控请求 | tail -f /var/log/nginx/access.log |
实时查看访问日志 |
8. 个人实战经验分享
在实际生产环境中部署 Nginx 时,有几个容易忽视但至关重要的细节:
-
连接数优化:
- 调整
worker_connections(默认 768)根据服务器内存设置 - 计算最大并发:
worker_processes * worker_connections
- 调整
-
Buffer 大小调整:
nginx复制proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k;这对大流量 API 响应至关重要
-
TCP 优化:
nginx复制sendfile on; tcp_nopush on; tcp_nodelay on;提升静态文件传输效率
-
调试技巧:
- 临时修改日志级别:
nginx复制error_log /var/log/nginx/error.log debug; - 获取完整请求头:
nginx复制add_header X-Debug-$host $host; add_header X-Debug-Real-IP $remote_addr;
- 临时修改日志级别:
最后提醒:每次修改配置后,务必先运行 nginx -t 测试语法,再执行重载操作。我曾因跳过测试步骤导致生产环境服务中断,这个教训值得所有运维人员谨记。