Apache 2.4 CORS configuration
如果是 api 的話,可以在程式的部分加上 header,但 resouce file (如圖片等)就得在 apache 裏頭做設定了
可以針對要設定的目錄在 site configuration file (/etc/apache2/sites-enabled/)中加上
<Directory /var/opt/www/mirror/public/vspf> Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers X-Requested-With </Directory>
這樣在該目錄底下的所有 resource file 就可以 CORS access 了。
如果是程式的話就得自己處理,以 php phalcon 為例會類似長這樣
$this->view->disable(); $resp = new \Phalcon\Http\Response(); $resp->setHeader("Access-Control-Allow-Origin", "*"); $resp->setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With');
或者在要允許CORS資源的目錄編輯 .htaccess,同樣地要記得開啟headers module
#remember to sudo a2enmod headers Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers X-Requested-With
要測試 CORS 是否設定正確可以用 curl command
curl -I -X OPTIONS -H "Origin: http://EXAMPLE.COM" -H 'Access-Control-Request-Method: GET' YOUR_CORS_RESOURCE_URL 2>&1 | grep 'Access-Control-Allow-Origin'
如果要針對某些檔案格式做CORS而已,那可以加上<Files> tag
#remember to sudo a2enmod headers <Files "*.ttf"> Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers X-Requested-With </Files>
Original link: Phanix's Blog