Cloudflare做反向代理
星期三 2010年11月10日 王佳明 生活 Cloudflare 反向代理 0人
我想实现一个效果,当访问https://5ubg.com的时侯,调用https://itjm.com/5ubg/的内容。
同步实现自动更新的免部署SSL
1,把域名5ubg.com接入 Cloudflare
域名-->添加域名-->连接域名
2,部署反向代理代码
构建-->计算-->Workers和Pages-->创建应用程序-->从Hello World!开始-->部署代码-->编辑代码
清除默认代码,录入以下代码:
export default {
async fetch(request, env, ctx) {
const reqUrl = new URL(request.url);
// 用户路径,去掉开头/,做拼接
let userPath = reqUrl.pathname.slice(1);
// 手动拼接:固定子目录前缀 /5ubg/
const targetUrl = "https://itjm.com/5ubg/" + userPath + reqUrl.search;
const newHeaders = new Headers(request.headers);
newHeaders.delete("accept-encoding");
newHeaders.set("Host", "itjm.com");
const proxyReq = new Request(targetUrl, {
method: request.method,
headers: newHeaders,
body: request.body,
redirect: "manual"
});
let resp = await fetch(proxyReq);
console.log("status:", resp.status, "target:", targetUrl);
if (resp.status >= 300 && resp.status < 400) {
const loc = resp.headers.get("location");
if (loc) {
const newLoc = loc
.replace(/^https?:\/\/itjm\.com\/5ubg\//, reqUrl.origin + "/")
.replace(/^\/5ubg\//, "/");
const newHd = new Headers(resp.headers);
newHd.set("location", newLoc);
return new Response(null, { status: resp.status, headers: newHd });
}
}
const contentType = resp.headers.get("content-type") || "";
if (contentType.includes("text/html")) {
let html = await resp.text();
html = html.replaceAll("https://itjm.com/5ubg/", reqUrl.origin + "/");
html = html.replaceAll("http://itjm.com/5ubg/", reqUrl.origin + "/");
const outHeaders = new Headers(resp.headers);
outHeaders.delete("content-length");
return new Response(html, { status: resp.status, headers: outHeaders });
}
return resp;
}
};部署生效。
3,绑定域名
构建-->计算-->Workers和Pages-->创建应用程序-->刚才创建的Worker-->域-->添加域名
本站内容多数为佳明one原创,少量转载自网络。
- 本文标题:Cloudflare做反向代理
- 本文地址:https://itjm.com/2010/11/404.html
