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

什么是同源策略

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

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

具体错误以下,Chrome 提示浏览器

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

Apache2 里配置 CORS

CORS 是其中一种解决方案。服务器

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

Apache2 里配置 CORS 的步骤以下。cors

找到配置文件,ide

/etc/apache2/apache2.conf

打开后,找到,网站

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

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

Header set Access-Control-Allow-Origin*

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

apachectl -t

而后执行下列语句,从新调用配置。

sudo service apache2 reload

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

a2enmod headers

参考资料

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

相关文章
相关标签/搜索