Nginx 基础使用完全指南
2024/8/28大约 4 分钟
Nginx 基础使用完全指南
什么是 Nginx
Nginx(发音为"engine-x")是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 服务器。它以其高并发、低内存消耗和高稳定性而闻名。
Nginx 的主要特点
1. 高并发处理能力
- 采用事件驱动的异步非阻塞架构
- 单个进程可以处理数千个并发连接
- 内存消耗极低
2. 模块化设计
- 核心模块 + 功能模块的架构
- 支持动态模块加载
- 丰富的第三方模块
3. 反向代理和负载均衡
- 支持多种负载均衡算法
- 健康检查功能
- 会话保持
安装 Nginx
Ubuntu/Debian 系统
sudo apt update
sudo apt install nginxCentOS/RHEL 系统
sudo yum install nginx
# 或者使用 dnf
sudo dnf install nginxmacOS 系统
brew install nginxNginx 目录结构
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 额外配置文件目录
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 启用站点配置
└── modules-enabled/ # 启用的模块基本配置
主配置文件结构
# 全局块
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
# events 块
events {
worker_connections 1024;
use epoll;
}
# http 块
http {
# http 全局块
include /etc/nginx/mime.types;
default_type application/octet-stream;
# server 块
server {
# server 全局块
listen 80;
server_name example.com;
# location 块
location / {
root /var/www/html;
index index.html;
}
}
}虚拟主机配置
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example;
index index.html index.php;
# 静态文件处理
location / {
try_files $uri $uri/ =404;
}
# PHP 处理
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
}
# 静态资源缓存
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}反向代理配置
基本反向代理
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost: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;
proxy_set_header X-Forwarded-Proto $scheme;
}
}负载均衡
# 定义上游服务器组
upstream backend {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 backup;
}
server {
listen 80;
server_name app.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;
}
}负载均衡算法
upstream backend {
# 轮询(默认)
server server1.example.com;
server server2.example.com;
}
upstream backend_weighted {
# 加权轮询
server server1.example.com weight=3;
server server2.example.com weight=1;
}
upstream backend_ip_hash {
# IP 哈希
ip_hash;
server server1.example.com;
server server2.example.com;
}
upstream backend_least_conn {
# 最少连接
least_conn;
server server1.example.com;
server server2.example.com;
}SSL/HTTPS 配置
server {
listen 443 ssl http2;
server_name example.com;
# SSL 证书配置
ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;
# SSL 优化
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 强制 HTTPS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
location / {
root /var/www/html;
index index.html;
}
}
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}性能优化
Gzip 压缩
http {
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/atom+xml
image/svg+xml;
}缓存配置
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
add_header Vary Accept-Encoding;
}
location ~* \.(html|htm)$ {
expires 1h;
add_header Cache-Control "public, no-cache";
}连接优化
http {
# 开启高效文件传输
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 连接超时设置
keepalive_timeout 65;
client_max_body_size 64M;
# 缓冲区设置
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
}日志配置
访问日志
http {
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;
}
server {
access_log /var/log/nginx/example.com.access.log main;
error_log /var/log/nginx/example.com.error.log;
}日志分析
# 查看访问最多的 IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10
# 查看最受欢迎的页面
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10
# 查看 404 错误
awk '$9 == "404" {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr常用命令
服务管理
# 启动 Nginx
sudo systemctl start nginx
# 停止 Nginx
sudo systemctl stop nginx
# 重启 Nginx
sudo systemctl restart nginx
# 重新加载配置
sudo systemctl reload nginx
# 查看状态
sudo systemctl status nginx
# 开机自启
sudo systemctl enable nginx配置测试
# 测试配置文件语法
sudo nginx -t
# 测试并显示配置
sudo nginx -T
# 查看版本信息
nginx -v
nginx -V安全配置
隐藏版本信息
http {
server_tokens off;
}限制请求
http {
# 限制请求频率
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
# 限制连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;
}
server {
# 应用限制
limit_req zone=login burst=5 nodelay;
limit_conn addr 10;
}防止常见攻击
# 防止 SQL 注入
location ~* \.(sql)$ {
deny all;
}
# 防止访问敏感文件
location ~ /\.(ht|git|svn) {
deny all;
}
# 添加安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;监控和维护
状态监控
server {
listen 8080;
server_name localhost;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}日志轮转
# 配置 logrotate
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
sharedscripts
postrotate
systemctl reload nginx
endscript
}最佳实践
配置文件组织
- 使用
include指令分离配置 - 为每个站点创建单独的配置文件
- 使用
性能优化
- 启用 Gzip 压缩
- 设置合适的缓存策略
- 优化 worker 进程数
安全措施
- 定期更新 Nginx
- 隐藏版本信息
- 配置防火墙规则
监控和维护
- 定期检查日志
- 监控服务器性能
- 备份配置文件
总结
Nginx 是一个功能强大且高效的 Web 服务器,掌握其基本使用对前端开发者来说非常重要。从静态文件服务到反向代理,从负载均衡到 SSL 配置,Nginx 为现代 Web 应用提供了全面的解决方案。
