Apache2 同源策略解决方案 - 配置 CORS

什么是同源策略

现在的浏览器大多配有同源策略(Same-Origin Policy),具体表现如下:

浏览某一网站,例如 http://www.decembercafe.org/。这个网页中的 Ajax 请求(XMLHttpRequest)试图获取另一个网站(例如 http://www.csdn.net/)的数据时,会发生错误。

具体错误如下,Chrome 提示

XMLHttpRequest cannot load **. No ‘Access-Control-Allow-Origin’
header is present on the requested resource. Origin ‘null’ is
therefore not allowed access.

Apache2 里配置 CORS

CORS 是其中一种解决方案。

某一网站在服务器端配置了 CORS 后,就可以接受其它域名发送来的 XMLHttpRequest 请求。

Apache2 里配置 CORS 的步骤如下。

找到配置文件,

/etc/apache2/apache2.conf

打开后,找到,

<Directory /var/www>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

将下面的语句加到倒数第二行:

Header set Access-Control-Allow-Origin*

保存后,执行下列语句,以确保语法正确:

apachectl -t

然后执行下列语句,重新调用配置。

sudo service apache2 reload

默认情况下,mod_headers是开启的,为防万一,可用以下语句开启

a2enmod headers

参考资料

[1] http://enable-cors.org/server_apache.html

posted on 2016-11-23 11:38  三少爷的剑123  阅读(1096)  评论(0编辑  收藏  举报

导航