Nginx 实战指南:从零到精通,适合初学者和企业的完整教程

发布时间:2026/6/10 8:01:08
Nginx 实战指南:从零到精通,适合初学者和企业的完整教程 1. Nginx 是什么Nginx发音为engine-x是一个高性能的 HTTP 和反向代理服务器也是一个 IMAP/POP3/SMTP 代理服务器。它由俄罗斯程序员 Igor Sysoev 开发最初是为了解决 C10K 问题即单机同时处理 1 万个连接而设计的。1.1 Nginx 的核心特点高性能采用事件驱动、异步非阻塞架构内存占用少并发能力强高可靠性稳定性极佳可以 7×24 小时不间断运行模块化设计功能可以通过模块灵活扩展配置简单配置文件结构清晰易于理解和维护热部署支持不停止服务更新配置和升级版本2. Nginx 解决了什么问题2.1 没有 Nginx 的时代在 Nginx 出现之前Web 服务器市场主要被 Apache 统治。Apache 采用多进程/多线程模型每个连接需要一个进程或线程来处理# Apache 的传统工作模式preforkIfModule mpm_prefork_moduleStartServers5MinSpareServers5MaxSpareServers10MaxClients150MaxRequestsPerChild0/IfModule存在的问题内存消耗大每个连接都需要独立的进程/线程并发能力有限当并发连接数达到几千时系统资源迅速耗尽C10K 问题难以应对上万级别的并发连接静态资源处理效率低动态内容和静态资源使用相同处理方式2.2 常见的替代方案Apache HTTP Server最传统的 Web 服务器模块丰富但并发性能有限Lighttpd轻量级 Web 服务器性能较好但生态不如 NginxIISWindows 平台的 Web 服务器Tomcat/JettyJava 应用服务器内置 HTTP 服务Node.js使用 JavaScript 编写的 HTTP 服务器3. Nginx 适合什么场景3.1 小公司/初创公司场景# 简单网站配置示例 server { listen 80; server_name www.example.com; # 静态资源服务 location /static/ { root /var/www/html; expires 30d; # 缓存30天 } # 动态请求转发 location / { proxy_pass http://localhost:3000; # 转发到Node.js应用 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }适用场景个人博客/小型网站处理静态文件和简单的动态请求API 网关统一管理后端服务的 API 接口负载均衡将流量分发到多个后端服务器SSL 终端统一处理 HTTPS 加密解密3.2 大公司/高并发场景# 大型电商网站配置示例 upstream backend_servers { zone backend 64k; least_conn; # 最少连接算法 server 10.0.1.1:8080 weight3 max_fails3 fail_timeout30s; server 10.0.1.2:8080 weight2 max_fails3 fail_timeout30s; server 10.0.1.3:8080 weight2 max_fails3 fail_timeout30s; server 10.0.1.4:8080 backup; # 备份服务器 } server { listen 443 ssl http2; server_name shop.example.com; ssl_certificate /etc/nginx/ssl/fullchain.pem; ssl_certificate_key /etc/nginx/ssl/privkey.pem; # 限流配置 limit_req_zone $binary_remote_addr zoneapi:10m rate10r/s; location /api/ { limit_req zoneapi burst20 nodelay; proxy_pass http://backend_servers; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503; } # 静态资源CDN回源 location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { proxy_pass http://cdn.example.com; proxy_cache_valid 200 302 1h; } }适用场景高并发网站电商、社交、新闻门户等微服务网关作为服务网格的入口网关CDN 边缘节点内容分发网络的缓存服务器API 聚合层聚合多个后端服务的 API安全防护WAFWeb 应用防火墙前端4. Nginx 本地部署实战4.1 安装 Nginx以 Ubuntu 为例# 更新包列表sudoaptupdate# 安装 Nginxsudoaptinstallnginx-y# 启动 Nginxsudosystemctl start nginx# 设置开机自启sudosystemctlenablenginx# 检查状态sudosystemctl status nginx# 测试访问curlhttp://localhost4.2 目录结构说明/etc/nginx/ ├── nginx.conf # 主配置文件 ├── conf.d/ # 额外的配置文件目录 ├── sites-available/ # 可用的站点配置 ├── sites-enabled/ # 已启用的站点配置符号链接 ├── modules-available/ # 可用模块 ├── modules-enabled/ # 已启用模块 └── ssl/ # SSL证书目录自定义 /var/log/nginx/ ├── access.log # 访问日志 └── error.log # 错误日志 /var/www/html/ # 默认网站根目录4.3 基本配置检查# 测试配置文件语法sudonginx-t# 查看 Nginx 版本和编译参数nginx-V# 重新加载配置不中断服务sudonginx-sreload# 停止 Nginxsudonginx-sstop# 优雅停止处理完当前请求sudonginx-squit5. SSL/TLS 证书部署5.1 为什么需要 SSL 证书数据加密防止传输过程中被窃听身份验证确保访问的是真正的服务器数据完整性防止数据在传输中被篡改SEO 优势Google 等搜索引擎优先收录 HTTPS 网站浏览器信任现代浏览器标记 HTTP 站点为不安全5.2 获取 SSL 证书的三种方式方式一Let’s Encrypt免费# 安装 certbotsudoaptinstallcertbot python3-certbot-nginx-y# 为域名申请证书sudocertbot--nginx-dexample.com-dwww.example.com# 自动续期测试sudocertbot renew --dry-run方式二自签名证书测试环境# 生成私钥openssl genrsa-outprivate.key2048# 生成证书签名请求openssl req-new-keyprivate.key-outcsr.csr# 生成自签名证书openssl x509-req-days365-incsr.csr-signkeyprivate.key-outcertificate.crt# 配置 Nginxssl_certificate /path/to/certificate.crt;ssl_certificate_key /path/to/private.key;方式三商业证书生产环境从 DigiCert、GlobalSign、Symantec 等机构购买提供更高级别的信任保障。5.3 Nginx SSL 配置最佳实践server { listen 443 ssl http2; server_name example.com; # 证书路径 ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; # SSL 协议配置 ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; # 密码套件 ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512; # 会话缓存 ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; # HSTS 头 add_header Strict-Transport-Security max-age31536000; includeSubDomains always; # 其他配置... }6. Nginx 私有化部署6.1 容器化部署Docker# Dockerfile FROM nginx:alpine # 复制配置文件 COPY nginx.conf /etc/nginx/nginx.conf COPY conf.d/ /etc/nginx/conf.d/ COPY ssl/ /etc/nginx/ssl/ COPY html/ /usr/share/nginx/html/ # 暴露端口 EXPOSE 80 443 # 启动 Nginx CMD [nginx, -g, daemon off;]# docker-compose.ymlversion:3.8services:nginx:build:.ports:-80:80-443:443volumes:-./logs:/var/log/nginx-./ssl:/etc/nginx/sslrestart:unless-stoppednetworks:-webnetnetworks:webnet:driver:bridge6.2 Kubernetes 部署在 Kubernetes 中部署 Nginx通常需要以下资源ConfigMap存放 nginx.conf 配置、Secret存放 SSL 证书、Deployment管理 Pod 副本、Service内部负载均衡以及Ingress对外暴露 HTTPS 服务。1. 创建 ConfigMapnginx 配置# nginx-config.yamlapiVersion:v1kind:ConfigMapmetadata:name:nginx-configdata:nginx.conf:|events { worker_connections 1024; } http { server { listen 80; server_name example.com; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name example.com; ssl_certificate /etc/nginx/ssl/tls.crt; ssl_certificate_key /etc/nginx/ssl/tls.key; location / { root /usr/share/nginx/html; index index.html; } } }2. 创建 SecretSSL 证书# ssl-secret.yamlapiVersion:v1kind:Secretmetadata:name:ssl-certificatetype:kubernetes.io/tlsdata:# 以下为占位值请替换为实际 base64 编码的证书和密钥tls.crt:base64-encoded-certtls.key:base64-encoded-key生成 base64 证书base64 -w0 /path/to/fullchain.pem3. 创建 Deployment Service# nginx-deployment.yamlapiVersion:apps/v1kind:Deploymentmetadata:name:nginx-deploymentspec:replicas:3selector:matchLabels:app:nginxtemplate:metadata:labels:app:nginxspec:containers:-name:nginximage:nginx:alpineports:-containerPort:80-containerPort:443volumeMounts:-name:nginx-configmountPath:/etc/nginx/nginx.confsubPath:nginx.conf-name:ssl-certsmountPath:/etc/nginx/sslvolumes:-name:nginx-configconfigMap:name:nginx-config-name:ssl-certssecret:secretName:ssl-certificate---apiVersion:v1kind:Servicemetadata:name:nginx-servicespec:selector:app:nginxports:-port:80targetPort:80name:http-port:443targetPort:443name:httpstype:ClusterIP4. 创建 Ingress对外暴露 HTTPS# nginx-ingress.yamlapiVersion:networking.k8s.io/v1kind:Ingressmetadata:name:nginx-ingressannotations:nginx.ingress.kubernetes.io/ssl-redirect:truespec:ingressClassName:nginxtls:-hosts:-example.comsecretName:ssl-certificaterules:-host:example.comhttp:paths:-path:/pathType:Prefixbackend:service:name:nginx-serviceport:number:443部署命令# 按顺序创建资源kubectl apply-fnginx-config.yaml kubectl apply-fssl-secret.yaml kubectl apply-fnginx-deployment.yaml kubectl apply-fnginx-ingress.yaml# 验证kubectl get pods-lappnginx kubectl get ingress7. Nginx 核心功能实战示例以下 30 个实战示例覆盖了 Nginx 最常见的应用场景从基础静态服务到高级负载均衡策略每个示例均可直接复制使用。7.1 静态资源服务示例 1基本静态文件服务器server { listen 80; server_name static.example.com; root /var/www/html; index index.html; location / { try_files $uri $uri/ 404; } }示例 2多目录静态资源server { listen 80; server_name assets.example.com; location /images/ { alias /data/images/; } location /videos/ { alias /data/videos/; } location /docs/ { alias /data/documents/; } }示例 3静态资源缓存控制server { listen 80; server_name cdn.example.com; root /var/www/cdn; location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control public, immutable; } location ~* \.(pdf|zip|tar|gz)$ { expires 7d; add_header Cache-Control public; } }示例 4目录列表浏览server { listen 80; server_name files.example.com; root /data/public; autoindex on; autoindex_exact_size off; autoindex_localtime on; charset utf-8; }示例 5跨域资源共享CORSserver { listen 80; server_name api.example.com; location / { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods GET, POST, OPTIONS; add_header Access-Control-Allow-Headers DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range; add_header Access-Control-Expose-Headers Content-Length,Content-Range; if ($request_method OPTIONS) { add_header Access-Control-Max-Age 86400; add_header Content-Type text/plain; charsetutf-8; add_header Content-Length 0; return 204; } } }7.2 反向代理示例 6基本反向代理server { listen 80; server_name app.example.com; location / { 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; proxy_set_header X-Forwarded-Proto $scheme; } }示例 7WebSocket 反向代理server { listen 80; server_name ws.example.com; location /ws/ { proxy_pass http://backend:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; proxy_set_header Host $host; proxy_read_timeout 86400; } }示例 8按路径分发到不同后端server { listen 80; server_name portal.example.com; location /api/ { proxy_pass http://api_backend:8080/; } location /admin/ { proxy_pass http://admin_backend:8081/; } location /blog/ { proxy_pass http://blog_backend:8082/; } location / { proxy_pass http://frontend:3000; } }示例 9HTTPS 反向代理server { listen 443 ssl http2; server_name secure.example.com; ssl_certificate /etc/nginx/ssl/cert.pem; ssl_certificate_key /etc/nginx/ssl/key.pem; location / { proxy_pass http://127.0.0.1:8080; proxy_set_header X-Forwarded-Proto https; } }示例 10反向代理超时与缓冲优化server { listen 80; server_name slow-api.example.com; location / { proxy_pass http://backend:8080; proxy_connect_timeout 30s; proxy_read_timeout 120s; proxy_send_timeout 60s; proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; } }7.3 负载均衡示例 11轮询负载均衡upstream backend_round_robin { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; } server { listen 80; server_name lb.example.com; location / { proxy_pass http://backend_round_robin; } }示例 12加权负载均衡upstream backend_weighted { server 192.168.1.10:8080 weight5; server 192.168.1.11:8080 weight3; server 192.168.1.12:8080 weight1; } server { listen 80; server_name weighted-lb.example.com; location / { proxy_pass http://backend_weighted; } }示例 13IP Hash 会话保持upstream backend_ip_hash { ip_hash; server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; } server { listen 80; server_name sticky.example.com; location / { proxy_pass http://backend_ip_hash; } }示例 14最少连接数upstream backend_least_conn { least_conn; server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; } server { listen 80; server_name leastconn.example.com; location / { proxy_pass http://backend_least_conn; } }示例 15健康检查与故障转移upstream backend_health { server 192.168.1.10:8080 max_fails3 fail_timeout30s; server 192.168.1.11:8080 max_fails3 fail_timeout30s; server 192.168.1.12:8080 backup; } server { listen 80; server_name ha.example.com; location / { proxy_next_upstream error timeout invalid_header http_500 http_502 http_503; proxy_next_upstream_tries 3; proxy_next_upstream_timeout 10s; proxy_pass http://backend_health; } }7.4 安全与访问控制示例 16IP 白名单server { listen 80; server_name admin.example.com; location / { allow 192.168.1.0/24; allow 10.0.0.0/8; deny all; proxy_pass http://admin_backend:8080; } }示例 17HTTP 基本认证server { listen 80; server_name private.example.com; location / { auth_basic Restricted Area; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://backend:8080; } }示例 18限制请求速率limit_req_zone $binary_remote_addr zoneapi_limit:10m rate10r/s; server { listen 80; server_name api.example.com; location /api/ { limit_req zoneapi_limit burst20 nodelay; limit_req_status 429; proxy_pass http://api_backend:8080; } }示例 19限制并发连接数limit_conn_zone $binary_remote_addr zoneconn_limit:10m; server { listen 80; server_name download.example.com; location /downloads/ { limit_conn conn_limit 5; limit_conn_status 503; limit_rate 200k; root /data/files; } }示例 20防 SQL 注入与 XSSserver { listen 80; server_name secure.example.com; location / { if ($query_string ~* (\%27)|(\)|(\-\-)|(\%23)|(#)) { return 403; } if ($query_string ~* (\%3C)|(\%3E)|()|()|(\%3Cscript)|(script)) { return 403; } proxy_pass http://backend:8080; } }7.5 URL 重写与重定向示例 21HTTP 强制跳转 HTTPSserver { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name example.com www.example.com; ssl_certificate /etc/nginx/ssl/cert.pem; ssl_certificate_key /etc/nginx/ssl/key.pem; location / { proxy_pass http://backend:8080; } }示例 22域名重定向server { listen 80; server_name old-domain.com www.old-domain.com; return 301 https://new-domain.com$request_uri; }示例 23URL 美化伪静态server { listen 80; server_name blog.example.com; root /var/www/blog; location / { try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }示例 24移动端自动跳转server { listen 80; server_name www.example.com; set $mobile_rewrite 0; if ($http_user_agent ~* (android|iphone|ipad|mobile)) { set $mobile_rewrite 1; } if ($mobile_rewrite 1) { rewrite ^ https://m.example.com$request_uri permanent; } location / { proxy_pass http://backend:8080; } }示例 25维护页面重定向server { listen 80; server_name example.com; if (-f /var/www/maintenance.html) { return 503; } error_page 503 maintenance; location maintenance { root /var/www; rewrite ^(.*)$ /maintenance.html break; } location / { proxy_pass http://backend:8080; } }7.6 日志与监控示例 26自定义日志格式log_format json_log escapejson { time_local:$time_local, remote_addr:$remote_addr, remote_user:$remote_user, request:$request, status:$status, body_bytes_sent:$body_bytes_sent, request_time:$request_time, http_referer:$http_referer, http_user_agent:$http_user_agent, upstream_addr:$upstream_addr, upstream_status:$upstream_status }; server { listen 80; server_name api.example.com; access_log /var/log/nginx/api_access.log json_log; error_log /var/log/nginx/api_error.log warn; location / { proxy_pass http://backend:8080; } }示例 27按域名分离日志http { log_format main $remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent; server { listen 80; server_name site1.example.com; access_log /var/log/nginx/site1_access.log main; location / { proxy_pass http://backend1:8080; } } server { listen 80; server_name site2.example.com; access_log /var/log/nginx/site2_access.log main; location / { proxy_pass http://backend2:8080; } } }示例 28Stub Status 监控server { listen 80; server_name monitor.example.com; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; allow 192.168.1.0/24; deny all; } }7.7 高级特性示例 29gzip 压缩优化server { listen 80; server_name compress.example.com; gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_min_length 256; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xmlrss text/javascript image/svgxml application/vnd.ms-fontobject font/ttf font/opentype; location / { proxy_pass http://backend:8080; } }示例 30大文件上传配置server { listen 80; server_name upload.example.com; client_max_body_size 500m; client_body_buffer_size 128k; client_body_temp_path /tmp/nginx_body_temp; proxy_connect_timeout 300s; proxy_read_timeout 300s; proxy_send_timeout 300s; location /upload { proxy_pass http://upload_backend:8080; proxy_request_buffering off; } }以上 30 个示例覆盖了 Nginx 最常用的 7 大类场景。每个示例都经过生产环境验证可根据实际需求直接复制调整。建议收藏本文遇到对应场景时直接参考使用。