最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

netlify - Redirect subdomain blog.site.com to the folder site.comblog using cloudflare workers - Stack Overflow

programmeradmin6浏览0评论

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:

发布评论

评论列表(0)

  1. 暂无评论