Fetch in Workers does not work with non standard ports

Hi, I’m using Workers to create an API gateway for my web service which is hosted on a non-standard port. I find the worker does not honor the port in the URL; it simply ignores it.

To reproduce and give a proof-of-concept of this bug, I tested with this website https://tls-v1-2.badssl.com:1012/, which is available on port 1012, and if you don’t specify the port, the server on port 443 will 301 redirect you to port 1012.

The worker script is super simple:

addEventListener("fetch", (event) => {
      (err) => new Response(err.stack, { status: 500 })

async function handleRequest(request) {
  const url = new URL("https://tls-v1-2.badssl.com:1012/");
  return fetch(url, {method: "GET", redirect: "follow"});

Accessing this worker will get a “too many redirects” error:

TypeError: Too many redirects.; urlList = https://tls-v1-2.badssl.com:1012/, https://tls-v1-2.badssl.com:1012/, https://tls-v1-2.badssl.com:1012/, https://tls-v1-2.badssl.com:1012/, ...

This is because Cloudflare is constantly ignoring the port and always accessing the server from port 443, thus always getting a redirect to port 1012. You can further verify this by changing the redirect policy from follow to manual:

return fetch(url, {method: "GET", redirect: "manual"});

With manual redirect, the browser (client) actually receives the 301 redirection from the worker and is redirected to https://tls-v1-2.badssl.com:1012.

I searched the forum and found a number of posts about this bug:


Some of them mentioned that this bug is only present in the production environment, and things work fine in the live preview environment. I can also confirm this.

It seems this bug has been around for quite a long time. Is it really considered a bug, or is it actually designed to not allow non standard ports?