Nginx Proxy Manager (NPM) 是一个基于Nginx的图形化管理工具,可以方便地配置反向代理、SSL证书等。以下是使用NPM实现跨域(CORS)访问授权管理的详细步骤:
选择或创建代理主机:
在"Advanced"选项卡中添加CORS头:
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
set $cors "";
if ($http_origin ~* (https?://(example\.com|sub\.example\.com))) {
set $cors $http_origin;
}
add_header 'Access-Control-Allow-Origin' '$cors' always;
如果需要发送Cookie或认证信息,需要额外配置:
add_header 'Access-Control-Allow-Credentials' 'true' always;
并确保Access-Control-Allow-Origin
不使用通配符*
,而是指定具体域名。
add_header 'Access-Control-Max-Age' 1728000;
对于需要特殊CORS规则的特定路径:
/api/
)如果需要基于认证的跨域控制,可以添加:
# 检查授权头
if ($http_authorization ~* "Bearer (.*)") {
# 验证token逻辑
# 如果验证通过,设置允许的源
set $cors $http_origin;
}
Access-Control-Max-Age
location / {
# CORS预检请求
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'https://example.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
# 实际请求的CORS头
add_header 'Access-Control-Allow-Origin' 'https://example.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
proxy_pass http://backend;
# 其他代理配置...
}
通过以上配置,您可以使用Nginx Proxy Manager灵活地管理跨域访问授权,既保证前端应用能正常访问API,又能确保安全性。