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");