且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Access-Control-Allow-Origin 通配符子域、端口和协议

更新时间:2022-11-22 19:45:18

基于DaveRandom的answer,我也在玩周围并找到了一个稍微简单的 Apache 解决方案,它产生相同的结果(Access-Control-Allow-Origin 动态设置为当前特定协议 + 域 + 端口),而不使用任何重写规则:

Based on DaveRandom's answer, I was also playing around and found a slightly simpler Apache solution that produces the same result (Access-Control-Allow-Origin is set to the current specific protocol + domain + port dynamically) without using any rewrite rules:

SetEnvIf Origin ^(https?://.+.mywebsite.com(?::d{1,5})?)$   CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin  %{CORS_ALLOW_ORIGIN}e   env=CORS_ALLOW_ORIGIN
Header merge  Vary "Origin"

就是这样.

那些想要在父域(例如 mywebsite.com)以及所有子域上启用 CORS 的人可以简单地将第一行中的正则表达式替换为这个:

Those who want to enable CORS on the parent domain (e.g. mywebsite.com) in addition to all its subdomains can simply replace the regular expression in the first line with this one:

^(https?://(?:.+.)?mywebsite.com(?::d{1,5})?)$.

注意:对于 规范合规性 和正确的缓存行为,始终为启用 CORS 的资源添加 Vary: Origin 响应标头,即使对于非 CORS 请求和来自不允许来源的请求(请参阅 示例原因).

Note: For spec compliance and correct caching behavior, ALWAYS add the Vary: Origin response header for CORS-enabled resources, even for non-CORS requests and those from a disallowed origin (see example why).