目录
- [Nginx 基本使用和高级用法详解](#Nginx 基本使用和高级用法详解)
-
- [一、Nginx 简介](#一、Nginx 简介)
- 二、基本安装与使用
-
- [1. 安装 Nginx](#1. 安装 Nginx)
- [2. 基本操作命令](#2. 基本操作命令)
- 三、配置文件结构
-
- [1. 主要配置文件目录结构](#1. 主要配置文件目录结构)
- [2. 基本配置示例(`/etc/nginx/nginx.conf`)](#2. 基本配置示例(
/etc/nginx/nginx.conf
))
- 四、虚拟主机配置
-
- [1. 基本虚拟主机配置](#1. 基本虚拟主机配置)
- [2. 启用站点](#2. 启用站点)
- 五、高级配置技巧
- 六、性能优化配置
-
- [1. 连接优化](#1. 连接优化)
- [2. 工作进程优化](#2. 工作进程优化)
- 七、日志配置
-
- [1. 自定义日志格式](#1. 自定义日志格式)
- [2. 日志分割脚本(`rotate_nginx_logs.sh`)](#2. 日志分割脚本(
rotate_nginx_logs.sh
))
- 八、监控和调试
-
- [1. 状态页面配置](#1. 状态页面配置)
- [2. 调试常用命令](#2. 调试常用命令)
- [九、Docker 中的 Nginx](#九、Docker 中的 Nginx)
-
- [1. Dockerfile 示例](#1. Dockerfile 示例)
- [2. Docker Compose 示例](#2. Docker Compose 示例)
- 结语
Nginx 基本使用和高级用法详解
一、Nginx 简介
Nginx 是一个高性能的 HTTP 和反向代理服务器,具有占用内存少、并发能力强等特点,广泛应用于 Web 服务、负载均衡、静态资源处理和反向代理等场景。
二、基本安装与使用
1. 安装 Nginx
Ubuntu/Debian
bash
sudo apt update
sudo apt install nginx
CentOS/RHEL
bash
sudo yum install nginx
# 或
sudo dnf install nginx
2. 基本操作命令
bash
# 启动
sudo systemctl start nginx
# 停止
sudo systemctl stop nginx
# 重启
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 查看状态
sudo systemctl status nginx
# 开机自启
sudo systemctl enable nginx
三、配置文件结构
1. 主要配置文件目录结构
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 额外配置文件目录
├── sites-available/ # 可用站点配置文件
└── sites-enabled/ # 已启用站点配置文件(软链接指向 sites-available)
2. 基本配置示例(/etc/nginx/nginx.conf
)
nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
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;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
四、虚拟主机配置
1. 基本虚拟主机配置
nginx
# /etc/nginx/sites-available/example.com
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# 静态资源缓存优化
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
2. 启用站点
bash
# 创建软链接启用站点
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
# 测试配置是否正确
sudo nginx -t
# 重新加载配置
sudo systemctl reload nginx
五、高级配置技巧
1. 反向代理配置
nginx
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;
# 超时设置
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 缓冲设置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
}
2. 负载均衡
nginx
upstream backend {
server backend1.example.com weight=3;
server backend2.example.com;
server backend3.example.com;
server backup.example.com 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;
}
}
3. SSL/TLS 配置
nginx
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
# SSL 安全设置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# HSTS 强制 HTTPS
add_header Strict-Transport-Security "max-age=63072000" always;
root /var/www/example.com;
index index.html;
}
4. 缓存配置
代理缓存
nginx
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g
inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_pass http://backend;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Cache-Status $upstream_cache_status;
}
}
静态资源缓存
nginx
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
5. 安全配置
nginx
# 隐藏版本号
server_tokens off;
# 安全响应头
add_header X-Frame-Options "SAMEORIGIN" always;
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 Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
# 上传大小限制
client_max_body_size 10m;
# 限制非法请求方法
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 405;
}
6. 限流配置
nginx
# 定义限流区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=2r/m;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
location /login {
limit_req zone=login burst=5;
proxy_pass http://backend;
}
}
7. URL 重写和重定向
nginx
server {
# 强制跳转 HTTPS
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
# 路径重定向
location /old-path {
return 301 /new-path;
}
# 去除 .html 扩展名
location / {
try_files $uri $uri.html $uri/ =404;
}
# RESTful URL 重写
location /api/v1/users {
rewrite ^/api/v1/users/(.*)$ /api/v1/users?id=$1 last;
}
}
8. Gzip 压缩
nginx
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
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;
六、性能优化配置
1. 连接优化
nginx
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 1000;
# 文件描述符缓存
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
2. 工作进程优化
nginx
worker_processes auto;
worker_cpu_affinity auto;
# 提高文件描述符限制
worker_rlimit_nofile 65535;
七、日志配置
1. 自定义日志格式
nginx
log_format main '$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;
error_log /var/log/nginx/error.log warn;
2. 日志分割脚本(rotate_nginx_logs.sh
)
bash
#!/bin/bash
# rotate_nginx_logs.sh
LOG_DIR="/var/log/nginx"
DATE=$(date -d "yesterday" +%Y-%m-%d)
mv $LOG_DIR/access.log $LOG_DIR/access.$DATE.log
mv $LOG_DIR/error.log $LOG_DIR/error.$DATE.log
# 通知 Nginx 重新打开日志文件
kill -USR1 $(cat /var/run/nginx.pid)
# 压缩7天前的日志
find $LOG_DIR -name "*.log" -mtime +7 -exec gzip {} \;
提示 :可配合
cron
定时执行日志轮转。
八、监控和调试
1. 状态页面配置
nginx
server {
listen 8080;
server_name localhost;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
访问 http://localhost:8080/nginx_status
可查看连接状态。
2. 调试常用命令
bash
# 测试配置语法
sudo nginx -t
# 打印完整配置(含 include)
sudo nginx -T
# 查看 Nginx 编译参数和模块
nginx -V
# 实时查看日志
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
# 压力测试(Apache Bench)
ab -n 1000 -c 100 http://example.com/
九、Docker 中的 Nginx
1. Dockerfile 示例
dockerfile
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY sites/ /etc/nginx/sites-available/
COPY html/ /usr/share/nginx/html/
RUN ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
EXPOSE 80 443
CMD ["nginx", "-g", "daemon off;"]
2. Docker Compose 示例
yaml
version: '3.8'
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./sites:/etc/nginx/sites-available
- ./html:/usr/share/nginx/html
- ./ssl:/etc/ssl
networks:
- webnet
networks:
webnet:
driver: bridge
结语
本指南涵盖了 Nginx 的 基础安装、虚拟主机、反向代理、负载均衡、SSL 配置、缓存、安全加固、限流、URL 重写、Gzip 压缩、性能调优、日志管理、监控调试 以及 Docker 部署 等核心内容,适用于构建高可用、高性能、安全的 Web 服务架构。
建议在生产环境中结合具体业务场景进行配置优化,并定期审查安全策略和性能指标。