最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - redirect all routes to https in nuxt project hosted in heroku - Stack Overflow

programmeradmin0浏览0评论

I'm trying to create a middleware to redirect all my routes to https, I think I need a middleware so I've created a redirect.js file in the middleware folder of Nuxt and then I've added this to nuxt.config.js:

router: {
  middleware: ["redirect"]
},

And here is my redirect.js file that gives me a server error:

export default function({ app }) {
  if (process.env.NODE_ENV === "production") {
   if (app.context.req.header("x-forwarded-proto") !== "https") {
  app.context.res.redirect(`https://${app.context.req.header("host")}${app.context.req.url}`);
   }
  }
}

I'm trying to create a middleware to redirect all my routes to https, I think I need a middleware so I've created a redirect.js file in the middleware folder of Nuxt and then I've added this to nuxt.config.js:

router: {
  middleware: ["redirect"]
},

And here is my redirect.js file that gives me a server error:

export default function({ app }) {
  if (process.env.NODE_ENV === "production") {
   if (app.context.req.header("x-forwarded-proto") !== "https") {
  app.context.res.redirect(`https://${app.context.req.header("host")}${app.context.req.url}`);
   }
  }
}
Share Improve this question edited Jan 15, 2021 at 5:31 zcserei 6657 silver badges32 bronze badges asked Jun 17, 2019 at 10:46 yoyojsyoyojs 1,7735 gold badges24 silver badges41 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 11

I found an easier way i've added the package redirect-ssl

npm i redirect-ssl

and then i've added this line in my nuxt.config.js :

serverMiddleware: ["redirect-ssl"],

For nuxt 3 (it works with heroku):

import redirectSSL from 'redirect-ssl'
export default defineEventHandler((event) => {
  const protocol = event.node.req.headers['x-forwarded-proto']; // http || https
  const env = process.env.NODE_ENV; // development || production
  if (protocol === 'http' && env === 'production') {
    return redirectSSL(event.node.req, event.node.res)
  }
})

You can configure this in heroku.

For Nuxt static mode:

  1. Add the https://github.com/heroku/heroku-buildpack-static.git buildpack after the heroku/nodejs buildpack under buildpacks
  2. Make sure the buildpacks are added in this order to an app.json in the root directory of your project
  3. Add a static.json in the root directory of your project
    • Make sure root and https_only are set correctly
    • If you want Nuxt to resolve routes instead of Nginx (so that you don't get the Nginx 404 page when you go to an unknown route), set routes as well.

Example static.json:

{
  "root": "dist/",
  "routes": {
    "/**": "index.html"
  },
  "https_only": true
}
发布评论

评论列表(0)

  1. 暂无评论