Who knows how to make redirects in nuxt.js from www to non-www?
Thanks in advance.
Who knows how to make redirects in nuxt.js from www to non-www?
Thanks in advance.
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
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()
}