Nginx入门教程 - 从零开始学习Nginx Web服务器
Nginx入门教程 - 从零开始学习Nginx Web服务器
目录
1. Nginx简介
Nginx(发音为"engine x")是一个高性能的HTTP和反向代理Web服务器,也是一个IMAP/POP3/SMTP代理服务器。Nginx由俄罗斯程序员Igor Sysoev开发,2004年首次公开发布。
核心特点:
✅ 高性能:采用事件驱动的异步非阻塞架构,能处理数万并发连接
✅ 低内存消耗:相比Apache,内存占用更少
✅ 高并发:官方测试可支持5万并发连接
✅ 反向代理:强大的反向代理和负载均衡功能
✅ 静态文件服务:高效处理静态文件请求
✅ 模块化设计:丰富的模块生态系统
✅ 配置简单:配置文件简洁易懂
Web服务器:提供HTTP/HTTPS服务
反向代理:作为后端服务器的代理
负载均衡:分发请求到多个后端服务器
静态资源服务:高效提供静态文件
API网关:作为微服务架构的API网关
CDN节点:内容分发网络节点
| 特性 | Nginx | Apache |
|---|---|---|
| 并发模型 | 事件驱动 | 进程/线程模型 |
| 内存占用 | 低 | 较高 |
| 静态文件 | 优秀 | 良好 |
| 动态内容 | 需配合PHP-FPM等 | 内置支持 |
| 配置复杂度 | 简单 | 较复杂 |
| 适用场景 | 高并发、反向代理 | 传统Web应用 |
- Master-Worker架构:主进程管理,工作进程处理请求
- 事件驱动模型:使用epoll(Linux)或kqueue(BSD)
- 非阻塞I/O:高效处理大量并发连接
2. 环境准备与安装
- 操作系统:Linux、macOS、Windows
- 内存:建议至少512MB
- 磁盘空间:至少100MB
Ubuntu/Debian系统
# 更新软件包列表
sudo apt update
# 安装Nginx
sudo apt install nginx
# 启动Nginx服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 检查状态
sudo systemctl status nginxCentOS/RHEL系统
# 安装EPEL仓库(如果需要)
sudo yum install epel-release
# 安装Nginx
sudo yum install nginx
# 启动Nginx服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 检查状态
sudo systemctl status nginx从源码编译安装
# 下载Nginx源码
wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0
# 安装依赖
sudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
# 配置编译选项
./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_gzip_static_module
# 编译和安装
make
sudo make install
# 启动Nginx
sudo /usr/local/nginx/sbin/nginx# 使用Homebrew安装
brew install nginx
# 启动Nginx
brew services start nginx
# 停止Nginx
brew services stop nginx
# 重启Nginx
brew services restart nginx- 访问Nginx官网:http://nginx.org/en/download.html
- 下载Windows版本
- 解压到指定目录(如:C:\nginx)
- 运行nginx.exe启动服务
2.5 验证安装
安装完成后,在浏览器中访问:
- Linux/macOS:http://localhost 或 http://127.0.0.1
- Windows:http://localhost
如果看到Nginx欢迎页面,说明安装成功。
2.6 Nginx目录结构
/usr/local/nginx/ # 安装目录(源码安装)
├── conf/ # 配置文件目录
│ ├── nginx.conf # 主配置文件
│ └── conf.d/ # 额外配置文件目录
├── html/ # 默认网站根目录
│ ├── index.html # 默认首页
│ └── 50x.html # 错误页面
├── logs/ # 日志目录
│ ├── access.log # 访问日志
│ └── error.log # 错误日志
└── sbin/ # 可执行文件目录
└── nginx # Nginx主程序包管理器安装的目录:
- 配置文件:/etc/nginx/
- 网站根目录:/usr/share/nginx/html/ 或 /var/www/html/
- 日志目录:/var/log/nginx/
- 可执行文件:/usr/sbin/nginx
3. Nginx基本配置
- 源码安装:/usr/local/nginx/conf/nginx.conf
- 包管理器安装:/etc/nginx/nginx.conf
# 全局配置块
user nginx; # 运行用户
worker_processes auto; # 工作进程数
error_log /var/log/nginx/error.log; # 错误日志
pid /var/run/nginx.pid; # PID文件位置
# 事件配置块
events {
worker_connections 1024; # 每个工作进程的最大连接数
use epoll; # 使用epoll事件模型
}
# HTTP配置块
http {
# 基础配置
include /etc/nginx/mime.types; # MIME类型文件
default_type application/octet-stream;
# 日志格式
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;
# 性能优化配置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss;
# Server配置块
server {
listen 80; # 监听端口
server_name localhost; # 服务器名称
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}全局配置
# 工作进程数(auto表示自动检测CPU核心数)
worker_processes auto;
# 错误日志级别:debug|info|notice|warn|error|crit
error_log /var/log/nginx/error.log warn;
# 工作进程的用户和组
user www-data;事件配置
events {
# 每个工作进程的最大连接数
worker_connections 1024;
# 事件模型(Linux使用epoll,BSD使用kqueue)
use epoll;
# 允许一个工作进程同时接受多个新连接
multi_accept on;
}HTTP配置
http {
# 包含MIME类型定义
include /etc/nginx/mime.types;
# 默认MIME类型
default_type application/octet-stream;
# 日志格式定义
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;
# 开启高效文件传输
sendfile on;
# 防止网络阻塞
tcp_nopush on;
tcp_nodelay on;
# 保持连接超时时间
keepalive_timeout 65;
# 客户端请求体大小限制
client_max_body_size 20M;
}修改配置后,务必测试配置文件:
# 测试配置文件语法
sudo nginx -t
# 测试并显示配置内容
sudo nginx -T
# 重新加载配置(不中断服务)
sudo nginx -s reload
# 或者使用systemctl
sudo systemctl reload nginx# 启动Nginx
sudo nginx
# 或
sudo systemctl start nginx
# 停止Nginx
sudo nginx -s stop
# 或
sudo systemctl stop nginx
# 优雅停止(等待请求处理完成)
sudo nginx -s quit
# 重新加载配置
sudo nginx -s reload
# 重新打开日志文件
sudo nginx -s reopen
# 查看版本信息
nginx -v
# 查看版本和配置信息
nginx -V4. 静态文件服务
server {
listen 80;
server_name example.com;
# 网站根目录
root /var/www/html;
# 默认首页文件
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}4.2 静态文件优化
server {
listen 80;
server_name example.com;
root /var/www/html;
location / {
try_files $uri $uri/ =404;
}
# 静态文件缓存配置
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}# 添加自定义MIME类型
location ~* \.json$ {
add_header Content-Type application/json;
}
location ~* \.xml$ {
add_header Content-Type application/xml;
}4.4 目录浏览
# 启用目录浏览(谨慎使用)
location /downloads/ {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}5. 反向代理配置
反向代理是Nginx的核心功能之一,它接收客户端请求,然后将请求转发给后端服务器,并将后端服务器的响应返回给客户端。
server {
listen 80;
server_name 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;
# 超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}# 定义上游服务器组
upstream backend {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}server {
listen 80;
server_name example.com;
location /ws/ {
proxy_pass http://127.0.0.1:8080;
# WebSocket必需的头信息
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;
# WebSocket超时设置
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
}server {
listen 80;
server_name example.com;
# API请求代理到后端API服务器
location /api/ {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
}
# 静态文件直接服务
location /static/ {
root /var/www/html;
}
# 其他请求代理到应用服务器
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
}
}6. 负载均衡
负载均衡是将客户端请求分发到多个后端服务器,以提高系统的可用性和性能。
轮询(Round Robin)- 默认
upstream backend {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
server 127.0.0.1:8082;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}加权轮询(Weighted Round Robin)
upstream backend {
server 127.0.0.1:8080 weight=3; # 权重3
server 127.0.0.1:8081 weight=2; # 权重2
server 127.0.0.1:8082 weight=1; # 权重1
}IP哈希(IP Hash)
upstream backend {
ip_hash; # 根据客户端IP进行哈希
server 127.0.0.1:8080;
server 127.0.0.1:8081;
server 127.0.0.1:8082;
}最少连接(Least Connections)
upstream backend {
least_conn;
server 127.0.0.1:8080;
server 127.0.0.1:8081;
server 127.0.0.1:8082;
}upstream backend {
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
server 127.0.0.1:8081 max_fails=3 fail_timeout=30s;
server 127.0.0.1:8082 backup; # 备用服务器
}upstream backend {
# 主服务器
server 127.0.0.1:8080 weight=3 max_fails=3 fail_timeout=30s;
server 127.0.0.1:8081 weight=2 max_fails=3 fail_timeout=30s;
# 备用服务器
server 127.0.0.1:8082 backup;
# 保持连接
keepalive 32;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}7. 虚拟主机配置
# 第一个虚拟主机
server {
listen 80;
server_name www.example.com example.com;
root /var/www/example;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# 第二个虚拟主机
server {
listen 80;
server_name www.test.com test.com;
root /var/www/test;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}# 端口80
server {
listen 80;
server_name example.com;
root /var/www/html;
}
# 端口8080
server {
listen 8080;
server_name example.com;
root /var/www/html2;
}# 默认服务器(处理未匹配的请求)
server {
listen 80 default_server;
server_name _;
return 444; # 关闭连接
}
# 其他虚拟主机
server {
listen 80;
server_name example.com;
root /var/www/example;
}8. SSL/TLS配置
使用Let's Encrypt(免费)
# 安装Certbot
sudo apt install certbot python3-certbot-nginx
# 获取证书(自动配置Nginx)
sudo certbot --nginx -d example.com -d www.example.com
# 自动续期测试
sudo certbot renew --dry-run手动配置SSL证书
server {
listen 443 ssl http2;
server_name example.com;
# SSL证书路径
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_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# SSL会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# HTTP重定向到HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}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;
# 只使用TLS 1.2和1.3
ssl_protocols TLSv1.2 TLSv1.3;
# 强加密套件
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
# HSTS(HTTP严格传输安全)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/ssl/ca-chain.crt;
root /var/www/html;
index index.html;
}9. Nginx常用模块
IP访问控制
server {
listen 80;
server_name example.com;
# 允许特定IP
location /admin/ {
allow 192.168.1.100;
allow 10.0.0.0/8;
deny all;
}
# 拒绝特定IP
location / {
deny 192.168.1.50;
allow all;
}
}密码保护
# 创建密码文件
sudo apt install apache2-utils
htpasswd -c /etc/nginx/.htpasswd usernameserver {
listen 80;
server_name example.com;
location /protected/ {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}URL重写
server {
listen 80;
server_name example.com;
# 重定向
location /old/ {
return 301 /new/;
}
# URL重写
location / {
rewrite ^/user/(\d+)$ /user.php?id=$1 last;
rewrite ^/product/(\w+)$ /product.php?name=$1 last;
}
}强制HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}# 在http块中定义限流区
http {
# 定义限流区
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/m;
server {
listen 80;
server_name example.com;
# API限流
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://backend;
}
# 登录限流
location /login {
limit_req zone=login_limit burst=3;
proxy_pass http://backend;
}
}
}http {
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml font/truetype font/opentype
application/vnd.ms-fontobject image/svg+xml;
}10. 性能优化
# 设置为CPU核心数
worker_processes auto;
# 绑定工作进程到CPU核心
worker_cpu_affinity auto;events {
worker_connections 4096;
use epoll;
multi_accept on;
}http {
# 打开文件缓存
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# 代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g
inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 60m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_pass http://backend;
}
}
}server {
# 启用sendfile
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
}11. 日志管理
http {
# 定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format detailed '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
# 使用日志格式
access_log /var/log/nginx/access.log main;
server {
# 特定server使用详细日志
access_log /var/log/nginx/example.com.access.log detailed;
# 禁用特定location的日志
location /static/ {
access_log off;
}
}
}# 全局错误日志
error_log /var/log/nginx/error.log warn;
# Server级别的错误日志
server {
error_log /var/log/nginx/example.com.error.log error;
}创建 /etc/logrotate.d/nginx:
/var/log/nginx/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}12. 安全配置
http {
server_tokens off;
}server {
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN" always;
# XSS保护
add_header X-XSS-Protection "1; mode=block" always;
# 内容类型嗅探保护
add_header X-Content-Type-Options "nosniff" always;
# 引用策略
add_header Referrer-Policy "no-referrer-when-downgrade" always;
# 权限策略
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
}# 限制请求大小
client_max_body_size 10M;
# 限制缓冲区大小
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
# 超时设置
client_body_timeout 10;
client_header_timeout 10;
keepalive_timeout 5 5;
send_timeout 10;server {
# 只允许GET和POST
if ($request_method !~ ^(GET|POST|HEAD)$ ) {
return 405;
}
}13. 实际应用案例
upstream backend {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name example.com;
root /var/www/frontend/dist;
index index.html;
# 前端静态文件
location / {
try_files $uri $uri/ /index.html;
}
# API代理
location /api/ {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
}upstream user_service {
server 127.0.0.1:8001;
server 127.0.0.1:8002;
}
upstream order_service {
server 127.0.0.1:8003;
server 127.0.0.1:8004;
}
server {
listen 80;
server_name api.example.com;
# 用户服务
location /api/users/ {
proxy_pass http://user_service;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 订单服务
location /api/orders/ {
proxy_pass http://order_service;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 限流
location /api/ {
limit_req zone=api_limit burst=20;
proxy_pass http://user_service;
}
}server {
listen 80;
server_name example.com;
root /var/www/wordpress;
index index.php index.html;
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;
}
location ~ /\.ht {
deny all;
}
}14. 常见问题与故障排除
# 测试配置文件
sudo nginx -t
# 查看配置
sudo nginx -T# 实时查看错误日志
sudo tail -f /var/log/nginx/error.log
# 查看访问日志
sudo tail -f /var/log/nginx/access.log502 Bad Gateway
原因:后端服务器无响应
解决:检查后端服务是否运行,检查代理配置
504 Gateway Timeout
原因:后端服务器响应超时
解决:增加proxy_read_timeout值
403 Forbidden
原因:权限不足
解决:检查文件权限和目录权限
413 Request Entity Too Large
原因:请求体过大
解决:增加client_max_body_size值
14.4 性能问题排查
# 查看Nginx进程
ps aux | grep nginx
# 查看连接数
netstat -an | grep :80 | wc -l
# 查看Nginx状态(需要安装nginx-module-vts)
curl http://localhost/nginx_status15. 总结与进阶
- ✅ 安装配置:掌握Nginx的安装和基本配置
- ✅ 静态文件服务:高效提供静态资源
- ✅ 反向代理:代理请求到后端服务器
- ✅ 负载均衡:分发请求到多个后端
- ✅ SSL/TLS:配置HTTPS加密
- ✅ 性能优化:提升Nginx性能
- ✅ 安全配置:保护服务器安全
- Nginx模块开发:学习C语言开发Nginx模块
- Lua脚本:使用OpenResty进行高级功能开发
- Kubernetes Ingress:在K8s中使用Nginx Ingress
- 性能调优:深入理解Nginx性能优化
- 高可用架构:构建高可用的Nginx集群
- 官方文档:https://nginx.org/en/docs/
- Nginx Wiki:https://www.nginx.com/resources/wiki/
- OpenResty:https://openresty.org/
- Nginx配置生成器:https://www.digitalocean.com/community/tools/nginx
- 配置文件组织:使用include分离配置
- 日志管理:定期轮转和清理日志
- 监控告警:设置Nginx监控和告警
- 安全加固:定期更新和检查安全配置
- 性能测试:使用工具测试Nginx性能
结语
Nginx是一个功能强大、性能优异的Web服务器和反向代理服务器。通过本教程的学习,相信你已经掌握了Nginx的核心功能和使用方法。
记住:
- 多实践:理论结合实践,多配置多测试
- 理解原理:理解Nginx的工作原理
- 关注安全:重视安全配置
- 持续学习:关注Nginx新特性和最佳实践
祝你学习愉快,配置顺利! 🚀
本教程由Java突击队学习社区编写,如有问题欢迎反馈。