Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【20161014】Nginx跨域配置 #33

Closed
zhongxia245 opened this issue Oct 14, 2016 · 1 comment
Closed

【20161014】Nginx跨域配置 #33

zhongxia245 opened this issue Oct 14, 2016 · 1 comment

Comments

@zhongxia245
Copy link
Owner

转载

原文地址:Nginx跨域配置,支持DELETE,PUT请求

自己解决跨域的几种简单方式

这里只描述一下,简单的跨域形式,不需要修改前后端代码,只需要做配置就行了。

一、Chrome浏览器关闭安全策略

开发时存在跨域,上线后部署在 一起,没有跨域问题
参照

28 Chrome关闭安全策略

背景描述

最近在研究RESTful API接口设计,使用的是Nginx,
要实现本地 http://127.0.0.1 跨域访问服务器端 http://api.zlzkj.com
并且要支持DELETE PUT等请求。

跨域配置

只需要在Nginx配置文件里加入以下配置,即可开启跨域

add_header Access-Control-Allow-Origin *;

*代表任何域都可以访问,可以改成只允许某个域访问,如Access-Control-Allow-Origin: http://www.zlzkj.com
这样的配置虽然开启了跨域请求,但只支持GET HEAD POST OPTIONS请求,使用DELETE发起跨域请求时,浏览器出于安全考虑会先发起OPTIONS请求,服务器端接收到的请求方式就变成了OPTIONS,所以引起了服务器的405 Method Not Allowed。

所以要对OPTIONS请求进行处理

if ($request_method = 'OPTIONS') { 
    add_header Access-Control-Allow-Origin *; 
    add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
    #其他头部信息配置,省略...
    return 204; 
}

当请求方式为OPTIONS时,设置Allow的响应头,重新处理这次请求。
配置好并重启Nginx,刷新页面重新发起请求,在控制台里你会发现,出现了二次请求,
第一次是OPTIONS请求,第二次才是DELETE请求,这就是对OPTIONS请求进行处理的结果,到这里总算完成了一次DELETE跨域请求了。

完整配置参考

add_header Access-Control-Allow-Origin *;
location / {
    if ($request_method = 'OPTIONS') { 
        add_header Access-Control-Allow-Origin *; 
        add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
        return 204; 
    }
    index index.php;
    try_files $uri @rewriteapp;
}

放到配置文件的server {}里

参考文章

总结

虽然最终配置代码没有几行,过程还是比较折腾的。
一开始不断地去翻墙,查阅相关文章,好不容易找到了跨域配置方法,却发现不支持DELETE等请求方式,于是又重新去翻墙,把原来的相关文章再次翻了一遍,才查到了些蛛丝马迹,又通过论坛提问,最终才找到了相应的解决方法,多折腾总有收获。

@Tseian
Copy link

Tseian commented Jan 23, 2018

跨域攻击 怎么办?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants