- 访问一个域名比如
https://test.com
,我在nginx中将它设置成跳转到https://www.test.com
,nginx配置如下:
server {
...
server_name test.com ...
# 跳转配置
if ($host != 'www.test.com' ) {
rewrite ^/(.*)$ https://www.test.com/$1 permanent;
}
# location中的跨域配置
location / {
if ($request_method = "OPTIONS") {
#... 省略
}
}
}
与此同时,我在www.test.com
中的index
页面有一个ajax接口请求 https://api.test.com/v1
- 此时我访问
test.com
或www.test.com
时,控制台都会报一个这样的错误:locked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
告诉我预检不允许跳转
我将重写的跳转配置删除,果然可以正常跨域。
- 实际情况中,我们还可能遇到各种各样的重写跳转,比如访问
http
跳转到https
,那么此时我该如何来解决跨域问题呢?
https://developer.mozilla.org...
在nginx配置里面加上 这个头,头的值为 *或者具体的域名。
也可以在api接口的响应头中加上。效果一样。