I’ve built a website with Nextjs (using version 12.1.4
). For SEO purposes I would like to make a permanent redirect for my www
version of the site to my non-www
. Normally this could easily be done with nginx or an .htaccess
file with apache. However, static websites hosted on Digitalocean are not running apache or nginx so an .htaccess file won’t do. I’ve read that this should be possible using Nextjs redirects.
I’ve tried the following 3 redirects:
redirects: async () => [
{
source: '/:path*',
has: [
{
type: 'host',
value: 'www',
},
],
destination: '/:path*',
permanent: true,
},
],
---------------------------------------------------
redirects: async () => [
{
source: '/:path*/',
has: [
{
type: 'host',
value: 'www',
},
],
destination: '/:path*/',
permanent: true,
},
],
------------------------------------------------------
redirects: async () => [
{
source: '/:path*',
has: [{ type: 'host', value: 'https://www.cvtips.nl/' }],
destination: 'https://cvtips.nl/:path*',
permanent: true,
},
],
All of them don’t seem to redirect to the non-www version. I don’t know if it is relevant, but I do use trailingSlash: true
in the config.
Next thing I tried is adding a middleware file. I both tried adding it at the root and calling it middleware.js
and inside the pages folder calling it _middleware.js
.
This is the code I use for the redirect:
--> https://github.com/vercel/next.js/discussions/33554
import { NextRequest, NextResponse } from 'next/server';
export function middleware(req: NextRequest) {
const host = req.headers.get('host');
const wwwRegex = /^www./;
// This redirect will only take effect on a production website (on a non-localhost domain)
if (wwwRegex.test(host) && !req.headers.get('host').includes('localhost')) {
const newHost = host.replace(wwwRegex, '');
return NextResponse.redirect(`https://${newHost}${req.nextUrl.pathname}`, 301);
}
return NextResponse.next();
}
Also does not work at all… Doesn’t do anything I believe.
How can I redirect a Nextjs website from www
to non-www
?
2
Answers
Try to remove
https://
, if you test it on a local machine you should restart the server. Starting with Next.js 12, middleware runs at the edge, which means it’s executed as close to the user as possible on the Vercel Edge Network or other supported platforms. DigitalOcean’s standard approach to hosting Next.js applications involves using a DigitalOcean Droplet configured with Nginx as a reverse proxy.I Hope this code is helpful
In your next.config.js file, you can set up a rewrite rule to redirect from www to non-www like this
You can create a file named middleware.js in your Next.js project’s root directory and paste the below code
make sure to include this middleware in your next.config.js like this
Remember to restart the Next.js server after adding the middleware file and modifying the next.config.js.