无论如何都要在cloudflare中添加自定义标题?
我们做一些https ajax来缓存静态文件, 但它没有处理像#34; Access-Control-Allow-Credentials"在响应标题中,并导致chrome失败。
答案 0 :(得分:5)
Scott Helme发布了一种方法,使用最近发布的新Cloudflare Workers来实现这一目标。
https://scotthelme.co.uk/security-headers-cloudflare-worker/
let securityHeaders = {
"Content-Security-Policy": "upgrade-insecure-requests",
"Strict-Transport-Security": "max-age=1000",
"X-Xss-Protection": "1; mode=block",
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
}
let sanitiseHeaders = {
"Server": "My New Server Header!!!",
}
let removeHeaders = [
"Public-Key-Pins",
"X-Powered-By",
"X-AspNet-Version",
]
addEventListener('fetch', event => {
event.respondWith(addHeaders(event.request))
})
async function addHeaders(req) {
let response = await fetch(req)
let newHdrs = new Headers(response.headers)
if (newHdrs.has("Content-Type") && !newHdrs.get("Content-Type").includes("text/html")) {
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHdrs
})
}
Object.keys(securityHeaders).map(function(name, index) {
newHdrs.set(name, securityHeaders[name]);
})
Object.keys(sanitiseHeaders).map(function(name, index) {
newHdrs.set(name, sanitiseHeaders[name]);
})
removeHeaders.forEach(function(name) {
newHdrs.delete(name)
})
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHdrs
})
}
答案 1 :(得分:0)
cloudflare不支持这种可能性
答案 2 :(得分:0)
要添加自定义标头,请在Cloudflare中选择Workers
。
要添加自定义标头,例如Access-Control-Allow-Credentials
或X-Frame-Options
,然后添加以下小脚本:-
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
let response = await fetch(request)
let newHeaders = new Headers(response.headers)
newHeaders.set("Access-Control-Allow-Credentials", "true")
newHeaders.set("X-Frame-Options", "SAMEORIGIN")
// ... and any more required headers
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
})
}
创建完工作人员后,您需要将其与路线匹配,例如
如果您现在使用例如Chrome开发工具,您将看到响应标题。