skip to Main Content

I have been trying to find a workable solution this searching google but can’t find anything solid. I am hosting my Next.js application on Vercel.

When I run a seo check it moans about me having the site available on www and non www and says I should pick one and get it to redirect so in my case, if someone types in www.example.com I would prefer it left of the www.

Since I don’t have a htaccess file I can do this in, how would I do it?

Not sure if it matters, but I am using WordPress as my backend aka: Headless WordPress

2

Answers


  1. you can easily handle permanent redirection in nextjs using the below-mentioned code.

    export const getServerSideProps = async (context) => {
        const { req, res } = context;
    
        if (req.headers.host.match(/^www/) !== null) {
            res.writeHead(301, {
                location: "https://" + req.headers.host.replace(/^www./, "") + req.url,
            });
            res.end();
        }
    
        return { props: {} };
    };
    
    Login or Signup to reply.
  2. You should be able to use host-based redirects now since Next v10.2. See https://nextjs.org/docs/api-reference/next.config.js/redirects#header-cookie-and-query-matching.

    In next.config.js:

    module.exports = {
      // ...
      redirects: async () => [
        {
          source: '/:path*',
          has: [{ type: 'host', value: 'www.yourdomain.com' }],
          destination: 'https://yourdomain.com/:path*',
          permanent: true
        }
      ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search