Nginx 配置不求人
Nginx是一个高性能的HTTP服务和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。能支持50000个并发连接数
这里放上参考文档
常用命令
查看帮助:nginx -h
查看版本号:nginx -v
启动:nginx
关闭:nginx -s stop
重新加载配置文件 nginx -s reload
配置文件组成
1. nginx.conf 主配置文件
文件位置 nginx\conf\nginx.conf
nginx.conf
#===================================== Nginx全局配置 =====================================#
#指定 nginx 进程运行的用户,默认nobody window下需要注释
#user nobody;
#允许生成的进程数,默认为1, window下无法利用多核cpu,Linux可以设置更大
worker_processes 1;
#日志 路径 级别 可以放入全局块,http块,server块 debug|info|notice|warn|error|crit|alert|emerg
error_log logs/error.log;
#error_log logs/error.log notice;
#指定nginx进程运行文件存放地址
pid logs/nginx.pid;
#===================================== Nginx全局配置 =====================================#
#======================================== events ========================================#
events {
worker_connections 2048; #最大连接数,默认为512
multi_accept on; #设置一个进程是否同时接受多个网络连接,默认为off
#accept_mutex on; #设置网路连接序列化,防止惊群现象发生,默认为on Linux特性,Windows下关闭增加性能
#accept_mutex_delay 500ms; #如果一个进程无互斥锁,它将默认延迟500ms Linux特性,Windows下关闭增加性能
# Linux特性,Windows下不支持 事件驱动模型,默认select(在大量连接性能较差)|poll|kqueue|epoll|resig|/dev/poll|eventport
#use epoll;
# Linux特性,Windows下不支持 事件驱动模块为use epoll时配置:
#epoll_events 1024; #默认512,每次事件循环最多处理512个事件
#epoll_event_connections 2048; #默认2048,每个事件最多处理2048个连接
#epoll_timeout 1s; #默认0,即epoll模块不会超时,时间取决于操作系统
}
#======================================== events ========================================#
#======================================== stream ========================================#
stream {
# 导入 stream 配置文件
include ../conf.d/_conf-stream.conf;
}
#======================================== stream ========================================#
#========================================= http =========================================#
http {
include mime.types;
#默认文件类型,默认为text/plain
default_type application/octet-stream;
#隐藏 Nginx 版本号,防止黑客针对特定版本的漏洞进行攻击
server_tokens off;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format detail '$remote_addr - $host [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time $upstream_response_time $upstream_addr '
'$host $request_id $gzip_ratio $upstream_cache_status';
log_format json escape=json '{ "time": "$time_local", '
'"ip": "$remote_addr", '
'"xff": "$http_x_forwarded_for", '
'"host": "$host", '
'"method": "$request_method", '
'"uri": "$request_uri", '
'"status": $status, '
'"bytes": $body_bytes_sent, '
'"rt": $request_time, '
'"urt": "$upstream_response_time", '
'"uaddr": "$upstream_addr", '
'"ustatus": "$upstream_status", '
'"ref": "$http_referer", '
'"ua": "$http_user_agent", '
'"rid": "$request_id" }';
#buffer [高性能] 缓冲写入(减少磁盘 I/O 次数)
access_log logs/access.log json buffer=32k flush=5s;
#Windows下sendfile会导致文件锁定(无法保存文件),开发机设为 off
sendfile on; # 开启高效文件传输模式 允许sendfile方式传输文件,默认为off,可以在http块,server块,location块
sendfile_max_chunk 0; # 每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限
#禁掉 Nagle 算法,让小数据包(如 API 响应)立即发送,降低延迟
tcp_nodelay on;
tcp_nopush on; # 提高大文件传输效率 Linux优化项,Windows下注释 测 1.28.0 版本window可开启
#开发环境不需要太长的连接保持 缩短超时,方便调试频繁的连接
keepalive_timeout 120s 120s; # 连接超时时间,默认为75s,可以在http,server,location块
#生产环境100提高到 500~1000,减少高并发下的 TCP 握手次数
keepalive_requests 100; # 每个长连接最多处理100个请求(避免连接长期占用)
# 优化速度 调整TCP接收/发送缓冲区(用系统默认的1.5倍,避免太小导致频繁IO) 增大内存缓冲区,减少临时文件产生
client_body_buffer_size 128k; # 客户端请求体缓冲
large_client_header_buffers 4 16k; # 大请求头缓冲
# gzip压缩配置
gzip on;
gzip_comp_level 5; # 5-6 性价比最高 压缩的级别,一般取2-6,级别越高,压缩的越小,但越耗费服务器的cpu
gzip_min_length 1k; # 超过1K的文件才进行压缩
# 图片(png/jpeg/gif/svg)一般已经压缩,再 gzip 可能收益不大 按需添加
gzip_types application/json application/javascript application/x-javascript application/xml application/xml+rss application/xhtml+xml text/plain text/css text/xml text/javascript image/svg+xml; # 文件类型
gzip_vary on; # 在响应头中添加 Vary
gzip_proxied any; # 无论请求经过了多少层代理,只要符合文件类型,通通压缩
gzip_buffers 16 8k; # 优化内存缓冲
# 优化速度 缓存静态文件的元数据 避免每次请求都去磁盘读取 开发环境注释掉
open_file_cache off; # 开发关闭
#open_file_cache max=20000 inactive=20s; # 缓存2万个文件元数据,20秒未用则淘汰
#open_file_cache_valid 30s; # 每30秒验证一次缓存有效性
#open_file_cache_min_uses 2; # 一个文件被访问2次后才缓存
#open_file_cache_errors on; # 缓存文件不存在/权限错误(减少重复磁盘检查)
# 优化速度 缓存静态文件的元数据 避免每次请求都去磁盘读取
# 跨域配置 $cors_origin 变量 (_default_location_cross_config.conf)
map $http_origin $cors_origin {
default "";
"~^https?://([a-zA-Z0-9-]+\.)*reinffy\.cc$" $http_origin
}
# 导入 server 配置文件
include ../conf.d/server*.conf;
}
#========================================= http =========================================#TIP
如果直接使用上述配置内容,记得根据实际情况修改 [!code warning] 黄色高亮区域内容
2. server*.conf 自定义的server配置
文件位置 nginx\conf.d\serve*.conf
serve-1.conf
############################################## HTTP server 80 default 生产环境强制使用https ###########################
#server {
# listen 80;
# listen [::]:80;
# server_name localhost;
# charset utf-8;
# # 强制所有HTTP流量重定向到HTTPS
# return 301 https://$server_name$request_uri;
#}
############################################## HTTP server 80 default 生产环境强制使用https ###########################
############################################## HTTPS server localhost default ################################################
server {
# server基本配置
listen 80; # 开发环境开发80,根据需求添加
listen [::]:80; # 开发环境开发80,根据需求添加
listen 443 ssl; # 443端口 开启ssl
listen [::]:443 ssl; # 443端口 开启ssl
http2 on;
server_name localhost;
charset utf-8;
# ban IP
include ../conf.d/_deny-ip.conf;
# log access使用流式写入
access_log logs/access.[localhost].log json buffer=32k flush=5s;
error_log logs/error.[localhost].log warn;
# SSL证书 仅对开了ssl的listen端口生效
ssl_certificate ../conf.d/ssl/cert.pem; # 证书颁发机构给的公钥crt openssl手动转pem文件
ssl_certificate_key ../conf.d/ssl/key.pem; # 发送给证书机构的私钥key openssl手动转pem文件
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off; # 如果不需要会话票据的话可以关闭
ssl_protocols TLSv1.2 TLSv1.3; # TLSv1 TLSv1.1 已经不安全
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
# SSL证书
# add_header 警告⚠:如果 location 有 add_header 配置,这里的安全头、跨域头等头需要在 location 复制一份,否则不生效!
# 安全头信息 HSTS 开启(注意:开启后很难回退到 HTTP,请确保证书稳定)
#add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
#add_header X-Content-Type-Options nosniff;
#add_header X-Frame-Options DENY;
#add_header X-XSS-Protection "1; mode=block";
# 安全头信息
# 默认配置
include ../conf.d/_default.conf;
include ../conf.d/_default_server_public_static_resources.conf;
# 页面示例
# location /txb {
# alias html/txb/dist/;
# index index.html index.htm;
# try_files $uri $uri/ /txb/index.html;
# }
# 范围大的 放下面
# 缓存配置
# location ~* \.(?:css|js|jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
# alias html/;
# expires 7d;
# access_log off;
# }
location / {
alias html/;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
# 默认页面代理配置 例如:Alist
# location / {
# # 代理默认配置
# #rewrite ^/(alist|nas)/(.*)$ /$1 break; # URL 重写
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 设置代理 IP 传递IP链
# proxy_set_header X-Forwarded-Proto $scheme; # 设置代理协议 传递协议(http/https)
# proxy_set_header Host $http_host; # 设置 Host 头部,保持原始 Host 信息 后台可以获取到完整的ip+端口号
# proxy_set_header X-Real-IP $remote_addr; # 设置客户端真实 IP
# proxy_set_header Range $http_range; # 资源头部信息
# proxy_set_header If-Range $http_if_range; # 资源头部信息 一致性
# proxy_redirect off; # 设置代理重定向的行为 off关闭; "http->https":"https://$host/ https://$http_host/;"
# client_max_body_size 20000m; # 上传文件的最大大小
# client_body_buffer_size 128k; # 客户端请求体缓冲
# proxy_read_timeout 60; # 代理超时时间 秒
# proxy_request_buffering off; # 杀手锏 允许后端(Alist)直接接收数据,不经过 Nginx 磁盘缓冲
# proxy_buffering off; # 杀手锏 关闭下载缓冲,提升流媒体或大文件下载实时性
# # 代理目标
# proxy_pass http://127.0.0.1:6379/;
# # 引入跨域配置
# include ../conf.d/_default_location_cross_config.conf;
# # 安全头信息 HSTS 开启(注意:开启后很难回退到 HTTP,请确保证书稳定)
# #add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
# #add_header X-Content-Type-Options nosniff;
# #add_header X-Frame-Options DENY;
# #add_header X-XSS-Protection "1; mode=block";
# # 安全头信息
# #开发环境优化 !生产环境注释! 知道请求到底命中了哪个 server 块或者 upstream
# add_header X-Served-By $hostname;
# add_header X-Cache-Status $upstream_cache_status;
# #开发环境优化
# }
# 默认页面代理配置 例如:Alist
}
#==============================================================================================================#TIP
根据实际情况使用,并不一定原封不动的复制
ssl需要的证书文件位置在 nginx\conf.d\xxx.pem, 根据情况处理
3. 抽离出去的配置 _conf-stream.conf
文件位置 nginx\conf.d\_conf-stream.conf
_conf-stream.conf
#upstream stream_server_7890 {
# server 127.0.0.1:7890; #被代理的服务器,
# }
# server {
# listen 32001;
# proxy_connect_timeout 8s; #连接超时
# proxy_timeout 1h; #代理服务器超时
# proxy_pass stream_server_7890; #明确指定被代理服务器
# }4. 抽离出去的配置 _default.conf
文件位置 nginx\conf.d\_default.conf
_default.conf
# proxy设置 代理全局超时设置
proxy_connect_timeout 30s; # 后端服务器连接的超时时间 生产环境不宜过长,快速失败 15s
proxy_send_timeout 120s; # 后端服务器数据回传时间 生产环境不宜过长,快速失败 60s
proxy_read_timeout 120s; # 等候后端服务器响应时间 生产环境不宜过长,快速失败 60s
# proxy设置
# http设置
client_header_timeout 20s; # 客户端请求头超时
client_body_timeout 40s; # 客户端请求体超时
# http设置
# 拒绝访问隐藏文件(.git, .env, .htaccess 等)
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 拒绝访问隐藏文件(.git, .env, .htaccess 等)
# 禁用子目录的目录浏览
autoindex off;
# 自定义错误页重定向
# 404
error_page 404 /404.html;
location = /404.html {
root html/.error_page;
internal; # 仅限内部重定向访问,防止外部直接访问
}
# 50x
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html/.error_page;
internal; # 仅限内部重定向访问,防止外部直接访问
}
# 自定义错误页重定向5. 抽离出去的配置 _default_location_cross_config.conf
文件位置 nginx\conf.d\_default_location_cross_config.conf
_default_location_cross_config.conf
# include ../conf.d/_default_location_cross_config.conf;
# 跨域配置 根据请求的 Origin 动态设置允许的来源 在需要的块引入 location (因为if里的add_header,不要再server层引入!)
# (如敏感的支付接口)可能不需要跨域,而静态资源或公共 API 需要
# 就近原则,add_header一旦命中,其他层级/块全部失效,需要注意!如果其他地方也有add_header配置!
# # 已在 http 块定义 map $http_origin $cors_origin (全局有效) 可修改具体限制域名
# 添加 CORS 头
add_header 'Access-Control-Allow-Origin' '$cors_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Range' always;
add_header 'Access-Control-Allow-Credentials' 'true' always; # 如果需要携带 cookie 等凭证
# 针对 OPTIONS 预检请求的处理
if ($request_method = OPTIONS) {
# 因为这里有 return,所以必须在这里重复一遍 add_header
# 否则这个 200 返回将不带任何跨域头
add_header 'Access-Control-Allow-Origin' '$cors_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
# 设置预检请求的有效期(秒),减少频繁发送 OPTIONS
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 200;
}
# 屏蔽后端干扰 关键:禁止后端设置 Access-Control-Allow-Origin
# 如果后端(如 Node.js、Python)也设置了 CORS,请关闭它!
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Credentials;
proxy_hide_header Access-Control-Allow-Methods;
proxy_hide_header Access-Control-Allow-Headers;
# 跨域配置TIP
根据实际情况使用,并不一定原封不动的复制
根据第一行 include ../conf.d/_default_location_cross_config.conf;引入
add_header 并不是增加,而是覆盖,一旦命中当前块内出现 add_header,那么这个块的其他层级(父级http层,子集if{}内等)的 add_header 都不生效;
6. 抽离出去的配置 _default_server_public_static_resources.conf
文件位置 nginx\conf.d\_default_server_public_static_resources.conf
_default_server_public_static_resources.conf
# include ../conf.d/_default_server_public_static_resources.conf;
# 静态资源服务 在server块引入
# #这里是放在http块中的配置
# map $http_origin $cors_origin {
# default "";
# "~^https?://([a-zA-Z0-9-]+\.)*localhost\.top$" $http_origin;
# }
# 正则匹配,~为区分大小写,~*为不区分大小写。
location ^~ /public {
alias public/;
# --- 传输优化 ---
sendfile on; # 开启高效文件传输模式
tcp_nopush on; # 提高大文件传输效率
tcp_nodelay on; # 禁掉 Nagle 算法,让小数据包(如 API 响应)立即发送,降低延迟
# 文件元数据缓存
# 优化速度 缓存静态文件的元数据 避免每次请求都去磁盘读取
open_file_cache off; # 限开发环境
# open_file_cache max=20000 inactive=20s; # 生产环境开启 缓存2万个文件元数据,20秒未用则淘汰
# open_file_cache_valid 30s; # 生产环境开启 每30秒验证一次缓存有效性
# open_file_cache_min_uses 2; # 生产环境开启 一个文件被访问2次后才缓存
# open_file_cache_errors on; # 生产环境开启 缓存文件不存在/权限错误(减少重复磁盘检查)
# 优化速度 缓存静态文件的元数据 避免每次请求都去磁盘读取
# --- 传输优化 ---
# --- 目录列表(开发开启,生产建议由外层 include 决定或手动关) ---
autoindex on; # 开启目录文件列表 会暴露文件结构 # 生产环境务必关闭 红线
autoindex_exact_size off; # 显示文件大小,单位 MB/GB
autoindex_localtime on; # 显示文件时间
charset utf-8,gbk; # 避免中文乱码
# --- 目录列表(开发开启,生产建议由外层 include 决定或手动关) ---
# --- 头部逻辑处理 ---
# 初始化变量(默认为空,空变量不会触发 add_header)
set $my_disposition "";
set $my_content_type "";
# 对图片等资源缓存
if ($request_filename ~* \.(png|jpg|jpeg|gif|ico)$) {
expires 7d;
}
# 仅开发环境 关闭指定文件在线预览
if ($request_filename ~* ^.*?\.(html|doc|pdf|docx|txt|zip|rar)$) {
set $my_disposition "attachment";
set $my_content_type "application/octet-stream";
}
# 统一输出 Header
# 只要变量不为空,这些 Header 就会和底部的 Cache-Control 一起发送
add_header Content-Disposition $my_disposition;
add_header Content-Type $my_content_type;
# 缓存控制头
# add_header Cache-Control "public, max-age=31536000, immutable"; # 生产环境
add_header Cache-Control "public, max-age=0, no-transform"; # 开发环境
#add_header ETag "5f8d0a3e8d4a7a23a6f1b3e"; # 写死会导致内容更新后浏览器不会重新获取,强制等缓存过期
# --- 头部逻辑处理 ---
# --- 暴力防盗链 (可选) 手动更改域名 ---
valid_referers none blocked server_names *.localhost.com;
if ($invalid_referer) { return 403; }
# --- 暴力防盗链 (可选) ---
# 文件预读 window下如果报错,注释它
read_ahead 1m;
}
# 静态资源服务TIP
根据实际情况使用,并不一定原封不动的复制
根据第一行 include ../conf.d/_default_server_public_static_resources.conf;引入
默认的一个静态资源服务,要确保nginx\public 文件夹存在
7. 抽离出去的配置 _deny-ip.conf 如果需要
文件位置 nginx\conf.d\_deny-ip.conf
_deny-ip.conf
# 1. 允许珠海电信IP段
allow 219.131.0.0/16;
allow 113.108.0.0/16;
allow 183.56.0.0/16;
allow 116.7.0.0/16;
# 2. 允许珠海联通IP段
allow 120.83.0.0/16;
allow 112.90.0.0/16;
allow 112.96.0.0/16;
# 3. 允许珠海移动IP段
allow 120.232.0.0/16;
allow 117.136.0.0/16;
# 4. 允许本地回环IP
allow 127.0.0.1;
# 5. 拒绝所有其他IP
#deny all;
allow all; # 允许其他所有IP访问(必须放在最后,否则所有IP都被拦截)场景 让8080同时支持http 和 https
极端场景下可能出现这种情况,例如,在政务网因政策、审批或其他原因只开放一个端口;
但是需要兼容不同的设备、服务、或历史遗留问题;
添加 server
# HTTP/HTTPS server 8080 让8080支持http和https访问 ##############################################################
server {
# server基本配置
listen 20036 proxy_protocol; # 通过stream的map 8080代理 HTTP 逻辑入口
listen 20037 proxy_protocol ssl; # 通过stream的map 8080代理 HTTPS 逻辑入口
server_name localhost;
charset utf-8;
real_ip_recursive on;
real_ip_header proxy_protocol; #基于stream层传来protocol数据进行后续修改
set_real_ip_from 127.0.0.0/24; #从real_ip_header中删除这个ip段的ip,也可直接写具体ip;
# ban IP
include ../conf.d/_deny-ip.conf;
# log
access_log logs/access.[8080].log json buffer=32k flush=5s;
error_log logs/error.[8080].log warn;
# SSL证书
ssl_certificate ../conf.d/ssl/cert.pem; # 证书颁发机构给的公钥crt
ssl_certificate_key ../conf.d/ssl/key.pem; # 发送给证书机构的私钥key
#
# 默认配置
include ../conf.d/_default.conf;
# 页面代理设置
location / {
alias html/;
index index.html index.htm;
#try_files $uri $uri/ /index.html;
}
}
# HTTP/HTTPS server 8080 让8080支持http和https访问 ##############################################################_conf-stream.conf 添加 配置
# 让8080支持http和https访问 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
upstream http_gateway {
server 127.0.0.1:20036; # 20036端口是一个开启http的端口
}
upstream https_gateway {
server 127.0.0.1:20037; # 20037端口是一个开启https的端口
}
map $ssl_preread_protocol $upstream{ # 根据不同的协议走不同的upstream
default http_gateway;
"TLSv1.0" https_gateway;
"TLSv1.1" https_gateway;
"TLSv1.2" https_gateway;
"TLSv1.3" https_gateway;
}
server {
listen 8080; # 实际监听端口
ssl_preread on;
proxy_pass $upstream;
proxy_protocol on; #开启protocol
}
# 让8080支持http和https访问 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑_conf-stream.conf 是抽离出来的 stream 模块(http配置内)的内容
不想抽离也可以直接在 nginx/conf/nginx.conf 内编辑:
#======================================== stream ========================================#
stream {
# 导入 stream 配置文件
include ../conf.d/_conf-stream.conf;
#... 直接在这里添加也是一样的
}
#======================================== stream ========================================#场景 限制IP请求频率
Details
http {
# 定义一个名为 one 的限速区域,10MB 内存,平均速率 1 请求/秒
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
listen 80;
server_name example.com;
location /search/ {
# 使用 one 区域,允许突发最多 5 次请求,超出的请求会排队延迟处理
limit_req zone=one burst=5;
}
}
}场景 VNC代理
server
# 升级 HTTP 协议的场景 vnc(远程)代理配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
#==============================================================================================================#
############################################## HTTP VNC TEST 8002 ##################################################
#server {
# # server基本配置
# listen 18002;
# charset 'utf-8'; #中文字符编码
# #access_log logs/host.access.log main;
#
# location / {
# autoindex on;
# root html/tool-vnc/;
# index index.html index.htm vnc_lite.html;
# # 缓存配置
# #location ~ .*.(?:jpg|jpeg|png|svg)$ { # 匹配静态资源的文件后缀
# # expires 7d; # 7天后过期
# #}
# try_files $uri $uri/ /index.html; #history路由资源重定向
# }
#
#}
#==============================================================================================================#