Nginx 1.18 解决跨域问题:CORS 配置示例
Nginx 1.18 解决跨域问题:CORS 配置示例
当遇到'Access to XMLHttpRequest at 'http://gl.kedxn.com/api/v3/adminstrator' from origin 'http://admin.integration.kedxn.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.' 这样的错误时,意味着你的前端代码(例如来自 'http://admin.integration.kedxn.com')试图访问另一个域名('http://gl.kedxn.com')的资源,而默认情况下浏览器会阻止这种跨域请求。
为了解决这个问题,你可以使用 CORS(跨域资源共享)机制,它允许服务器明确地指定哪些域可以访问它的资源。在 Nginx 中,你可以通过添加以下配置到 nginx.conf 文件来实现 CORS 支持:
location /api/ {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
}
在这个例子中,我们在 location 块中设置了一些条件和头信息来解决跨域问题。其中,OPTIONS 请求设置了 Access-Control-Allow-Origin 头信息,这样它们就可以被跨域请求访问。
我们还设置了响应的 Content-Type 和 Content-Length 头信息,以确保返回的响应正确地格式化并且正确地指定了响应的长度。
当 POST 或 GET 请求到达时,我们添加了相同的头信息来允许跨域请求。
重要说明:
- 为了安全起见,不要使用
Access-Control-Allow-Origin: *,因为它允许任何网站访问你的 API。建议根据实际需求,只允许特定域名访问 API。 - 在实际应用中,建议根据你的 API 需要暴露哪些头部信息,调整
Access-Control-Expose-Headers的设置。
通过以上配置,你就可以在 Nginx 1.18 中成功实现 CORS 支持,解决跨域请求问题。
原文地址: https://www.cveoy.top/t/topic/oY2l 著作权归作者所有。请勿转载和采集!