301 redirection port is always translated into internal port.

I am implementing a 301 redirection for www to non-www domain using an application middleware. (Next.js middleware)

The my fly.toml is the following:

primary_region = 'iad'

[build]

[http_service]
auto_start_machines = true
auto_stop_machines = true
force_https = true
internal_port = 3000
min_machines_running = 0
processes = ['app']

[[vm]]
cpu_kind = 'shared'
cpus = 1
memory_mb = 1024

The middleware in the app the following:

import { type NextRequest, NextResponse } from "next/server";

export function middleware(request: NextRequest) {
  const { nextUrl: url, headers } = request;
  const host = headers.get("host");

  if (host?.startsWith("www.")) {
    url.hostname = host.replace("www.", "");
    url.port = ""; // Empty the port so that the browser uses the default port for the protocol
    console.log(`Redirecting to ${url.toString()}`);
    return NextResponse.redirect(url);
  }

  return NextResponse.next();
}

I’ve noticed that, although the application returns a URL without a port, the internal port 3000 is always reapplied, I believe by the fly proxy.

I may be misunderstanding, but I don’t think redirection has anything to do with this.

If no port is included, the default port for the service requested is implied (e.g., 443 for an HTTPS URL, and 80 for an HTTP URL).

Host - HTTP | MDN

An [http_service] section defines a service that listens on ports 80 and 443. Port 80 will have an HTTP handler. Port 443 will have a TLS and HTTP handler. You can configure additional services on different ports by adding [[services]] sections.

. . .

  • internal_port: The port this service (and application) will use to communicate with clients. The default is 8080. We recommend applications use the default.

Fly Launch configuration (fly.toml) · Fly Docs

So, if you redirect to the default port for the protocol, the browser will send a new request to port 80 or port 443 (depending on the service), and fly will route that request to the internal_port you specify.

1 Like

Thank you very much!