基础配置
本章将介绍 Nginx 配置文件的基本结构和语法,理解配置文件的工作方式。
配置文件结构
基本结构
Nginx 配置文件采用层级块结构,主要由指令和块组成:
# 全局块
worker_processes auto;
# events 块
events {
worker_connections 1024;
}
# http 块
http {
# http 全局配置
include /etc/nginx/mime.types;
default_type application/octet-stream;
# server 块
server {
listen 80;
server_name localhost;
# location 块
location / {
root /usr/share/nginx/html;
index index.html;
}
}
}
配置层级
┌─────────────────────────────────────────┐
│ main(全局) │
│ worker_processes, user, error_log... │
├─────────────────────────────────────────┤
│ events │
│ worker_connections, use... │
├─────────────────────────────────────────┤
│ http │
│ include, default_type... │
│ ┌─────────────────────────────────────┐│
│ │ server ││
│ │ listen, server_name... ││
│ │ ┌─────────────────────────────────┐││
│ │ │ location │││
│ │ │ root, index, proxy_pass... │││
│ │ └─────────────────────────────────┘││
│ └─────────────────────────────────────┘│
├─────────────────────────────────────────┤
│ mail(可选) │
└─────────────────────────────────────────┘
解释:
- main 块:最外层,定义全局设置
- events 块:配置网络连接处理方式
- http 块:HTTP 服务相关配置
- server 块:虚拟主机配置
- location 块:URL 匹配规则和处理方式
指令语法
基本语法
# 指令语法
directive_name value1 value2...;
# 示例
worker_processes 4; # 数值
user nginx; # 字符串
error_log /var/log/nginx/error.log warn; # 多个参数
# 块语法
directive {
sub_directive value;
}
语法规则:
- 每条指令以分号
;结尾 - 块指令使用花括号
{}包围 - 字符串可以用引号,也可以不用
- 注释使用
#
注释
# 这是单行注释
# worker_processes 4; # 这也是注释
# Nginx 不支持多行注释
全局配置指令
worker_processes
设置工作进程数量,通常设置为 CPU 核心数:
# 自动检测 CPU 核心数(推荐)
worker_processes auto;
# 指定数量
worker_processes 4;
# 设置为 CPU 核心数
worker_processes 8;
解释:
- 每个工作进程是一个独立的线程
- 设置为
auto时,Nginx 自动检测 CPU 核心数 - 一般设置为 CPU 核心数,或设置为
auto
worker_connections
每个工作进程的最大连接数:
events {
# 每个 worker 进程最多同时处理 1024 个连接
worker_connections 1024;
# 提高文件描述符限制
worker_rlimit_nofile 65535;
}
解释:
- 最大并发连接数 =
worker_processes×worker_connections - 受系统文件描述符限制,可能需要修改
/etc/security/limits.conf
user
指定运行 Nginx 的用户:
# 设置用户和组
user nginx;
# 也可以指定组
user nginx nginx;
error_log
错误日志配置:
# 基本语法
error_log /var/log/nginx/error.log;
# 指定日志级别
error_log /var/log/nginx/error.log warn;
# 日志级别(从低到高)
# debug - 调试信息
# info - 一般信息
# notice - 通知
# warn - 警告
# error - 错误
# crit - 严重错误
# alert - 警报
# emerg - 紧急
# 关闭错误日志
error_log /dev/null crit;
pid
PID 文件路径:
pid /var/run/nginx.pid;
events 块配置
基本配置
events {
# 每个 worker 进程的最大连接数
worker_connections 2048;
# 使用 epoll 事件模型(Linux)
use epoll;
# 允许同时接受多个连接
multi_accept on;
}
事件模型
events {
# 自动选择最佳模型
use epoll; # Linux 2.6+
# use kqueue; # FreeBSD, macOS
# use select; # 所有平台(兼容性好)
# use poll; # 大多数 Unix
}
解释:
epoll是 Linux 上最高效的事件模型kqueue是 FreeBSD 和 macOS 上的高效模型- 如果不指定,Nginx 会自动选择可用的最佳模型
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(高效文件传输)
sendfile on;
# 开启 TCP NOPUSH(Linux)
tcp_nopush on;
# 开启 TCP NODELAY
tcp_nodelay on;
# 保持连接超时时间
keepalive_timeout 65;
# 开启 gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;
# 包含其他配置文件
include /etc/nginx/conf.d/*.conf;
}
sendfile 指令
# 开启 sendfile(推荐)
sendfile on;
# 使用 aio 和 directio(大文件)
sendfile on;
tcp_nopush on;
tcp_nodelay on;
解释:
sendfile使用内核的零拷贝技术传输文件tcp_nopush将多个包合并后一起发送tcp_nodelay禁用 Nagle 算法,减少延迟
keepalive 连接
http {
# 保持连接超时时间
keepalive_timeout 65;
# 单个连接最大请求数
keepalive_requests 100;
# 保持连接的超时时间
# 第一个参数:客户端超时
# 第二个参数:响应头中的 Keep-Alive
keepalive_timeout 75s 60;
}
gzip 压缩
http {
# 开启 gzip 压缩
gzip on;
# 压缩级别(1-9)
gzip_comp_level 5;
# 最小压缩文件大小
gzip_min_length 256;
# 压缩的 MIME 类型
gzip_types
text/plain
text/css
text/javascript
application/json
application/javascript
application/xml
image/svg+xml;
# 为代理请求压缩
gzip_proxied any;
# 在响应头中添加 Vary: Accept-Encoding
gzip_vary on;
# 禁用 IE6 的 gzip
gzip_disable "msie6";
}
解释:
gzip_comp_level建议设置为 4-6,平衡压缩率和 CPU 消耗gzip_min_length小于此大小的文件不压缩gzip_vary告诉代理服务器存在压缩版本
buffer 配置
http {
# 客户端请求体缓冲区
client_body_buffer_size 16k;
# 客户端请求体最大大小
client_max_body_size 8m;
# 客户端请求头缓冲区
client_header_buffer_size 1k;
# 大请求头缓冲区
large_client_header_buffers 4 8k;
# 代理缓冲区
proxy_buffer_size 4k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 32k;
}
server 块配置
基本配置
server {
# 监听端口
listen 80;
# 服务器名称
server_name example.com www.example.com;
# 网站根目录
root /var/www/example;
# 默认首页
index index.html index.php;
# 编码
charset utf-8;
}
监听指令
# 监听指定端口
listen 80;
listen 8080;
# 监听指定 IP 和端口
listen 192.168.1.1:80;
# 监听所有 IPv4
listen *:80;
# 监听所有 IPv6
listen [::]:80;
# 监听所有 IPv4 和 IPv6
listen 80;
listen [::]:80;
# 使用 SSL
listen 443 ssl;
listen [::]:443 ssl;
# HTTP/2
listen 443 ssl http2;
server_name 指令
# 精确匹配
server_name example.com;
# 多个域名
server_name example.com www.example.com;
# 通配符
server_name *.example.com; # 匹配所有子域名
server_name example.*; # 匹配所有后缀
# 正则表达式
server_name ~^www\d+\.example\.com$;
# 默认服务器
server_name _; # 匹配所有未定义的域名
匹配优先级:
- 精确匹配
- 前缀通配符
*.example.com - 后缀通配符
example.* - 正则表达式匹配
location 块配置
基本语法
location [修饰符] 匹配模式 {
# 配置指令
}
匹配修饰符
# 精确匹配
location = / {
# 只匹配 /
}
# 前缀匹配(优先级最高)
location ^~ /images/ {
# 匹配 /images/ 开头的请求
# 一旦匹配,不再检查正则
}
# 正则匹配(区分大小写)
location ~ \.php$ {
# 匹配 .php 结尾的请求
}
# 正则匹配(不区分大小写)
location ~* \.(jpg|jpeg|png|gif)$ {
# 匹配图片文件
}
# 前缀匹配
location /documents/ {
# 匹配 /documents/ 开头的请求
}
# 默认匹配
location / {
# 匹配所有请求
}
匹配优先级(从高到低):
=精确匹配^~前缀匹配(优先)~和~*正则匹配(按配置顺序)- 普通前缀匹配(最长匹配)
/默认匹配
location 示例
server {
listen 80;
server_name example.com;
root /var/www/example;
# 默认处理
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# PHP 文件处理
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
# API 代理
location /api/ {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
变量
常用内置变量
# 客户端信息
$remote_addr # 客户端 IP
$remote_user # 客户端用户名
$http_user_agent # User-Agent
$http_referer # 来源页面
# 请求信息
$request_method # 请求方法 (GET, POST...)
$request_uri # 完整请求 URI
$uri # 请求 URI(不带参数)
$args # 查询参数
$query_string # 同 $args
$scheme # 协议 (http, https)
$host # 主机名
$server_name # 服务器名称
$server_port # 服务器端口
# 响应信息
$status # 响应状态码
$body_bytes_sent # 发送的字节数
# 时间信息
$time_local # 本地时间
$time_iso8601 # ISO 8601 时间
# 连接信息
$connection # 连接序列号
$connection_requests # 当前连接的请求数
# SSL 信息
$ssl_protocol # SSL 协议版本
$ssl_cipher # 加密套件
自定义变量
# 设置变量
set $my_var "hello";
# 使用变量
if ($my_var = "hello") {
# ...
}
# 在日志中使用
log_format custom '$remote_addr - $my_var - $request';
包含文件
include 指令
# 包含单个文件
include /etc/nginx/conf.d/default.conf;
# 包含目录下所有 .conf 文件
include /etc/nginx/conf.d/*.conf;
# 包含所有文件
include /etc/nginx/sites-enabled/*;
# 相对路径(相对于配置文件目录)
include mime.types;
最佳实践:
- 使用
conf.d/*.conf管理多个站点配置 - 将不同功能的配置分离到不同文件
- 保持主配置文件简洁
完整配置示例
# /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/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;
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json
application/javascript application/xml+rss
application/atom+xml image/svg+xml;
include /etc/nginx/conf.d/*.conf;
}
小结
本章我们学习了:
- Nginx 配置文件的层级结构
- 指令语法和注释方式
- 全局配置指令(worker_processes、user、error_log)
- events 块配置(worker_connections、事件模型)
- http 块配置(日志、压缩、缓冲区)
- server 块和 location 块配置
- 内置变量的使用
- include 指令管理配置文件
练习
- 查看默认的 nginx.conf 配置文件
- 修改 worker_processes 设置
- 配置 gzip 压缩
- 添加一个简单的 server 块