官网解释说明
http://nginx.org/en/docs/configure.html
隐藏版本号信息
http {
# 关闭在响应头中显示Nginx版本号
# 默认响应头: Server: nginx/1.18.0
# 关闭后响应头: Server: nginx
server_tokens off;
}
限制连接数
为防止DOS攻击,应该限制单个IP的连接数和请求频率
http {
# 定义一个共享内存区域,用于存储IP连接数信息
# $binary_remote_addr: 使用二进制格式存储客户端IP,节省空间
# zone=addr:10m: 指定共享内存区域名称为addr,大小为10MB
limit_conn_zone $binary_remote_addr zone=addr:10m;
# 限制每个IP同时最多100个连接
limit_conn addr 100;
# 定义请求频率限制,每个IP每秒最多10个请求
# rate=10r/s: 每秒10个请求
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=10r/s;
# 应用请求频率限制,burst=20表示最多允许20个请求排队
limit_req zone=req_zone burst=20 nodelay;
}
配置白名单
对于管理后台等敏感区域,建议配置IP白名单
location /admin/ {
# 允许内网IP段访问
# 192.168.1.0/24: 允许192.168.1.x网段的所有IP
allow 192.168.1.0/24;
# 允许另一个内网IP段访问
allow 10.0.0.0/8;
# 拒绝其他所有IP访问
deny all;
# 开启基础认证
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}
SSL/TLS安全配置
配置SSL证书并强制HTTPS访问
server {
# 监听443端口,启用SSL
listen 443 ssl;
server_name wangjian.run;
ssl on; #开启https
ssl_certificate /etc/nginx/server.crt; #配置nginx ssl证书的路径
ssl_certificate_key /etc/nginx/server.key; #配置nginx ssl证书key的路径
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #指定客户端建立连接时使用的ssl协议版本,如果不需要兼容TSLv1,直接去掉即可
ssl_ciphers HIGH:!aNULL:!MD5; #指定客户端连接时所使用的加密算法,你可以再这里配置更高安全的算法
# 将所有HTTP请求重定向到HTTPS ,也可以把if判断去掉 直接写return即可
if ($scheme != "https") {
return 301 https://$server_name$request_uri;
}
}
在 Nginx 中,$scheme
是一个内置变量,用于表示客户端请求使用的协议方案。它通常可以取以下值:
http
:当客户端使用 HTTP 协议发起请求时,$scheme
的值为http
。https
:当客户端使用 HTTPS 协议发起请求时,$scheme
的值为https
。
限制上传文件大小
防止通过上传大文件耗尽服务器资源
# 限制请求体大小,即上传文件的最大大小为10MB
client_max_body_size 10m;
# 设置请求体缓冲区大小为128KB
# 超过此大小的请求体会被写入临时文件
client_body_buffer_size 128k;
# 配置临时文件存储路径
client_body_temp_path /var/nginx/client_body_temp;
配置上传目录权限
location /uploads/ {
# 指定上传根目录
root /var/www/uploads;
# 指定临时文件目录
client_body_temp_path /var/www/tmp;
# 允许的WebDAV方法
dav_methods PUT DELETE MKCOL COPY MOVE;
# 自动创建上传目录
create_full_put_path on;
# 设置目录访问权限
# user:rw - 文件所有者可读写
# group:rw - 组用户可读写
# all:r - 其他用户只读
dav_access user:rw group:rw all:r;
# 限制上传文件类型
if ($request_filename ~* ^.*?\.(php|php5|sh|pl|py)$) {
return 403;
}
}
防止SQL注入
配置特殊字符过滤
location / {
# 检查URL中是否包含特殊字符
# 如果包含分号、单引号、尖括号等字符,返回444状态码
# 444是Nginx特殊状态码,表示关闭连接而不发送响应头
if ($request_uri ~* [;'<>] ) {
return 444;
}
# 检查查询字符串中的特殊字符
if ($args ~* [;'<>] ) {
return 444;
}
# 保护敏感URI
location ~* /(admin|backup|config|db|src)/ {
deny all;
}
}
防止目录遍历
禁止访问隐藏文件和目录
# 禁止访问所有以点开头的隐藏文件和目录
location ~ /\. {
# 拒绝所有请求
deny all;
# 禁止记录访问日志
access_log off;
# 禁止记录404错误日志
log_not_found off;
}
# 禁止访问特定目录
location ~* ^/(uploads|images)/.*\.(php|php5|sh|pl|py|asp|aspx|jsp)$ {
deny all;
}
# 防止目录列表
location / {
autoindex off;
}
配置访问日志
详细记录访问信息,便于安全分析
# 定义详细的日志格式
log_format detailed '$remote_addr - $remote_user [$time_local] ' # 记录客户端IP和访问时间
'"$request" $status $body_bytes_sent ' # 记录请求信息、状态码和发送字节数
'"$http_referer" "$http_user_agent" ' # 记录来源页面和用户代理
'$request_time $upstream_response_time'; # 记录请求处理时间和上游响应时间
# 配置访问日志
# buffer=32k: 使用32KB缓冲区
# flush=5s: 每5秒刷新一次日志
access_log /var/log/nginx/access.log detailed buffer=32k flush=5s;
# 对于静态资源,可以关闭访问日志以提高性能
location /static/ {
access_log off;
}
配置错误日志
设置适当的错误日志级别
# 设置错误日志级别为warn
# 可选级别: debug, info, notice, warn, error, crit, alert, emerg
error_log /var/log/nginx/error.log warn;
# 对于开发环境,可以使用debug级别获取更多信息
# error_log /var/log/nginx/error.log debug;
禁止执行脚本
在静态资源目录中禁止执行脚本
location /static/ {
# 禁止执行PHP文件
location ~ \.(php|php5)$ {
deny all;
}
# 只允许特定文件类型
location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 30d; # 设置缓存时间
add_header Cache-Control "public, no-transform";
}
}
配置超时时间
设置合理的超时参数,防止慢速攻击
# 客户端请求体超时时间,单位秒
client_body_timeout 10;
# 客户端请求头超时时间
client_header_timeout 10;
# 客户端保持连接超时时间
# 第一个参数是客户端超时时间
# 第二个参数是在响应头中的Keep-Alive超时时间
keepalive_timeout 5 5;
# 向客户端发送响应的超时时间
send_timeout 10;
# 读取代理服务器响应的超时时间
proxy_read_timeout 10;
# 连接代理服务器的超时时间
proxy_connect_timeout 10;
根据协议设置不同的响应头
server {
listen 80;
listen 443 ssl;
server_name example.com;
if ($scheme = http) {
add_header X-Forwarded-Proto http;
}
if ($scheme = https) {
add_header X-Forwarded-Proto https;
}
}
在这个例子中,使用 add_header
指令,根据 $scheme
的值设置 X-Forwarded-Proto
响应头。对于 HTTP 请求,将 X-Forwarded-Proto
头设置为 http
,对于 HTTPS 请求,将其设置为 https
。
后端服务的协议选择
server {
listen 80;
server_name example.com;
location / {
proxy_pass $scheme://backend;
}
}
在这个配置中,proxy_pass
指令使用 $scheme
来决定将请求代理到后端服务时使用的协议,是 HTTP 还是 HTTPS。
常用nginx配置
# main段配置信息 全局配置,对全局生效;
user nginx; # 运行用户,默认即是nginx,可以不进行设置
worker_processes auto; # Nginx 进程数,一般设置为和 CPU 核数一样
error_log /var/log/nginx/error.log warn; # Nginx 的错误日志存放目录
pid /var/run/nginx.pid; # Nginx 服务启动时的 pid 存放位置
# events段配置信息
events {
use epoll;#使用epoll的I/O模型(如果你不知道Nginx该使用哪种轮询方法,会自动选择一个最适合你操作系统的)
worker_connections 1024; # 每个进程允许最大并发数
}
#负载均衡配置 默认是轮询
upstream backend_pool {
ip_hash;#解决负载均衡 session 的问题
server localhost:8080 weight=9; #负载均衡权重
server localhost:8081 weight=1;
# 以下是健康检查相关设置(使用ngx_http_upstream_check_module模块,需要安装这个模块)
check interval = 3000 rise = 2 fall = 3 timeout = 1000; #表示每隔3000毫秒(3 秒)对后端服务器进行一次健康检查。如果连续2次检查成功,则认为服务器恢复正常(rise = 2);如果连续3次检查失败,则认为服务器不可用(fall = 3),检查超时时间为1000毫秒(1 秒)。
check_http_send "HEAD / HTTP/1.0\r\n\r\n"; #定义了发送给后端服务器进行健康检查的 HTTP 请求内容,这里是发送一个HEAD请求到根路径。
check_http_expect_alive http_2xx http_3xx; #表示如果后端服务器返回2xx或3xx状态码,则认为服务器是健康的。
}
# http段配置信息
# 配置使用最频繁的部分,代理、缓存、日志定义等绝大多数功能和第三方模块的配置都在这里设置
http {
#设置日志模式
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; # Nginx访问日志存放位置
sendfile on; # 开启高效传输模式
keepalive_timeout 65; # 保持连接的时间,也叫超时时间,单位秒
include /etc/nginx/mime.types; # 文件扩展名与类型映射表
include /etc/nginx/conf.d/*.conf; # 加载子配置项
default_type application/octet-stream; # 默认文件类型
server_tokens off; #隐藏nginx版本号
server {
listen 80; # 标准 HTTP 协议 配置监听的端口
server_name https://wangjian.run; # 配置的域名或者ip地址
#默认访问配置
location / {
root /usr/share/nginx/html; # 网站根目录
index index.html index.htm; # 默认首页文件
}
error_page 500 502 503 504 /50x.html; # 默认50x对应的访问页面
error_page 400 404 error.html; # 默认40x对应的访问页面
#拒绝User-Agent
location / {
if ($http_user_agent ~* LWP::Simple|BBBike|wget|curl) {
return 444;
}
}
#反向代理配置,在这里设置一个代理,和 upstream 的名字一样
location /backend_pool/ {
#跨域问题
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods *;
add_header Access-Control-Allow-Headers *;
return 204;
}
#proxy_pass http://localhost:3000;
proxy_pass http://backend_pool/;#必填
proxy_set_header Host $host$server_port; #必填 设置转发请求的Host头信息,确保后端服务器能够正确识别请求的主机名,以及端口号,正常情况下无需带$server_port
proxy_set_header X-Real-IP $remote_addr; #必填 将客户端的真实IP地址传递给后端服务器。
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #必填 添加一个X-Forwarded-For头信息,用于记录请求经过的代理服务器链(如果有多个代理),其中包含客户端的真实 IP 地址。
}
#黑名单 表示拒绝192.168.1.0/24;,其它的都允许访问
location /ops-coffee/ {
deny 192.168.1.0/24;
allow all;
}
#黑白名单ip配置方式
localhost /moni/ {
#ip允许拒绝配置,可以放到 http, server, location, limit_except 语句块
deny IP; # 屏蔽单个 ip 访问
allow IP; # 允许单个 ip 访问
deny all; # 屏蔽所有 ip 访问
allow all; # 允许所有 ip 访问
deny 123.0.0.0/8; # 屏蔽整个段即从 123.0.0.1 到 123.255.255.254 访问的命令
deny 124.45.0.0/16; # 屏蔽IP段即从 123.45.0.1 到 123.45.255.254 访问的命令
deny 123.45.6.0/24; # 屏蔽IP段即从 123.45.6.1 到 123.45.6.254 访问的命令
#写法2
set $allow false;
if ($http_x_forwarded_for = "211.144.204.2") { set $allow true; }
if ($http_x_forwarded_for ~ "108.2.66.[89]") { set $allow true; }
if ($allow = false) { return 404; }
}
}
server {
listen 443;
server_name ops-coffee.cn;
ssl on; #开启https
ssl_certificate /etc/nginx/server.crt; #配置nginx ssl证书的路径
ssl_certificate_key /etc/nginx/server.key; #配置nginx ssl证书key的路径
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #指定客户端建立连接时使用的ssl协议版本,如果不需要兼容TSLv1,直接去掉即可
ssl_ciphers HIGH:!aNULL:!MD5; #指定客户端连接时所使用的加密算法,你可以再这里配置更高安全的算法
}
}
配置文件 events 段核心参数
location /test/ {
...
}
不带 / 当访问 www.nginx-test.com/test 时, Nginx 先找是否有 test 目录,如果有则找 test 目录下的 index.html ;如果没有 test 目录, nginx 则会找是否有 test 文件;
带 / 当访问 www.nginx-test.com/test 时, Nginx 先找是否有 test 目录,如果有则找 test 目录下的 index.html ,如果没有它也不会去找是否存在 test 文件。
2) return
停止处理请求,直接返回响应码或重定向到其他 URL ;执行 return 指令后, location 中后续指令将不会被执行。
return code [text];
return code URL;
return URL;
例如:
location / {
return 404; # 直接返回状态码
}
location / {
return 404 "pages not found"; # 返回状态码 + 一段文本
}
location / {
return 302 /bbs ; # 返回状态码 + 重定向地址
}
location / {
return https://www.baidu.com ; # 返回重定向地址
}
rewrite
根据指定正则表达式匹配规则,重写 URL 。
语法:rewrite 正则表达式 要替换的内容 [flag];
上下文:server、location、if
示例:rewirte /images/(.*\.jpg)$ /pic/$1; # $1是前面括号(.*\.jpg)的反向引用
flag 可选值的含义:
last 重写后的 URL 发起新请求,再次进入 server 段,重试 location 的中的匹配;
break 直接使用重写后的 URL ,不再匹配其它 location 中语句;
redirect 返回 302 临时重定向;
permanent 返回 301 永久重定向。
server{
listen 80;
server_name fe.lion.club; # 要在本地hosts文件进行配置
root html;
location /search {
rewrite ^/(.*) https://www.baidu.com redirect;
}
location /images {
rewrite /images/(.*) /pics/$1;
}
location /pics {
rewrite /pics/(.*) /photos/$1;
}
location /photos {
}
}
按照这个配置我们来分析:
当访问 fe.lion.club/search 时,会自动帮我们重定向到 https://www.baidu.com;
当访问 fe.lion.club/images/1.jpg 时,第一步重写 URL 为 fe.lion.club/pics/1.jpg ,找到 pics 的 location ,继续重写 URL 为 fe.lion.club/photos/1.jpg ,找到 /photos 的 location 后,去 html/photos 目录下寻找 1.jpg 静态资源。
if 指令
语法:if (condition) {...}
上下文:server、location
示例:
if($http_user_agent ~ Chrome){
rewrite /(.*)/browser/$1 break;
}
condition 判断条件:
$variable 仅为变量时,值为空或以0开头字符串都会被当做 false 处理;
= 或 != 相等或不等;
~ 正则匹配;
! ~ 非正则匹配;
~* 正则匹配,不区分大小写;
-f 或 ! -f 检测文件存在或不存在;
-d 或 ! -d 检测目录存在或不存在;
-e 或 ! -e 检测文件、目录、符号链接等存在或不存在;
-x 或 ! -x 检测文件可以执行或不可执行;
实例:
server {
listen 8080;
server_name localhost;
root html;
location / {
if ( $uri = "/images/" ){
rewrite (.*) /pics/ break;
}
}
}
当访问 localhost:8080/images/ 时,会进入 if 判断里面执行 rewrite 命令。
autoindex
用户请求以 / 结尾时,列出目录结构,可以用于快速搭建静态资源下载网站。
autoindex.conf 配置信息:
server {
listen 80;
server_name fe.lion-test.club;
location /download/ {
root /opt/source;
autoindex on; # 打开 autoindex,,可选参数有 on | off
autoindex_exact_size on; # 修改为off,以KB、MB、GB显示文件大小,默认为on,以bytes显示出⽂件的确切⼤⼩
autoindex_format html; # 以html的方式进行格式化,可选参数有 html | json | xml
autoindex_localtime off; # 显示的⽂件时间为⽂件的服务器时间。默认为off,显示的⽂件时间为GMT时间
}
}
当访问 fe.lion.com/download/ 时,会把服务器 /opt/source/download/ 路径下的文件展示出来,如下图所示:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容