前言
nginx 的强大之处已无需多言,正由于它过于强大,配置文件里一个参数的不同就会有完全不同的行为,容易让人摸不着头脑,今天我们就来完整分析它的配置文件里面到底有什么内容~
配置文件的基础结构
主配置文件位置
nginx的主配置文件通常位于:
linux系统:
/etc/nginx/nginx.confmacos(通过homebrew安装):
/usr/local/etc/nginx/nginx.confwindows系统:
<安装目录>/conf/nginx.conf
配置文件的层级结构
nginx配置文件采用块状结构,主要分为以下几个层级:
# 全局块
user nginx;
worker_processes auto;
# events 块
events {
worker_connections 1024;
}
# http 块
http {
# http 全局块
include 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;
}
}
}全局块配置详解
全局块是配置文件的最外层,影响 nginx 服务器整体运行的配置指令。
核心配置项
# 运行 nginx 的用户和用户组 user nginx nginx; # 工作进程数(通常设置为 cpu 核心数) worker_processes auto; # 错误日志路径和级别 error_log /var/log/nginx/error.log warn; # 进程 pid 文件位置 pid /var/run/nginx.pid; # 最大打开文件数 worker_rlimit_nofile 65535;
关键参数说明:
worker_processes:建议设置为auto或 cpu 核心数,可通过grep processor /proc/cpuinfo | wc -l查看error_log级别从低到高:debug→info→notice→warn→error→crit
events 块配置
events 块主要影响 nginx 服务器与用户的网络连接。
events {
# 单个工作进程的最大连接数
worker_connections 10240;
# 使用 epoll 事件驱动模型(linux 推荐)
use epoll;
# 尽可能多地接受连接
multi_accept on;
}性能优化建议:
worker_connections:理论最大并发连接数 =worker_processes × worker_connectionslinux 系统推荐使用
epoll,bsd 系统使用kqueue
http 块核心配置
http 块是配置的核心部分,包含了大部分 web 服务相关的设置。
基础配置
http {
# 引入 mime 类型定义
include mime.types;
default_type application/octet-stream;
# 字符集
charset utf-8;
# 日志格式定义
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;
# 客户端请求体大小限制
client_max_body_size 20m;
# gzip 压缩
gzip on;
gzip_vary on;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss;
}性能优化配置
http {
# 隐藏 nginx 版本号(安全)
server_tokens off;
# 文件缓存
open_file_cache max=10000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
# 客户端缓冲区大小
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 16k;
# fastcgi 缓存(用于 php 等)
fastcgi_cache_path /var/cache/nginx levels=1:2
keys_zone=my_cache:10m max_size=1g
inactive=60m use_temp_path=off;
}server 块配置详解
server 块定义了一个虚拟主机,一个 http 块可以包含多个 server 块。
基础虚拟主机配置
server {
# 监听端口
listen 80;
listen [::]:80; # ipv6
# 服务器域名
server_name example.com www.example.com;
# 网站根目录
root /var/www/example.com;
# 默认首页
index index.html index.htm index.php;
# 访问日志(可覆盖 http 块设置)
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
}https 配置
server {
listen 443 ssl http2;
server_name example.com;
# ssl 证书
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
# ssl 配置
ssl_protocols tlsv1.2 tlsv1.3;
ssl_ciphers high:!anull:!md5;
ssl_prefer_server_ciphers on;
# ssl 会话缓存
ssl_session_cache shared:ssl:10m;
ssl_session_timeout 10m;
# hsts(强制 https)
add_header strict-transport-security "max-age=31536000" always;
}
# http 自动跳转 https
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}location 块配置详解
location 块是 nginx 配置中最灵活的部分,用于匹配不同的 uri 请求。
location 匹配规则
# 精确匹配(优先级最高)
location = /exact {
# 只匹配 /exact
}
# 正则匹配(区分大小写)
location ~ \.php$ {
# 匹配以.php结尾的请求
}
# 正则匹配(不区分大小写)
location ~* \.(jpg|jpeg|png|gif)$ {
# 匹配图片文件
}
# 前缀匹配(优先级高于正则)
location ^~ /static/ {
# 匹配以/static/开头的请求
}
# 普通前缀匹配
location /api/ {
# 匹配以/api/开头的请求
}
# 通用匹配(最低优先级)
location / {
# 匹配所有请求
}匹配优先级(从高到低):
=精确匹配^~前缀匹配~和~*正则匹配(按配置顺序)普通前缀匹配(最长匹配原则)
常见 location 配置示例
静态文件服务
location / {
root /var/www/html;
index index.html;
try_files $uri $uri/ =404;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header cache-control "public, immutable";
}反向代理配置
location /api/ {
proxy_pass http://backend_server;
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 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}php-fpm 配置
location ~ \.php$ {
root /var/www/html;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param script_filename $document_root$fastcgi_script_name;
include fastcgi_params;
}负载均衡配置
upstream 配置
# 定义后端服务器组
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 192.168.1.13:8080 max_fails=3 fail_timeout=30s;
# 保持连接
keepalive 32;
}
server {
location / {
proxy_pass http://backend;
}
}负载均衡策略
# ip hash(同一客户端固定访问同一服务器)
upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
}
# 最少连接
upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
}
# url hash
upstream backend {
hash $request_uri consistent;
server backend1.example.com;
server backend2.example.com;
}安全配置最佳实践
防止常见攻击
# 限制请求方法
location / {
limit_except get post {
deny all;
}
}
# 防止 sql 注入和 xss(基础防护)
if ($request_uri ~* "(union|select|insert|delete|update|drop)") {
return 403;
}
# 防止目录遍历
location ~ /\. {
deny all;
}
# 限制文件上传大小
client_max_body_size 10m;访问控制
# ip 白名单
location /admin/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
# http 基本认证
location /secure/ {
auth_basic "restricted access";
auth_basic_user_file /etc/nginx/.htpasswd;
}限流配置
# 定义限流区域
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /api/ {
# 限制请求频率(每秒 1 个请求,突发最多 5 个)
limit_req zone=one burst=5 nodelay;
# 限制并发连接数
limit_conn addr 10;
}
}实战配置案例
完整的 wordpress 网站配置
server {
listen 80;
server_name myblog.com www.myblog.com;
root /var/www/wordpress;
index index.php index.html;
access_log /var/log/nginx/myblog.access.log;
error_log /var/log/nginx/myblog.error.log;
# wordpress固定链接
location / {
try_files $uri $uri/ /index.php?$args;
}
# 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;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
expires 30d;
add_header cache-control "public, immutable";
}
# 禁止访问敏感文件
location ~ /\.(ht|git) {
deny all;
}
# 禁止访问 wp-config.php
location = /wp-config.php {
deny all;
}
}前后端分离的单页应用(spa)配置
server {
listen 80;
server_name app.example.com;
root /var/www/vue-app/dist;
# spa路由支持
location / {
try_files $uri $uri/ /index.html;
}
# api反向代理
location /api/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header upgrade $http_upgrade;
proxy_set_header connection 'upgrade';
proxy_set_header host $host;
proxy_cache_bypass $http_upgrade;
}
# websocket支持
location /ws/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header upgrade $http_upgrade;
proxy_set_header connection "upgrade";
}
}配置文件管理与调试
配置文件模块化
建议将配置拆分为多个文件:
# 主配置文件 nginx.conf
http {
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}推荐的目录结构:
/etc/nginx/
├── nginx.conf # 主配置文件
├── mime.types # mime 类型
├── conf.d/ # 通用配置
│ ├── security.conf # 安全配置
│ ├── ssl.conf # ssl 通用配置
│ ├── gzip.conf # 压缩配置
│ └── proxy.conf # 代理通用配置
├── sites-available/ # 站点配置(所有)
│ ├── default
│ ├── example.com.conf
│ └── api.example.com.conf
├── sites-enabled/ # 启用的站点(软链接)
│ └── example.com.conf -> ../sites-available/example.com.conf
├── snippets/ # 可复用的配置片段
│ ├── ssl-params.conf
│ ├── proxy-params.conf
│ └── fastcgi-php.conf
└── ssl/ # ssl 证书
├── example.com.crt
├── example.com.key
└── dhparam.pem配置验证与重载
# 检查配置文件语法 nginx -t # 重新加载配置(不中断服务) nginx -s reload # 停止nginx nginx -s stop # 优雅停止(等待当前请求完成) nginx -s quit
常见问题排查
# 查看错误日志 tail -f /var/log/nginx/error.log # 查看访问日志 tail -f /var/log/nginx/access.log # 检查nginx进程 ps aux | grep nginx # 检查端口占用 netstat -tulpn | grep :80
写在最后
配置关键要点:
结构清晰:使用模块化配置,便于管理和维护
安全第一:隐藏版本号、配置ssl、设置访问控制
性能优化:合理配置 worker 进程、启用 gzip、设置缓存
日志管理:定期清理日志,使用日志切割工具
持续学习:nginx 功能强大,需要根据实际场景不断优化
学习建议:
从基础配置开始,逐步深入高级功能
在测试环境充分验证后再应用到生产环境
关注 nginx 官方文档和社区最佳实践
定期审查和优化配置文件
在 nginx 配置文件中,以 $ 开头的变量是 nginx 内置的预定义变量,它们在请求处理过程中会被自动赋值。理解这些变量对于编写灵活的配置至关重要。不要被它们吓倒,虽然 nginx 没有内置命令列出所有变量,但可以参考官方文档,见相关资源部分。实践是最好的学习方式,动手试试吧!
到此这篇关于nginx配置文件完全指南的文章就介绍到这了,更多相关nginx配置文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论