nginx解决跨域
nginx可以通过以下要素解决跨域问题:
- Access-Control-Allow-Origin:设置响应头指定允许的源域。
例如:
add_header Access-Control-Allow-Origin ;
- Access-Control-Allow-Credentials:如果需要允许凭证(如 cookie),设置响应头允许凭证传递。
例如:
add_header Access-Control-Allow-Credentials true;
- Access-Control-Allow-Methods:设置响应头指定允许的 HTTP 方法。
例如:
add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE, OPTIONS;
- Access-Control-Allow-Headers:设置响应头指定允许的请求头。
例如:
add_header Access-Control-Allow-Headers Content-Type, Authorization;
- Access-Control-Max-Age:设置响应头指定预检请求结果缓存的时间(单位为秒)。
例如:
add_header Access-Control-Max-Age 3600;
示例配置:
nginx
location /api {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin ;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE, OPTIONS;
add_header Access-Control-Allow-Headers Content-Type, Authorization;
add_header Access-Control-Max-Age 3600;
return 204;
}
# ...其他配置
}
![](https://img1.baidu.com/it/u=1989019465,1255087557&fm=253.jpg)