10 months 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?
3 Replies
10 months 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 • 10 months ago
10 months 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 • 10 months ago
Status changed to Solved johnjoubert • 10 months ago
Status changed to Awaiting Railway Response Railway • 10 months ago
Status changed to Solved brody • 10 months ago
