Nginx 配置示例及核心模块详解
作者:学亮编程手记
这篇文章主要介绍了Nginx 配置示例及核心模块详解,包括配置文件结构及核心模块详解,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
Nginx 配置详解
一、配置文件结构
# 全局块(主配置)
main
# 事件块
events {
...
}
# HTTP 块
http {
# HTTP 全局配置
...
# 虚拟主机块(一个或多个)
server {
# 服务器配置
...
# 位置块(一个或多个)
location {
...
}
}
# 可包含其他配置文件
include /etc/nginx/conf.d/*.conf;
}二、核心模块详解
1. 全局配置(main context)
user nginx nginx; # 运行用户和组 worker_processes auto; # 工作进程数(auto = CPU核心数) error_log /var/log/nginx/error.log warn; # 错误日志 pid /var/run/nginx.pid; # PID文件 worker_rlimit_nofile 65535; # 文件描述符限制
2. 事件模块(events context)
events {
worker_connections 1024; # 每个worker最大连接数
use epoll; # 事件驱动模型(Linux)
multi_accept on; # 同时接受多个连接
accept_mutex off; # 连接互斥锁
}3. HTTP模块(http context)
基础配置:
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优化
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 65; # 长连接超时
client_max_body_size 20m; # 最大上传文件大小
# Gzip压缩
gzip on;
gzip_comp_level 6;
gzip_types text/plain text/css application/json;
# 上游服务器(负载均衡)
upstream backend {
server 192.168.1.100:8080 weight=3;
server 192.168.1.101:8080;
server 192.168.1.102:8080 backup;
# 负载均衡策略:轮询(默认)、ip_hash、least_conn
}
}4. 虚拟主机(server context)
server {
listen 80; # 监听端口
listen [::]:80 ipv6only=on; # IPv6
server_name example.com www.example.com; # 域名
# 根目录和索引
root /var/www/html;
index index.html index.htm index.php;
# 字符集
charset utf-8;
# SSL配置(HTTPS)
listen 443 ssl http2;
ssl_certificate /etc/ssl/cert.pem;
ssl_certificate_key /etc/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# 重定向HTTP到HTTPS
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
# 安全头
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
}5. 位置块(location context)
location / {
# 匹配所有请求
try_files $uri $uri/ /index.php?$query_string;
}
# 精确匹配(=)
location = /api {
# 仅匹配 /api
}
# 正则匹配(~ 区分大小写,~* 不区分)
location ~ \.(jpg|png|gif)$ {
expires 30d; # 缓存控制
add_header Cache-Control "public, immutable";
}
# 前缀匹配(^~)
location ^~ /static/ {
# 匹配 /static/ 开头的URI
alias /var/www/static/;
}
# 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;
# 超时设置
proxy_connect_timeout 30s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
}
# PHP处理
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}三、高级配置示例
1. 负载均衡
upstream app_cluster {
least_conn; # 最少连接数
server app1.example.com:8080 max_fails=3 fail_timeout=30s;
server app2.example.com:8080;
server app3.example.com:8080 down; # 临时下线
keepalive 32; # 连接池
}2. 缓存代理
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
inactive=60m max_size=1g;
location / {
proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating;
}3. 限流
# 限制连接数
limit_conn_zone $binary_remote_addr zone=perip:10m;
# 限制请求速率
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
location /api/ {
limit_conn perip 10; # 每个IP最多10个连接
limit_req zone=perip burst=20 nodelay; # 令牌桶算法
}4. 反向代理WebSocket
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}四、配置最佳实践
- 安全配置:
# 隐藏Nginx版本号
server_tokens off;
# 限制请求方法
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 405;
}
# 防止目录遍历
autoindex off;
# 禁用不需要的HTTP方法
location / {
limit_except GET POST { deny all; }
}- 性能优化:
# 文件缓存 open_file_cache max=1000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; # 缓冲优化 proxy_buffers 8 16k; proxy_buffer_size 32k; client_body_buffer_size 128k; # TCP优化 sendfile_max_chunk 512k;
- 日志管理:
# 按天分割日志(在crontab中配置)
access_log /var/log/nginx/access-$(date +%Y%m%d).log;
# 排除静态文件日志
location ~* \.(jpg|css|js)$ {
access_log off;
log_not_found off;
}五、调试和测试
# 检查配置语法 nginx -t # 测试配置并显示解析结果 nginx -T # 重新加载配置(不中断服务) nginx -s reload # 调试特定问题 error_log /var/log/nginx/error.log debug;
六、常用变量
$remote_addr # 客户端IP $http_host # 请求主机头 $request_uri # 完整请求URI $args # 查询参数 $scheme # 协议(http/https) $server_name # 服务器名 $content_length # 请求体长度 $http_user_agent # 用户代理 $status # 响应状态码
七、配置组织建议
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 通用配置片段
│ ├── gzip.conf
│ ├── security.conf
│ └── proxy.conf
├── sites-available/ # 可用站点配置
│ └── example.com.conf
├── sites-enabled/ # 启用的站点(符号链接)
│ └── example.com.conf -> ../sites-available/example.com.conf
└── snippets/ # 可复用配置块
└── ssl-params.conf到此这篇关于Nginx 配置示例及核心模块详解的文章就介绍到这了,更多相关nginx配置核心模块内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
