Home > Enterprise >  Nextjs redirect non-www to www
Nextjs redirect non-www to www

Time:12-29

So, from what I've read using www is better than not using it, and I want to redirect all non-www requests to www.

I want to do this in the next.config.js or if it's not possible in the middleware.js

CodePudding user response:

You can't do it with next.config.js, but in your main js file, if you use express you can do it like this :

const server = express()

  server.use((req, res, next) => {
    if (req.headers.host.slice(0, 4) === 'www.') {
      next()
    } else {
      res.writeHead(301, {
        Location: `https://www.${req.headers.host}${req.url}`
      })
      res.end()
    }
  })

CodePudding user response:

With the help of @Johan, I've managed to write an answer for nextjs:

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

// This function can be marked `async` if using `await` inside
export function middleware(req: NextRequest) {
    const host = req.headers.get('host')
    if (host?.slice(0, 4) !== 'www.' && !host?.includes('localhost')) {
        return NextResponse.redirect(`https://www.${host}${req.nextUrl.pathname}`, 301);
    }
}
  • Related