Nginx 配置示例
以下是我们的 Nginx 配置示例:
location /your/path {
# 允许所有域名访问
add_header 'Access-Control-Allow-Origin' '*';
# 或者允许特定域名访问(示例:example.com 和 another-domain.com)
# add_header 'Access-Control-Allow-Origin' 'https://example.com, https://another-domain.com';
# 指定允许的 HTTP 方法
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
# 指定允许的请求头
add_header 'Access-Control-Allow-Headers' 'Origin, Authorization, Content-Type, Accept, X-Requested-With';
# 如果请求方法为 OPTIONS,则直接返回 204 状态码
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Origin, Authorization, Content-Type, Accept, X-Requested-With';
return 204;
}
# 转发请求到后端服务
proxy_pass http://192.168.99.12:10086;
}
配置解析
location /your/path:
该指令定义了一个 URI 路径,当请求的路径匹配 /your/path 时,Nginx 将应用以下配置。
add_header ‘Access-Control-Allow-Origin’ ‘*’:
允许所有域访问该资源。使用 * 表示允许任何来源的请求。这种设置适用于公共 API,但在安全性要求较高的场景下,建议使用特定的域名。
允许特定域名访问:
如果您希望限制某些特定的域名,可以用如下方式设置:
nginx
复制
add_header ‘Access-Control-Allow-Origin’ ‘https://example.com, https://another-domain.com’;
这种方式只允许 https://example.com 和 https://another-domain.com 访问该资源。
add_header ‘Access-Control-Allow-Methods’ ‘GET, POST, OPTIONS’:
指定允许的 HTTP 方法,这里包括 GET、POST 和 OPTIONS。
add_header ‘Access-Control-Allow-Headers’ ‘Origin, Authorization, Content-Type, Accept, X-Requested-With’:
指定允许的请求头,确保客户端可以发送这些头部信息。
处理预检请求:
CORS 中的预检请求是指在实际请求前,浏览器先发送一个 OPTIONS 请求,以确定服务器是否允许该请求。
if ($request_method = ‘OPTIONS’):
检查请求方法是否为 OPTIONS。
add_header …:
如果是 OPTIONS 请求,添加相应的 CORS 头部。
return 204:
返回 HTTP 204 状态码,表示请求成功且没有内容返回。
proxy_pass:
proxy_pass http://192.168.99.12:10086;
将请求转发到指定的后端服务。
通过以上配置,Nginx 可以有效地处理跨域请求,允许来自不同源的前端应用访问其资源。配置中的 CORS 头部确保了浏览器能够正确地识别和处理跨域请求
————————————————