Heroku将Next.js React客户端应用HTTP重定向到https

5to*_*per 6 ssl https heroku reactjs next.js

我在Heroku上部署了一个快递服务器:https : //server.mydomain.com

在Heroku上也部署了Next.js React应用:https://app.mydomain.com

两者都有由Heroku自动配置的SSL证书,当我访问https域时,它们可以按预期工作。

我的问题是,当我访问http://app.mydomain.com时,它不会重定向到https://app.mydomain.com

我在网上找到的所有解决方案都指向在服务器上强制使用SSL:

/* At the top, with other redirect methods before other routes */
app.get('*',function(req,res,next){
 if(req.headers['x-forwarded-proto']!='https')
   res.redirect('https://app.mydomain.com'+req.url)
 else
   next() /* Continue to other routes if we're not redirecting */
})
Run Code Online (Sandbox Code Playgroud)

这些解决方案可以很好地处理服务器请求,但是加载React客户端页面不一定会触发app.get()。显然,React客户端可以独立于服务器运行。

所以问题是:如何在Heroku上强制将https用作子域Next.js React客户端应用程序?不使用快递服务器方法?

Joã*_*nha 6

我在我的一个生产应用程序中执行此操作。

我们准备下一个 app 对象并初始化一个 express 服务器。这是在server.js文件中完成的。您可以在有关自定义服务器文档中阅读有关它的更多信息。

Next.js 在他们的 github 中的 examples 文件夹中还有一个关于自定义快速服务器的示例。它在这里

const express = require('express');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });

const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {

    const server = express();

    server.use((req, res, next) => {
      const hostname = req.hostname === 'www.app.domain.com' ? 'app.domain.com' : req.hostname;

      if (req.headers['x-forwarded-proto'] === 'http' || req.hostname === 'www.app.domain.com') {
        res.redirect(301, `https://${hostname}${req.url}`);
        return;
      }

      res.setHeader('strict-transport-security', 'max-age=31536000; includeSubDomains; preload');
      next();
    });

    server.get('*', (req, res) => handle(req, res));

    server.listen(
      4242,
      error => {
        if (error) throw error;
        console.error('Listening on port 4242');
      }
    );

  })
  .catch(error => {
    console.error(error);
    process.exit(1);
  });
Run Code Online (Sandbox Code Playgroud)

至于部署到 Heroku,您应该能够自定义npm start脚本来启动 nextjs,如下所示:

"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start"
}
Run Code Online (Sandbox Code Playgroud)

Heroku 还自动运行npm run build,因此它应该为您构建应用程序。

  • 先生,您是一位绅士,一位学者。有效!感谢您花时间如此清晰地概述它。非常感激! (2认同)