在heroku中托管的nuxt项目中将所有路由重定向到https

yoa*_*azz 5 javascript redirect http heroku nuxt.js

我正在尝试创建一个中间件来将我的所有路由重定向到 https,我想我需要一个中间件,所以我redirect.js在 Nuxt 的中间件文件夹中创建了一个文件,然后将其添加到nuxt.config.js

router: {
  middleware: ["redirect"]
},
Run Code Online (Sandbox Code Playgroud)

这是我的redirect.js文件,它给了我一个服务器错误:

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}`);
   }
  }
}
Run Code Online (Sandbox Code Playgroud)

yoa*_*azz 5

我找到了一种更简单的方法,我添加了包 redirect-ssl

npm i redirect-ssl
Run Code Online (Sandbox Code Playgroud)

然后我在我的 nuxt.config.js 中添加了这一行:

serverMiddleware: ["redirect-ssl"],
Run Code Online (Sandbox Code Playgroud)

  • 如果您只想在生产中启用它,请尝试此行:`import redirectSSL from 'redirect-ssl'; 导出默认 { serverMiddleware: [redirectSSL.create({enabled: process.env.NODE_ENV === '生产'})]}` (2认同)