Search code examples
typescriptsecurityhttpsnestjs

NestJS redirect HTTP to HTTPS / force SSL


Building a NestJS Application I want to route ALL incoming traffic through https without inconvenience for the user.

So far there are two ways I know, both doesn't fit my requirements.

  1. Set up two servers for http and https and than redirect traffic per route/api endpoint, which is really not DRY and cannot be best practice. Doc redirect

  2. By only creating the https server, the user would always be forced to type the https address manually what I don't want. Doc https

Ideally I would assume a solution where https is checked and forced the very first moment some one is hitting the server by just typing example.com. I think this would best be done in main.ts of my NestJS application.


Solution

  • For production release you will probably use nginx. Nginx will be listen on port 80 and redirect to nestJS port. Advantage of this solution is easy redirecting to https. In you config you can put something like this

    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;
           ...
    }
    

    So each http request will be redirect to https. And your application don't have to care about http request because each of them will be redirect before.