Cloudflare是一家美国的跨国科技企业,以向客户提供网站安全管理、性能优化及相关的技术支持为主要业务。通过基于反向代理的内容分发网络(CDN, Content Delivery Network)、任播(Anycast)技术、基于nginx+lua架构的Web应用防火墙(WAF, Web Application Firewall)及分布式域名解析服务(Distributed Domain Name Server)等技术,Cloudflare可以帮助受保护站点抵御包括分布式拒绝服务攻击(DDoS, Distributed Denial of Service)在内的大多数网络攻击,确保该网站长期在线,同时提升网站的性能、访问速度以改善访客体验。
今年有个项目,使用的正是Cloudflare的CDN服务,同时双向配置了SSL证书,运行一向平稳安全~
某一天,应业务需要搭建了个分站,突然发现项目样式、JS无法正常调用、加载,不过最终还是找到了解决方案,mark一下。
项目情况描述:
A站,域名是website.com,即部署了Cloudflare的CDN服务站点,也配置了双向SSL证书(Cloudflare 泛SSL + 真实服务器SSL)
B站,域名是xx.website.com(A站的分站),也部署了Cloudflare的CDN服务,同时也配置了SSL证书(真实服务器SSL),B站前端调用了A站的js、样式、字体、图片等文件
问题:访问B站的时候,A站的js、样式、字体等文件全部无法加载,Chrome报错为xxx has been blocked by CORS policy: No ‘Access-Control-Allow-Origin‘ header is present
解决方案:
一、创建 CloudFlare Worker 服务
设置服务名称,然后选择 HTTP 处理程序
二、创建Workers服务
点击“Workers—>服务—>cros—>资源”,快速编辑
将以下代码复制编辑框中,保存并部署
const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS", "Access-Control-Max-Age": "86400", } function handleOptions (request) { // Make sure the necessary headers are present // for this to be a valid pre-flight request let headers = request.headers if ( headers.get("Origin") !== null && headers.get("Access-Control-Request-Method") !== null && headers.get("Access-Control-Request-Headers") !== null ) { // Handle CORS pre-flight request. // If you want to check or reject the requested method + headers // you can do that here. let respHeaders = { ...corsHeaders, // Allow all future content Request headers to go back to browser // such as Authorization (Bearer) or X-Client-Name-Version "Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers"), } return new Response(null, { headers: respHeaders, }) } else { // Handle standard OPTIONS request. // If you want to allow other HTTP Methods, you can do that here. return new Response(null, { headers: { Allow: "GET, HEAD, POST, OPTIONS", }, }) } } async function handleRequest (request) { let response if (request.method === "OPTIONS") { response = handleOptions(request) } else { response = await fetch(request) response = new Response(response.body, response) response.headers.set("Access-Control-Allow-Origin", "*") response.headers.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") } return response } addEventListener("fetch", (event) => { event.respondWith( handleRequest(event.request).catch( (err) => new Response(err.stack, { status: 500 }) ) ) } )
三、添加路由
点击“Workers—>服务—>cros—>触发器”,添加路由
注:使用星号 (*) 字符可代替泛指
再访问B站测试一下,发现CloudFlare CORS 跨域问题已解决~
————————————————
参考文章:
https://developers.cloudflare.com/workers/examples/cors-header-proxy
https://uaxk.com/cloudflare-cors-error/