nuxt-community / redirect-module

No more cumbersome redirects for Nuxt 2!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

redirect-ssl

yoann54 opened this issue · comments

I wonder if we could use this module to redirect each url to https, Is there a pattern that someone already used ?

Hey @yoann54. I've exhausted this route. I also tried writing serverMiddleware to do the redirect with the nuxt service. Nothing worked but creating an Express server instance did.

You need to create a .js file (could be any name) and register it in your nuxt.config.js file as serverMiddleware. In my case, I have a file named redirect.js in a directory named api.

In your nuxt.config.js file:

serverMiddleware: [
    '~/api/redirect'
],

In your redirect.js file:

import express from 'express'

const app = express()

if (process.env.NODE_ENV === 'production') {
  app.use((req, res, next) => {
    const hasWWW = req.headers.host.includes('www.')
    const protocol = req.header('x-forwarded-proto')
    const isSecure = protocol && protocol === 'https'
    const fullUrl = `${protocol}://${req.get('host')}${req.originalUrl}`
    const redirectedUrl = `https://www.your-domain.com${req.url}`

    if (fullUrl === redirectedUrl) {
      next()
    } else if ((!isSecure && hasWWW) || (!isSecure && !hasWWW) || (isSecure && !hasWWW)) {
      // Always redirect to  https://www.your-domain.com
      res.redirect(301, redirectedUrl)
    } else {
      next()
    }
  })
}

export default app

In this case, I am 301 redirecting any combo of my domain to https://www. The final result will be...

http://www.your-domain.com -> https://www.your-domain.com
http://your-domain.com -> https://www.your-domain.com
https://your-domain.com -> https://www.your-domain.com

It's important to have that first if statement though to check if the initial request equals the domain you want to redirect to. If you don't have this, you will get an infinite loop.