Nginx服务器超详细入门教程
一、Nginx简介与核心优势
Nginx(发音为”engine-x”)是一款开源的高性能Web服务器、反向代理服务器及负载均衡器,自2004年发布以来,凭借其轻量级、高并发和低资源消耗的特性,成为Apache之后最流行的Web服务器解决方案之一。
核心优势
- 异步非阻塞架构:基于事件驱动模型,单线程可处理数万并发连接,内存占用仅为Apache的1/10。
- 模块化设计:支持动态加载模块(如HTTP反向代理、FastCGI、邮件代理等),无需重启即可扩展功能。
- 高可用性:内置健康检查、故障转移机制,适合生产环境部署。
- 负载均衡:支持轮询、IP哈希、最少连接数等7种算法,可与Keepalived实现高可用集群。
典型应用场景包括:静态资源服务、API网关、微服务架构中的服务发现、CDN加速等。
二、安装与基础配置
1. 安装方式
-
Linux系统(Ubuntu/CentOS)
# Ubuntu/Debiansudo apt update && sudo apt install nginx# CentOS/RHELsudo yum install epel-release && sudo yum install nginx
- Windows系统:下载ZIP包解压后运行
nginx.exe,需注意性能低于Linux环境。 - Docker部署:
docker run -d --name mynginx -p 80:80 nginx
2. 基础命令
nginx -s stop # 立即停止nginx -s quit # 优雅停止(处理完当前请求)nginx -s reload # 重新加载配置nginx -t # 测试配置文件语法
3. 配置文件结构
主配置文件位于/etc/nginx/nginx.conf(Linux)或conf/nginx.conf(Windows),采用主配置+包含文件的分层设计:
# 主配置文件示例user nginx;worker_processes auto; # 自动匹配CPU核心数events {worker_connections 1024; # 每个worker的最大连接数}http {include /etc/nginx/mime.types;default_type application/octet-stream;# 包含子配置include /etc/nginx/conf.d/*.conf;include /etc/nginx/sites-enabled/*;}
三、核心功能详解
1. 静态资源服务
配置示例:
server {listen 80;server_name example.com;root /var/www/html;index index.html;location / {try_files $uri $uri/ =404; # 优先查找文件,不存在返回404}# 图片压缩优化location ~* \.(jpg|jpeg|png|gif)$ {expires 30d;add_header Cache-Control "public";}}
关键参数:
root:指定静态文件根目录try_files:按顺序查找文件expires:设置浏览器缓存时间
2. 反向代理配置
将请求转发至后端服务(如Node.js、Tomcat):
server {listen 80;server_name api.example.com;location / {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;}}
进阶配置:
- WebSocket支持:添加
proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; - 超时设置:
proxy_connect_timeout 60s; proxy_read_timeout 60s;
3. 负载均衡
配置上游服务器组:
upstream backend {server 192.168.1.10:8080 weight=3; # 权重3server 192.168.1.11:8080;server 192.168.1.12:8080 backup; # 备用服务器}server {listen 80;location / {proxy_pass http://backend;}}
算法选择:
round_robin(默认):轮询least_conn:最少连接数ip_hash:基于客户端IP的哈希(适合会话保持)
4. HTTPS配置
使用Let’s Encrypt免费证书:
# 安装Certbotsudo apt install certbot python3-certbot-nginx# 获取证书sudo certbot --nginx -d example.com
自动生成的配置示例:
server {listen 443 ssl;server_name example.com;ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;ssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers HIGH:!aNULL:!MD5;# 强制HTTPS跳转if ($scheme != "https") {return 301 https://$host$request_uri;}}
四、性能优化技巧
1. 连接数调优
worker_processes 4; # 通常设置为CPU核心数worker_rlimit_nofile 65535; # 单个worker可打开的文件描述符数events {worker_connections 4096; # 每个worker的最大连接数use epoll; # Linux下高效事件模型}
2. Gzip压缩
gzip on;gzip_types text/plain text/css application/json application/javascript text/xml;gzip_min_length 1k;gzip_comp_level 6; # 压缩级别1-9
3. 缓存控制
# 浏览器缓存location ~* \.(js|css|png)$ {expires 1y;add_header Cache-Control "public, no-transform";}# 代理缓存(需配置proxy_cache_path)proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m;location / {proxy_cache my_cache;proxy_cache_valid 200 302 10m;proxy_cache_valid 404 1m;}
五、常见问题排查
1. 502 Bad Gateway错误
- 原因:后端服务未启动或超时
- 解决方案:
- 检查
proxy_pass地址是否正确 - 增加
proxy_connect_timeout和proxy_read_timeout - 查看后端服务日志
- 检查
2. 静态文件404错误
- 检查点:
root或alias路径是否正确- 文件权限是否为
nginx:nginx(Linux) - SELinux是否阻止访问(
chcon -R -t httpd_sys_content_t /path)
3. 高并发下连接失败
- 优化建议:
- 调整
worker_rlimit_nofile和worker_connections - 禁用
accept_mutex(高并发场景):accept_mutex off; - 使用
epoll多路复用模型
- 调整
六、进阶实践:Nginx与Docker集成
1. 多容器负载均衡
# docker-compose.ymlversion: '3'services:nginx:image: nginx:latestports:- "80:80"volumes:- ./nginx.conf:/etc/nginx/nginx.confdepends_on:- app1- app2app1:image: my-appexpose:- "3000"app2:image: my-appexpose:- "3000"
2. 动态上游配置
使用Consul Template动态更新上游服务器:
# nginx.confupstream app {{{range service "app"}}server {{.Address}}:{{.Port}};{{end}}}
七、总结与学习资源
Nginx的强大源于其简洁的设计哲学——做少但做好。对于初学者,建议按以下路径深入:
- 掌握基础配置语法
- 实践反向代理和负载均衡
- 学习Lua脚本扩展(OpenResty)
- 研究源码理解事件驱动模型
推荐资源:
- 官方文档:nginx.org/en/docs/
- 《Nginx高性能Web服务器详解》
- GitHub开源项目:kubernetes/ingress-nginx
通过系统学习与实践,Nginx将成为您构建高可用Web架构的利器。