首页 > 解决方案 > 更改浏览器 URL 栏文本

问题描述

我在托管服务提供商中拥有一个域(只是域)。此域指向另一个网址:

domain.com-->anotherdomain.dom/path

另一方面,我已将我的域添加到我的 Cloudflare 帐户,如下所示:

domain.com-->Cloudflare-->anotherdomain.dom/path

问题是输入后domain.dom,浏览器 URL 栏中的 URL 文本是anotherdomain.dom/path,我需要它domain.com

是否可以domain.com在浏览器的 URL 栏中有?我必须在我的.htaccess文件中写一些代码还是在里面写一些代码anotherdomain.com?我是否必须在 Cloudflare 内部做点什么(可能是“工人”)?

标签: urlredirectcloudflarecloudflare-workers

解决方案


听起来目前,您的域domain.com设置为重定向。当用户domain.com在浏览器中访问时,服务器 (Cloudflare) 会回复一条消息:“请转至anotherdomain.com/path。” 然后浏览器的行为就像用户anotherdomain.com/path在地址栏中实际键入的一样。

听起来您想要的是domain.com成为代理。当请求进入时domain.com,您希望 Cloudflare 从中获取内容anotherdomain.com/path,然后返回该内容以响应原始请求。

为此,您需要使用 Workers。Cloudflare Workers 允许您编写任意 JavaScript 代码来告诉 Cloudflare 如何处理您的域的 HTTP 请求。

这是一个实现您想要的代理行为的 Worker 脚本:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  // Parse the original request URL.
  let url = new URL(request.url);

  // Change domain name.
  url.host = "anotherdomain.org";
  // Add path prefix.
  url.pathname = "/path" + url.pathname;

  // Create a new request with the new URL, but
  // copying all other properties from the
  // original request.
  request = new Request(url, request);

  // Send the new request.
  let response = await fetch(request);

  // Use the response to fulfill the original
  // request.
  return response;
}

推荐阅读