3

Who knows how to make redirects in nuxt.js from www to non-www?

Thanks in advance.

Igor Oleniuk
  • 145
  • 4
  • 11
  • Please elaborate. for redirection, you have `nuxt-link` or anchor tag with href or router push – Hardik Shah Apr 20 '20 at 06:12
  • @HardikShah, I have a project on nuxt.js (universal mode) and I want to make redirect each time when user open link with www for example (www.example.com) to non-www url (example.com) – Igor Oleniuk Apr 21 '20 at 19:44

2 Answers2

1

Incase any is still having this issue.

I had to solve it with CloudFlare using this article https://support.cloudflare.com/hc/en-us/articles/200172286-How-do-I-perform-URL-forwarding-or-redirects-with-Cloudflare-

You can also achieve it with serverMiddleware https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-servermiddleware#custom-server-middleware

Create a file and paste in the following code.

module.exports = function (req, res, next) {
  const host = req.headers.host
  const url = req.url
  const env = process.env.NODE_ENV
  const forceDomain = 'https://masteringbackend.com'

  if (env === 'production' && host !== 'www.masteringbackend.com') {
    res.writeHead(301, { Location: forceDomain + url })
    return res.end()
  }

  return next()
}

Then you register the file in serverMiddleware

Another way

You can take a look at https://mindthecode.com/blog/how-to-redirect-www-traffic-to-non-www-in-your-express-app/ but remember that res.redirect is only for Express, to do redirect in Connect (pure node.js http): Response redirect in Connect

Kaperskyguru
  • 73
  • 3
  • 8
-1

Regarding Kaperskyguru shared code for the serverMiddleware: It is almost perfect, but the "if line" should be "===" instead of "!==". For me this one works:

module.exports = function (req, res, next) {
 const host = req.headers.host
 const url = req.url
 const env = process.env.NODE_ENV
 const forceDomain = 'https://masteringbackend.com'

 if (env === 'production' && host === 'www.masteringbackend.com') {
   res.writeHead(301, { Location: forceDomain + url })
   return res.end()
 }

 return next()
}