Nginx配置:仅允许指定前端域名访问API
解决方案
要实现仅允许指定前端域名访问API,你需要检查请求的来源标识头(而非$host,它指的是API服务自身的域名),常用的是Referer或Origin头,下面是具体配置:
location /api { # 定义允许的前端域名(可多个,用空格分隔) set $allowed_frontend "myfrontend.com"; # 检查Referer头:来源是指定前端域名(包括子域名或完整URL前缀) if ($http_referer !~* "^https?://$allowed_frontend(/.*)?$") { # 同时检查Origin头(跨域请求会携带) if ($http_origin !~* "^https?://$allowed_frontend$") { return 403; } } proxy_pass http://127.0.0.1; # 可选:添加必要的跨域头(如果前端需要) add_header Access-Control-Allow-Origin "https://myfrontend.com"; add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"; add_header Access-Control-Allow-Headers "Content-Type, Authorization"; }
说明:
$http_referer:记录了请求的来源页面URL,匹配规则确保来源是myfrontend.com的任意页面$http_origin:跨域请求时浏览器会自动携带,匹配规则确保来源域名完全一致- 两层判断是为了覆盖不同场景:普通同域请求带Referer,跨域请求带Origin
- 如果需要允许多个前端域名,修改
$allowed_frontend为"myfrontend.com anotherfrontend.com",并调整正则为~* "^https?://($allowed_frontend)(/.*)?$"
特殊情况处理:
如果前端有特殊场景无法携带Referer/Origin(比如某些隐私模式),可以改用API密钥验证:要求前端请求时携带自定义头,Nginx检查该头是否匹配预设值,示例:
location /api { if ($http_x_api_key != "your-secret-key") { return 403; } proxy_pass http://127.0.0.1; }
内容的提问来源于stack exchange,提问作者Yash
相关产品推荐
相关产品推荐

