CentOS 上 Nginx 防盗版与资源保护策略
一 核心目标与思路
二 推荐策略与配置示例
基础安全响应头与版本隐藏
http {
server_tokens off;
more_set_headers 'Server: WebServer'; # 需 ngx_http_headers_more_module
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'self';";
}
Referer 防盗链(基础且高效)
location ~* \.(jpg|jpeg|png|gif|webp|ico|css|js|woff2)$ {
root /usr/local/nginx/html;
valid_referers none blocked your_domain.com *.your_domain.com;
if ($invalid_referer) { return 403; }
expires 30d;
add_header Cache-Control "public, max-age=2592000";
access_log off; # 可选:静态资源关闭日志,降 IO
}
下载类资源的强校验与一次性链接(可选进阶)
location /download/ {
internal;
alias /data/files/;
add_header Content-Disposition 'attachment';
}
location ~* ^/dl/([a-zA-Z0-9]+)$ {
# 伪代码:校验 $arg_token、$arg_expires、资源存在与权限
# if (!valid_token($1, $arg_token, $arg_expires)) { return 403; }
# set $real_path /download/$1;
# rewrite ^ /download/$1 last;
return 403; # 未通过鉴权则拒绝
}
访问频率与并发限制(防批量抓取与刷流)
http {
limit_req_zone $binary_remote_addr zone=req:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn:10m;
server {
location ~* \.(jpg|jpeg|png|gif|webp|ico|css|js|woff2)$ {
root /usr/local/nginx/html;
valid_referers none blocked your_domain.com *.your_domain.com;
if ($invalid_referer) { return 403; }
limit_req zone=req burst=20 nodelay;
limit_conn conn 10;
expires 30d;
add_header Cache-Control "public, max-age=2592000";
access_log off;
}
}
}
访问控制与黑白名单(精准拦截)
location /admin/ {
allow 203.0.113.10;
allow 198.51.100.0/24;
deny all;
}
location /admin/ {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/conf.d/.htpasswd;
}
# 生成密码:htpasswd -c -m /etc/nginx/conf.d/.htpasswd alice
三 部署与验证步骤
,应返回 403。四 注意事项与扩展