admin管理员组文章数量:1320617
I need to redirect my subdomain (blog.site
) to the folder (site/blog
) using Cloudflare workers.
The main site, site is deployed on Netlify where I am using ReactJS. Also, I have deployed the blog using Next.js at blog.site
. All DNS are handled at Cloudflare side using 'CNAME
' Records and pointing to the Netlify routes.
Now I want to point out the subdomain into the folder structure like site/blog
. I have tried myself setting up the Cloudflare worker. But isn't working.
This is my Cloudflare worker's code:
const API_HOST = "picsht/blog"; // Main domain with the /blog path
const ASSET_HOST = "blog.picsht"; // Subdomain for static assets
async function handleRequest(request, ctx) {
const url = new URL(request.url);
const pathname = url.pathname;
const search = url.search;
const pathWithParams = pathname + search;
// Redirect from blog subdomain to the main domain /blog path
if (url.host === "blog.picsht") {
const redirectUrl = `https://${API_HOST}${pathname}${search}`;
return Response.redirect(redirectUrl, 301); // Permanent redirect
}
// Handle static asset retrieval
if (pathname.startsWith("/static/")) {
return retrieveStatic(request, pathWithParams, ctx);
}
// Forward other requests to the main domain
return forwardRequest(request, pathWithParams);
}
async function retrieveStatic(request, pathname, ctx) {
let response = await caches.default.match(request);
if (!response) {
response = await fetch(`https://${ASSET_HOST}${pathname}`);
ctx.waitUntil(caches.default.put(request, response.clone()));
}
return response;
}
async function forwardRequest(request, pathWithSearch) {
const originRequest = new Request(request);
originRequest.headers.delete("cookie"); // Avoid sending cookies for API calls
return await fetch(`https://${API_HOST}${pathWithSearch}`, originRequest);
}
export default {
async fetch(request, env, ctx) {
return handleRequest(request, ctx);
},
};
And this is the Worker Routes:
版权声明:本文标题:netlify - Redirect subdomain blog.site.com to the folder site.comblog using cloudflare workers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742077703a2419504.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论