Search code examples
urlhttp-redirectcloudflarecloudflare-workers

Change the browser URL bar text


I own a domain in a hosting provider (just the domain). This domain is pointing to another web address:

domain.com-->anotherdomain.dom/path

In another side, I have added my domain to my Cloudflare account, like this:

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

The issue is that after typing domain.dom, the URL text in the browser URL bar is anotherdomain.dom/path, and I need it to be domain.com.

Is it possible to have domain.com in the broswer URL bar? Do I have to write some code inside my .htaccess file or something inside anotherdomain.com? Do I have to do something inside Cloudflare (maybe with "workers")?


Solution

  • It sounds like currently, your domain domain.com is set up as a redirect. When a user visits domain.com in their browser, the server (Cloudflare) responds with a message saying: "Please go to anotherdomain.com/path instead." The browser then acts like the user actually typed anotherdomain.com/path in the address bar.

    It sounds like what you want instead is for domain.com to be a proxy. When a request comes in for domain.com, you want Cloudflare to fetch the content from anotherdomain.com/path and then return that content in response to the original request.

    In order to do this, you will need to use Workers. Cloudflare Workers allows you to write arbitrary JavaScript code to tell Cloudflare how to handle HTTP requests for your domain.

    Here's a Worker script that implements the proxy behavior that you want:

    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;
    }