Skip to content

How to redirect HTTP traffic to HTTPS

Lloyd Brookes edited this page May 23, 2020 · 8 revisions

Required to satisfy this Lighthouse audit.

Summary

HTTP and HTTPS are two separate services runing on separate ports (80 and 443). Therefore, we need to launch two servers - one catching rogue HTTP traffic on port 80, the other serving the main application via HTTPS on port 443.

The HTTP server on port 80 should do nothing but redirect each request to the equivalent resource on the HTTPS server.

Setup

Install local-web-server and lws-redirect (a middleware plugin for redirecting requests).

$ npm install --save-dev local-web-server lws-redirect

Redirect HTTP traffic

Launch a server on port 80 with a single redirect rule: redirect everything to HTTPS.

$ npx ws --port 80 --stack redirect --redirect 'http -> https'

Test. Notice the Location header correctly returns the same path via HTTPS.

$ curl -I http://127.0.0.1/
HTTP/1.1 302 Found
Location: https://127.0.0.1/
Content-Type: text/html; charset=utf-8
Content-Length: 67
Date: Sun, 09 Jun 2019 16:53:38 GMT
Connection: keep-alive

Main HTTPS server

Launch the main HTTPS server. Any requests made to the HTTP server above will be redirected to this HTTPS server.

$ npx ws --port 443 --https
Clone this wiki locally