总结:Nginx配置文件案例说明
一·Nginx目录结构说明
bash
/etc/nginx/
├── nginx.conf # 主配置文件
├── mime.types # MIME类型映射文件
├── fastcgi.conf # FastCGI默认参数
├── fastcgi_params # FastCGI参数文件
├── scgi_params # SCGI协议参数
├── uwsgi_params # uWSGI协议参数
├── koi-utf # 编码转换映射文件
├── koi-win # 编码转换映射文件
├── win-utf # 编码转换映射文件
├── modules/ # 动态模块目录
│ └── *.so # 各种动态模块
├── conf.d/ # 通用配置片段
│ └── *.conf # 按功能拆分的配置文件
├── sites-available/ # 所有可用站点配置
│ └── example.com.conf # 站点配置文件模板
├── sites-enabled/ # 已启用的站点配置(符号链接)
│ └── example.com.conf -> ../sites-available/example.com.conf
├── snippets/ # 配置代码片段
│ ├── ssl.conf # SSL通用配置
│ ├── headers.conf # 安全头配置
│ └── proxy.conf # 代理通用配置
├── ssl/ # SSL证书目录
│ ├── example.com.crt # 证书文件
│ ├── example.com.key # 私钥文件
│ └── dhparam.pem # DH参数文件
├── cache/ # 缓存目录
│ ├── client_temp # 客户端请求缓存
│ ├── proxy_temp # 代理缓存
│ ├── fastcgi_temp # FastCGI缓存
│ ├── uwsgi_temp # uWSGI缓存
│ └── scgi_temp # SCGI缓存
├── logs/ # 日志目录(实际通常位于/var/log/nginx)
│ ├── access.log # 访问日志
│ └── error.log # 错误日志
└── html/ # 默认网站根目录
├── index.html # 默认首页
├── 50x.html # 错误页
└── .well-known/ # 用于ACME验证等
关键目录说明
1.核心配置文件
- /etc/nginx/nginx.conf:主配置文件
- /etc/nginx/conf.d/*.conf:全局配置片段
2.站点配置
- sites-available/:所有站点配置(相当于"库存")
- sites-enabled/:实际加载的站点(启用时创建符号链接)
3.代码片段
- snippets/:可重用的配置块
bash
# 示例:包含SSL配置
server {
listen 443 ssl;
include snippets/ssl.conf;
}
4.SSL证书管理
bash
/etc/nginx/ssl/
├── domain.crt # 证书链(包含中间证书)
├── domain.key # 私钥文件
└── dhparam.pem # Diffie-Hellman参数(加强安全性)
二·nginx.conf配置文件示例
bash
# ===========================
# Nginx 主配置文件示例
# ===========================
# 用户和用户组:指定 Nginx 工作进程运行的用户和组(建议使用非 root 用户,如 www)
# user www www;
# 指定运行 Nginx 的用户和组
user nginx;
# 工作进程数,建议设置为 CPU 核心数(可通过 `grep processor /proc/cpuinfo | wc -l` 查看),auto 表示自动检测
worker_processes auto;
# 错误日志路径及日志级别(debug, info, notice, warn, error, crit, alert, emerg)
error_log /var/log/nginx/error.log warn;
# PID 文件路径,记录主进程 ID
pid /var/run/nginx.pid;
# 限制每个工作进程打开的最大文件数
worker_rlimit_nofile 65535;
# ===========================
# events 模块:连接处理配置
# ===========================
events {
# 单个工作进程的最大并发连接数
# 理论值 = 打开文件数限制 / 工作进程数,建议设置为 65535(需先调整系统文件描述符限制)
worker_connections 10240;
# 事件模型:epoll 是 Linux 下高性能的 I/O 多路复用模型(推荐)
# 其他可选:select/poll/kqueue(FreeBSD)/devpoll(Solaris)
use epoll;
# 允许一个连接同时接受多个网络连接(优化长连接场景,如 HTTP/2)
multi_accept on;
# 是否一次性接受多个连接
accept_mutex on;
}
# ===========================
# http 模块:HTTP 服务配置
# ===========================
http {
# 字符集配置:默认编码,避免中文乱码
charset utf-8;
# MIME 类型映射文件:指定不同文件后缀对应的 Content-Type 响应头
include /etc/nginx/mime.types;
# 默认 MIME 类型:如果文件后缀未匹配 mime.types,默认作为二进制流传输
default_type application/octet-stream;
# ======================== 日志格式配置 ========================
# 定义主访问日志格式:name 为 main,可自定义;各参数含义如下:
# $remote_addr:客户端 IP
# $remote_user:客户端认证用户名(无则为空)
# $time_local:服务器本地时间
# $request:完整请求行(方法 + URL + 协议)
# $status:HTTP 响应状态码
# $body_bytes_sent:发送给客户端的响应体字节数
# $http_referer:请求来源(Referer)
# $http_user_agent:客户端浏览器/设备信息
# $http_x_forwarded_for:反向代理场景下的真实客户端 IP
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:使用内核零拷贝技术,加速静态文件传输(跳过用户态,直接内核态传输)
sendfile on;
# 开启 tcp_nopush:在 sendfile 开启时,合并多个小数据包一次性发送,减少网络开销
tcp_nopush on;
# 开启 tcp_nodelay:禁用 Nagle 算法,减少延迟(适合实时性要求高的场景)
tcp_nodelay on;
# 连接超时时间:客户端与服务器的长连接保持时间(秒)
keepalive_timeout 65;
# 长连接最大请求数:单个长连接可处理的最大请求数,避免连接长期占用
keepalive_requests 100;
# 客户端请求头缓冲区大小:默认 1k,若请求头较大(如 Cookie 多)可调大
client_header_buffer_size 1k;
# 超大请求头缓冲区:备用缓冲区,处理超过 client_header_buffer_size 的请求头
large_client_header_buffers 4 8k;
# 客户端请求体最大大小:限制上传文件大小,超出返回 413 错误
client_max_body_size 100m;
# 请求体缓冲区大小:若请求体小于该值,直接存内存;否则存临时文件
client_body_buffer_size 10m;
# ======================== Gzip 压缩配置 ========================
# 响应压缩:开启 gzip 压缩,减少传输流量(适合文本类文件:html/css/js/json)
gzip on;
# 允许客户端缓存压缩后的响应(通过 Vary 头),在响应头添加 Vary: Accept-Encoding
gzip_vary on;
# 反向代理场景下,向后端服务器传递压缩标识
gzip_proxied any;
# 压缩级别:1-9,级别越高压缩率越高,但 CPU 消耗越大(推荐 2-4)
gzip_comp_level 3;
# 压缩最小文件大小:小于该值的文件不压缩(小文件压缩收益低)
gzip_min_length 1k;
# 压缩缓冲区大小:处理压缩的内存缓冲区
gzip_buffers 4 16k;
# 压缩协议版本:支持 HTTP/1.0 和 HTTP/1.1
gzip_http_version 1.0;
# 压缩文件类型:指定需要压缩的 MIME 类型
gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml application/xml+rss application/x-javascript;
# ======================== 反向代理缓存区 ========================
proxy_buffering on; # 开启代理缓冲
proxy_buffer_size 16k; # 头部缓冲区大小
proxy_buffers 8 16k; # 8个缓冲区,每个16k
proxy_busy_buffers_size 32k; # 繁忙缓冲区大小
# ======================== 安全防护配置 ========================
# 隐藏 Nginx 版本号:避免攻击者利用已知版本漏洞
server_tokens off;
# ======================== 限流配置 ========================
# 基于客户端 IP 创建限流区
# 10m 表示内存大小
# rate=20r/s 每秒20个请求
# 限制并发连接:单 IP 最多 100 个并发连接
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
# 限制请求速率:单 IP 每秒最多 20 个请求,突发 30 个(超出返回 503)
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=20r/s;
# ======================== upstream 负载均衡 ========================
upstream backend {
server 127.0.0.1:8080 weight=1 max_fails=3 fail_timeout=30s;
# weight=1 权重
# max_fails=3 最大失败次数
# fail_timeout=30s 失败检测时间窗口
}
# ======================== 引入外部其他配置文件 ========================
# 包含其他配置文件(nginx默认加载配置文件路径)
include /etc/nginx/conf.d/*.conf;
# 加载所有自定义模块(例如把server模块单独拆分为conf文件)
include /lmf/nginx/custom-modules/*.conf;
# ===========================
# server 块:虚拟主机配置
# ===========================
server {
# 监听端口和协议:80 端口(HTTP),默认服务器(匹配未指定主机头的请求)
listen 80 default_server;
# IPv6 监听(可选)域名:多个域名用空格分隔(如 www.example.com example.com)
listen [::]:80 default_server;
# 服务器域名
server_name example.com www.example.com;
# 网站根目录(需确保用户有读取权限)
root /var/www/html;
# 默认首页文件
index index.html index.htm index.php;
# 字符集设置
charset utf-8;
# 限制连接数
limit_conn conn_limit 10;
# 限制请求频率
limit_req zone=req_limit burst=20 nodelay;
# ======================== 主站点配置 ========================
location / {
# 尝试按顺序查找文件、目录,否则返回 404
try_files $uri $uri/ =404;
}
# ======================== 静态资源缓存优化 ========================
# 匹配静态文件后缀,设置缓存头(客户端缓存,减少重复请求)
location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt)$ {
# 缓存有效期:30 天(客户端本地缓存)
expires 30d;
# public - 表示响应可以被任何缓存存储(包括代理服务器)
# immutable - 表示资源永远不会改变,可以永久缓存
add_header Cache-Control "public, immutable";
# 关闭日志:静态文件访问不记录日志,减少磁盘 IO
access_log off;
# 跨域允许:允许静态资源跨域访问(可选)
add_header Access-Control-Allow-Origin *;
}
# ======================== 防盗链配置(可选) ========================
location ~* \.(jpg|jpeg|png|gif)$ {
# 只允许指定域名引用资源(防止其他网站盗用图片)
valid_referers none blocked example.com *.example.com;
# 非法引用返回 403
if ($invalid_referer) {
return 403;
}
}
# ======================== PHP 处理示例(需配合 PHP-FPM) ========================
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_connect_timeout 60;
fastcgi_send_timeout 180;
fastcgi_read_timeout 180;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
}
# ======================== 反向代理示例 ========================
#(1)location /api/ (带斜杠)
#匹配规则:只匹配以 /api/ 开头的路径
#示例匹配:
#✅ /api/users
#✅ /api/products/list
#❌ /api
#❌ /apitest
#路径处理规则(核心区别)
#请求: /api/users/123
#转发: http://backend/users/123 (去掉 /api/)
#(2)location /api (不带斜杠)
#匹配规则:匹配以 /api 开头的所有路径
#示例匹配:
#✅ /api
#✅ /api/
#✅ /api/users
#✅ /apitest
#✅ /apifoo
#路径处理规则(核心区别)
#请求: /api/users/123
#转发: http://backend/api/users/123 (保留完整路径)
location /api/ {
# 限流配置
limit_req zone=req_limit burst=20 nodelay;
# 反向代理配置
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 60;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffering on;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
# ======================== 健康检查接口(用于负载均衡) ========================
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
# ======================== 限制访问(可选) ========================
# 禁止访问隐藏文件(如 .htaccess、.git)
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 禁止访问备份文件
location ~* \.(bak|swp|tmp|old)$ {
deny all;
access_log off;
log_not_found off;
}
# ======================== 错误页面配置 ========================
# 404 错误页面:跳转到自定义 404.html
error_page 404 /404.html;
# 500/502/503/504 错误页面:跳转到自定义 50x.html
error_page 500 502 503 504 /50x.html;
# 定义错误页面的访问路径
location = /50x.html {
root /var/www/example.com;
}
}
# ===========================
# HTTPS 配置示例(需 SSL 证书)
# ===========================
server {
# 监听端口和协议:443 端口(HTTPS),启用 SSL
listen 443 ssl http2; # 监听 443 + 启用 SSL + HTTP2
# 域名,多个逗号分隔
server_name example.com www.example.com;
# ======================== SSL 配置 ========================
ssl_certificate /etc/nginx/ssl/example.crt; # 证书文件
ssl_certificate_key /etc/nginx/ssl/example.key; # 私钥文件
ssl_protocols TLSv1.2 TLSv1.3; # 允许协议版本
ssl_ciphers HIGH:!aNULL:!MD5; # 加密套件
ssl_prefer_server_ciphers on; # 优先使用服务器加密套件
# ======================== 静态文件目录 ========================
root /var/www/html; # 网站根目录
index index.html index.htm index.php; # 默认首页文件
# ======================== 静态资源缓存 ========================
location ~* \.(jpg|jpeg|png|gif|css|js|ico)$ {
expires 30d; # 缓存30天
access_log off; # 不记录访问日志
add_header Cache-Control "public";
}
# ======================== API 限流 ========================
location /api-back/ {
limit_req zone=api_limit burst=20 nodelay;
# burst=20 突发20个请求
# nodelay 不延迟处理
proxy_pass http://backend; # 转发到 upstream
proxy_set_header Host $host; # 转发 Host 头
proxy_set_header X-Real-IP $remote_addr; # 真实 IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# ======================== PHP 解析 ========================
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000; # PHP-FPM 地址
fastcgi_index index.php; # 默认 PHP 文件
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params; # 加载 FastCGI 参数
}
# ======================== 防止隐藏文件访问 ========================
location ~ /\. {
deny all; # 禁止访问 . 开头的文件(如 .git)
}
# ======================== 错误页面配置 ========================
error_page 404 /404.html;
location = /404.html {
internal; # 只能内部访问
}
}
# 强制跳转 HTTPS
server {
# 监听端口和协议:8080 端口(HTTP),默认服务器(匹配未指定主机头的请求)
listen 8080 default_server;
# IPv6 监听(可选)
listen [::]:8080 default_server;
# 域名:多个域名用空格分隔(如 www.example.com example.com)
server_name example.com www.example.com;
# 强制跳转 HTTPS路径
return 301 https://$host$request_uri;
}
}
三·Nginx配置文件语法检测
bash
nginx -t # 检查配置语法
nginx -s reload # 重载配置