apaceh 配置:
<VirtualHost *:80> ServerAdmin xxx@qq.com DocumentRoot "C:/htdocs/demo" ServerName dev.dd.cn ##ErrorLog "logs/dummy-host.localhost-error.log" ##CustomLog "logs/dummy-host.localhost-access.log" combined <Directory "C:/htdocs/demo"> #Require all denied Header set Access-Control-Allow-Origin * </Directory> </VirtualHost>
PHP文件设置:
<?php header("Access-Control-Allow-Origin:*"); //处理请求输出数据 ?>
配置的含义是允许任何域发起的请求都可以获取当前服务器的数据。当然,这样有很大的危险性,恶意站点可能通过XSS攻击我们的服务器。所以我们应该尽量有针对性的对限制安全的来源,例如下面的设置使得只有http://feng.com这个域才能跨域访问服务器的API。
httpd.conf:
<VirtualHost *:80> ServerAdmin xxx@qq.com DocumentRoot "C:/htdocs/demo" ServerName dev.dd.cn ##ErrorLog "logs/dummy-host.localhost-error.log" ##CustomLog "logs/dummy-host.localhost-access.log" combined <Directory "C:/htdocs/demo"> #Require all denied Header set Access-Control-Allow-Origin http://feng.com </Directory> </VirtualHost>
PHP文件中:
header("Access-Control-Allow-Origin:http://feng.com");