如何为 apache2.4 设置工作且安全的 CORS 配置? [复制]
Posted
技术标签:
【中文标题】如何为 apache2.4 设置工作且安全的 CORS 配置? [复制]【英文标题】:How to setup a working and secure CORS configuration for apache2.4? [duplicate] 【发布时间】:2020-02-26 07:06:01 【问题描述】:目前,我的 apache2.4 虚拟主机中有这个配置:
Header always append Access-Control-Allow-Origin "https://www.testdomain.local"
Header always append Access-Control-Allow-Origin "https://testdomain.local"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
RewriteEngine on
RewriteCond %REQUEST_METHOD OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
但是我不断收到此错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.testdomain.local/ads?_=1572477483136. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://www.testdomain.local, https://testdomain.local’).
我知道我可以通过将 Access-Control-Allow-Origin 设置为通配符来解决此问题,但这并不安全。
【问题讨论】:
您的 apache 配置在前两行设置了两次 Access-Control-Allow-Origin 标头。你不能那样做。如果你设置了两次,浏览器会合并这些值,所以浏览器最终会认为它有两个值。但是浏览器只允许它有一个值。这就是浏览器在该错误消息中告诉您的内容。 好吧,我同意。根据文档将其更改为“附加”仍然不能解决此问题:httpd.apache.org/docs/current/mod/mod_headers.html 【参考方案1】:我可以通过使用这个配置来解决它:
SetEnvIf Origin "http(s)?://(.+\.)?testdomain\.local$" CORS=$0
Header always set Access-Control-Allow-Origin "%CORSe" env=CORS
Header always merge Vary "Origin"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
RewriteEngine on
RewriteCond %REQUEST_METHOD OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
【讨论】:
以上是关于如何为 apache2.4 设置工作且安全的 CORS 配置? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
如何为使用 Cloud Firestore 的 Flutter 应用设置安全规则?
如何为 Android 应用设置 Firebase 数据库安全规则
在 QtService 上使用 QLocalServer:如何为 QLocalServer 创建的命名管道设置安全属性?