通过nginx限制/api/ContentManage/Article/GetPageList接口访问
问题描述:/api/ContentManage/Article/GetPageList是网站端公开的调用文章列表的接口,有时会被恶意扫描,需要允许指定域名才可以调用。
解决方法:例如要允许动易的测试站*.sd.powereasy.net任意端口的站点来访问。可以nginx中添加如下规则:
location ~* ^/api/ContentManage/Article/ {
# ========== 第一步:校验 Referer ==========
if ($http_referer !~ "^https?://sd\.powereasy\.net(/|$)") {
return 403;
}
# ========== 第二步:动态设置 CORS 响应头 ==========
set $allow_origin "";
if ($http_origin ~* "^https?://sd\.powereasy\.net(/|$)") {
set $allow_origin $http_origin;
}
# 如果 Origin 为空或不在白名单,放行但用 * 兜底(保证浏览器不报 CORS 错误)
if ($allow_origin = "") {
set $allow_origin "*";
}
# ========== 第三步:在所有响应上添加 CORS 头(包括后端返回的错误码)==========
add_header 'Access-Control-Allow-Origin' "$allow_origin" always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Max-Age' 86400 always;
# ========== 第四步:处理 OPTIONS 预检请求 ==========
if ($request_method = 'OPTIONS') {
return 204;
}
# ========== 第五步:代理到后端 ==========
proxy_pass http://webservers;
include /etc/nginx/conf/proxy.conf;
}