Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

redirect-ssl #73

Open
yoann54 opened this issue Mar 16, 2020 · 1 comment
Open

redirect-ssl #73

yoann54 opened this issue Mar 16, 2020 · 1 comment

Comments

@yoann54
Copy link

yoann54 commented Mar 16, 2020

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

@daveberning
Copy link

daveberning commented Oct 9, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants