Nginx在Ubuntu 22.04上的安装与优化配置指南 1. 为什么选择Nginx作为Web服务器Nginx已经成为现代Web架构中的核心组件根据W3Techs的最新统计全球超过40%的网站都在使用Nginx。相比传统的Apache服务器Nginx采用事件驱动的异步架构能够轻松应对C10K问题即单机同时处理上万个连接。我在实际生产环境中部署过数百个Nginx实例其内存占用仅为Apache的1/5到1/10特别是在高并发场景下优势更为明显。Ubuntu 22.04 LTSJammy Jellyfish作为长期支持版本提供了5年的安全更新支持周期。这个版本中的Nginx软件包经过Canonical的严格测试与系统其他组件的兼容性有充分保障。我建议所有生产环境都优先考虑LTS版本避免使用非LTS版本可能带来的频繁升级问题。2. 安装前的系统准备2.1 更新系统软件包在开始安装前建议先执行以下命令更新系统sudo apt update sudo apt upgrade -y sudo apt autoremove重要提示生产服务器建议在非业务高峰时段执行升级操作避免意外情况影响线上服务。我曾经遇到过因内核升级导致网卡驱动不兼容的情况所以建议先在测试环境验证。2.2 检查防火墙配置Ubuntu 22.04默认使用ufw防火墙需要确保HTTP(80)和HTTPS(443)端口开放sudo ufw allow Nginx Full sudo ufw enable sudo ufw status3. Nginx安装的三种方式及选择建议3.1 使用官方APT仓库安装推荐这是我最推荐的方式可以获得最新稳定版并自动接收安全更新sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo gpg --dearmor -o /usr/share/keyrings/nginx-archive-keyring.gpg echo deb [signed-by/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu lsb_release -cs nginx | sudo tee /etc/apt/sources.list.d/nginx.list sudo apt update sudo apt install nginx3.2 使用Ubuntu默认仓库安装这种方式安装的版本可能较旧但稳定性有保障sudo apt install nginx3.3 从源码编译安装适合需要自定义模块或特定功能的高级用户wget https://nginx.org/download/nginx-1.25.3.tar.gz tar zxvf nginx-1.25.3.tar.gz cd nginx-1.25.3 ./configure --with-http_ssl_module --with-http_v2_module make sudo make install经验之谈除非有特殊需求否则建议使用官方APT仓库。我曾经为了一个定制模块选择源码编译结果每次升级都要重新编译维护成本很高。4. Nginx基础配置详解4.1 核心目录结构了解这些目录是管理Nginx的基础/etc/nginx/ ├── nginx.conf # 主配置文件 ├── conf.d/ # 额外配置文件 ├── sites-available/ # 可用站点配置 ├── sites-enabled/ # 已启用站点配置符号链接 ├── modules-available/ ├── modules-enabled/ └── snippets/ # 可复用的配置片段4.2 主配置文件优化编辑/etc/nginx/nginx.conf建议修改以下参数user www-data; worker_processes auto; # 自动匹配CPU核心数 worker_rlimit_nofile 100000; # 提高文件描述符限制 events { worker_connections 4096; # 每个worker的最大连接数 multi_accept on; # 一次接受所有新连接 use epoll; # Ubuntu默认使用epoll } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_types text/plain text/css application/json application/javascript text/xml; }4.3 虚拟主机配置示例在/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 index.htm; location / { try_files $uri $uri/ 404; } location ~ /\.ht { deny all; } }然后启用配置sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t # 测试配置 sudo systemctl reload nginx5. 安全加固措施5.1 禁用服务器令牌在nginx.conf的http块中添加server_tokens off;5.2 配置SSL/TLS使用Lets Encrypt免费证书sudo apt install certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com证书会自动续期建议配置证书强加密参数ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m;5.3 防止常见攻击在server块中添加安全头add_header X-Frame-Options SAMEORIGIN; add_header X-XSS-Protection 1; modeblock; add_header X-Content-Type-Options nosniff; add_header Referrer-Policy strict-origin;6. 性能调优实战6.1 启用HTTP/2在监听443端口的server块中添加listen 443 ssl http2;6.2 静态资源缓存配置长期缓存静态资源location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 365d; add_header Cache-Control public, no-transform; }6.3 启用Brotli压缩先安装Brotli模块sudo apt install libnginx-mod-brotli然后在配置中添加brotli on; brotli_types text/plain text/css application/javascript application/json text/xml;7. 监控与日志分析7.1 配置访问日志格式在http块中定义自定义日志格式log_format main $remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for;7.2 使用GoAccess分析日志安装并实时监控访问日志sudo apt install goaccess goaccess /var/log/nginx/access.log -o /var/www/html/report.html --log-formatCOMBINED --real-time-html8. 常见问题排查8.1 502 Bad Gateway错误可能原因及解决方案后端服务未启动检查PHP-FPM或其他应用服务器状态权限问题确保/var/lib/nginx目录权限正确资源不足检查系统内存和连接数限制8.2 地址已被占用错误使用以下命令查找冲突进程sudo ss -tulnp | grep :808.3 性能突然下降检查方向当前连接数netstat -an | grep :80 | wc -l系统负载top或htop磁盘I/Oiostat -x 19. 进阶配置技巧9.1 负载均衡配置配置上游服务器组upstream backend { server 10.0.0.1:8080 weight5; server 10.0.0.2:8080; server 10.0.0.3:8080 backup; } server { location / { proxy_pass http://backend; } }9.2 地理位置限制阻止特定国家IP访问geo $blocked_country { default 0; 1.0.0.0/24 1; # 示例IP段 } server { if ($blocked_country) { return 403; } }9.3 灰度发布配置基于Cookie的流量分割split_clients ${remote_addr}${http_user_agent} $variant { 10% v2; * v1; } server { location / { if ($variant v2) { proxy_pass http://new_version; } proxy_pass http://old_version; } }10. 维护与管理命令常用系统命令备忘# 检查配置语法 sudo nginx -t # 重新加载配置不中断服务 sudo systemctl reload nginx # 完全重启 sudo systemctl restart nginx # 查看运行状态 systemctl status nginx # 设置开机启动 sudo systemctl enable nginx # 查看错误日志实时监控 sudo tail -f /var/log/nginx/error.log在实际运维中我习惯将常用检查项写成脚本定期执行。比如这个简单的健康检查脚本#!/bin/bash response$(curl -sI http://localhost | head -n 1 | cut -d -f2) [ $response 200 ] || systemctl restart nginx

本月热点