htaccess - 如何在相同原点发送Access Control标头

时间:2016-11-24 08:44:07

标签: .htaccess cors

我的API迎合来自其他来源的请求,因此我在.htaccess中设置了以下内容:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Headers "Content-Type,Accept"
Header always set Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS"
Header always set Access-Control-Expose-Headers "Content-Type,Content-Length"

但是,我希望这些标题不会在没有预检时显示,例如,GET请求,或者我自己的网站访问此API。

一个例子:

$ curl 127.0.0.1/api/featured/ -I
HTTP/1.1 200 OK
Date: Thu, 24 Nov 2016 08:33:47 GMT
Server: Apache/2.4.18 OpenSSL/1.0.1k-fips PHP/5.6.19
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type,Accept
Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS
Access-Control-Expose-Headers: Content-Type,Content-Length
X-Powered-By: PHP/5.6.19
Content-Type: text/html; charset=UTF-8

这感觉相当无关紧要;这是localhost中的一个卷曲,它仍在发送CORS头。我应该怎么做呢?

1 个答案:

答案 0 :(得分:1)

当请求是同源时,可以使用以下内容来抑制CORS头:

List

如果SetEnvIf Origin "^https://example\.com$" IS_SAME_ORIGIN Header always set Access-Control-Allow-Origin "*" env=!IS_SAME_ORIGIN Header always set Access-Control-Allow-Headers "Content-Type,Accept" env=!IS_SAME_ORIGIN Header always set Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS" env=!IS_SAME_ORIGIN Header always set Access-Control-Expose-Headers "Content-Type,Content-Length" env=!IS_SAME_ORIGIN 标头的值为" implementation,则Apache会检查Origin请求标头并设置IS_SAME_ORIGIN SetEnvIf { {1}}"

其他行使用environment variable指定仅在Origin环境变量设置时才发送CORS标头。