nginx配置有重写跳转时如何同时解决跨域问题?

  • 访问一个域名比如 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.comwww.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,那么此时我该如何来解决跨域问题呢?
阅读 4.5k
1 个回答

https://developer.mozilla.org...

在nginx配置里面加上 这个头,头的值为 *或者具体的域名。

也可以在api接口的响应头中加上。效果一样。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题