NestJS 将 HTTP 重定向到 HTTPS / 强制 SSL

Fuz*_*per 4 security https typescript nestjs

构建 NestJS 应用程序 我想通过 https 路由所有传入流量,而不会给用户带来不便。

目前我知道的有两种方式,都不符合我的要求。

  1. 为 http 和 https 设置两个服务器,然后重定向每个路由/api 端点的流量,这确实不是 DRY,也不是最佳实践。文档重定向

  2. 通过仅创建 https 服务器,用户总是被迫手动输入我不想要的 https 地址。文档 https

理想情况下,我会假设一个解决方案,其中检查 https 并强制有人只需键入即可访问服务器的第一刻example.com。我认为这最好在我的 NestJS 应用程序中完成main.ts

R. *_* V. 7

对于我的用例,我认为没有理由在节点 http 服务器功能齐全的情况下使用反向代理层来使服务器膨胀。由于问题与 NestJS 有关,这里我使用 Nest 中间件提出简单的本机解决方案。当然,您还必须遵循有关托管两个服务器的 NestJS 文档,这也相当简单。

import { HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from "express";

@Injectable()
export class HttpsRedirectMiddleware implements NestMiddleware
{
    use(req: Request, res: Response, next: () => void)
    {
        if (!req.secure)
        {
            const httpsUrl = `https://${req.hostname}${req.originalUrl}`;
            res.redirect(HttpStatus.PERMANENT_REDIRECT, httpsUrl);
        }
        else
        {
            next();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我们只是询问请求对象连接是否安全,如果不安全,我们会促使浏览器永久重定向到相同的 url,但这次前缀为https://. configure()然后,上面的中间件类将在的方法中为所有路由注册AppModule

configure(consumer: MiddlewareConsumer)
{
    consumer.apply(HttpsRedirectMiddleware).forRoutes("*");
}
Run Code Online (Sandbox Code Playgroud)


Prz*_*ert 5

对于生产版本,您可能会使用nginx。Nginx 将监听端口 80 并重定向到 NestJS 端口。此解决方案的优点是可以轻松重定向到 https。在你的配置中你可以放置这样的东西

server {
       listen         80;
       server_name    example1.com example2.com;
       return         301 https://$host$request_uri;
}

server {
       listen         443 ssl;
       server_name    example1.com example2.com;
       ...
}
Run Code Online (Sandbox Code Playgroud)

所以每个http请求都会被重定向到https。并且您的应用程序不必关心 http 请求,因为每个请求之前都会被重定向。