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.