Have you ever needed to enable HTTPS on your localhost quickly and effortlessly? In this concise guide, requiring less than 2 minutes of your time, I'll walk you through a straightforward method that I discovered to achieve just that.
Why Enable HTTPS on Localhost?
In certain scenarios, like experimenting with an API that exclusively functions over HTTPS, enabling HTTPS on your localhost becomes essential. Avoiding the complexities of uploading code to external servers, such as DigitalOcean or platforms like Heroku, is particularly beneficial when dealing with non-production code.
Solution: mkcert – Your Zero-Configuration HTTPS Enabler
Meet mkcert, a user-friendly, zero-configuration tool designed for creating locally-trusted development certificates. Find it on its GitHub page and follow the instructions tailored for your operating system. For Mac users employing Homebrew, simply execute the following commands in your terminal:
brew install mkcert
mkcert -key-file ~/localhost-key.pem -cert-file ~/localhost-cert.pem localhost
Deciphering the Command:
mkcert: The command-line tool facilitating the process.
-key-file ~/localhost-key.pem: Specifies the path and filename for the private key file.
-cert-file ~/localhost-cert.pem: Specifies the path and filename for the certificate file.
localhost: The domain for which the certificate is generated.
Upon completion, two files,
localhost-key.pem (private key) and
localhost-cert.pem (certificate), will reside in your home directory.
Create a Certificate Bundle:
Run the following command to concatenate the key and certificate into a single file,
localhost-bundle.pem, for future use.
cat ~/localhost-key.pem ~/localhost-cert.pem > ~/localhost-bundle.pem
Setting Up a Secure Tunnel with stunnel:
To overcome localhost's inherent lack of SSL/TLS support, we'll utilize stunnel. Install it with:
brew install stunnel
Initiate SSL for Your Local Server:
Start your local server and execute the following command, adjusting the port numbers if necessary:
sudo stunnel3 -f -d 443 -r 8000 -p ~/localhost-bundle.pem
Breaking Down the Command:
sudo: Executes the subsequent command with elevated privileges.
stunnel3: The command-line tool creating encrypted tunnels.
-f: Runs stunnel in the foreground for real-time feedback.
-d 443: Specifies the local port for encrypted traffic (default HTTPS port).
-r 8000: Specifies the destination address and port of the local server.
-p ~/localhost-bundle.pem: Specifies the path to the concatenated certificate and private key file.
Verify Your Setup:
If all steps are executed correctly, access https://localhost to ensure your secure local server is up and running.