You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将主域example.co的POST请求转发至子域sub-domain.example.co?

域名请求转发配置方案

场景与需求

  • 已购入域名example.co并部署前端网站,该站点仅响应GET请求
  • 子域名sub-domain.example.co部署后端应用,专门处理POST请求
  • 核心需求:将example.co接收到的所有POST请求转发至sub-domain.example.co,同时保证GET请求由example.co正常响应

实现代码(Cloudflare Worker)

export default {
  async fetch(request) {
    const url = new URL(request.url);
    const { method } = request;

    if (method === "POST") {
      url.hostname = 'sub-domain.example.co';

      // 创建更新URL后的新请求
      const newRequest = new Request(url.toString(), {
        method: request.method,
        headers: request.headers,
        body: request.body,
        redirect: 'manual' // 确保手动处理重定向
      });

      try {
        // 发起请求并返回响应
        const response = await fetch(newRequest);
        return response;
      } catch (error) {
        console.error('转发请求出错:', error);
        return new Response('转发请求出错', { status: 500 });
      }
    }

    // 允许GET请求正常处理
    return fetch(request);
  }
};

已完成的验证操作

  • 确认DNS记录已通过Cloudflare代理
  • 已将Worker脚本正确部署,并关联路由example.co/*和*.example.co/*

内容的提问来源于stack exchange,提问作者Lavneesh Jaggi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 03:34:57