Redirect www to root domain
johnjoubert
PROOP

a year ago

Hey there,

Similar to this thread: https://station.railway.com/questions/i-would-like-to-setup-a-www-redirect-to-d883ff50

I want to redirect my www to the root domain.

I use Namecheap (which according to your documentation) does support ALIAS / CNAME Flattening records. https://docs.railway.com/guides/public-networking#adding-a-custom-domain

How do I set this up correctly in Railway?

Solved

3 Replies

a year ago

Hello,

Railway itself does not offer any way to do the redirection at the platform level.

You would need to do this redirection in your code, likely with some middleware.

Best,
Brody


Status changed to Awaiting User Response Railway 12 months ago


johnjoubert
PROOP

a year ago

Thanks Brody, I was hoping for a slightly better walkthrough but I managed to figure this out.

For posterity, here's what I did:
1. Added both www and root domains to the Railway settings
2. Added CNAMEs for both in Namecheap
3. Wrote a middleware for NextJS:

```

import { NextResponse } from 'next/server';

export function middleware(req) {
  const host = req.headers.get('host') || '';

  if (host.startsWith('www.')) {
    const url = new URL(req.url);
    url.host = host.slice(4);
    url.port = '';

    return NextResponse.redirect(url, 301);
  }
  return NextResponse.next();
}

export const config = {
  matcher: '/((?!api|_next|favicon.ico).*)',
};

```


Status changed to Awaiting Railway Response Railway 12 months ago


Status changed to Solved johnjoubert 12 months ago


eddorileo
PRO

a year ago

thanks


Status changed to Awaiting Railway Response Railway 12 months ago


Status changed to Solved brody 12 months ago


Welcome!

Sign in to your Railway account to join the conversation.

Loading...