Create a Self-Signed Certificate for NGINX on macOS

Nginx Jul 18, 2020 Viewed 3K Comments 0

In order to develop better, sometimes we need to configure https in our own local environment. This guide describes how to create a Self-Signed Certificate for NGINX on macOS.

1. Create openssl.cnf

Copy a openssl.cnf to the current directory:

cp /System/Library/OpenSSL/openssl.cnf openssl.cnf

Add the following 2 lines at the end of openssl.cnf. test.cpming.top is resolved to 127.0.0.1 in the file of /private/etc/hosts. It can be another domain, such as localhost.

[v3_ca]
subjectAltName = DNS:test.cpming.top

2. Create the SSL Certificate

Create the requisite directories:

mkdir -p /usr/local/etc/ssl/private
mkdir -p /usr/local/etc/ssl/certs

Create a key and certificate pair:

sudo openssl req \
  -x509 -nodes -days 365 -newkey rsa:2048 \
  -subj "/CN=test.cpming.top" \
  -config openssl.cnf \
  -keyout /usr/local/etc/ssl/private/self-signed.key \
  -out /usr/local/etc/ssl/certs/self-signed.crt

3. Create a Diffie-Hellman Key Pair

sudo openssl dhparam -out /usr/local/etc/ssl/certs/dhparam.pem 128

4. Configure Nginx

Configure a server in nginx.conf, enable ports 80 and 443. Restart the NGINX server.

server {
    listen       80;
    listen       443 ssl;
    server_name  test.cpming.com;

    ssl_certificate     /usr/local/etc/ssl/certs/self-signed.crt;
    ssl_certificate_key /usr/local/etc/ssl/private/self-signed.key;

    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_dhparam /usr/local/etc/ssl/certs/dhparam.pem;
    ...
}

5. Add the self-signed certificate to the trusted root store

Navigate to http://test.cpming.top. Because the certificate I created isn’t signed by one of the system’s trusted certificate authorities, I am greeted with a big warning sign and the admonition Your connection is not private. To remedy this, I add the self-signed certificate to the trusted root store. Run the following command.

sudo security add-trusted-cert \
  -d -r trustRoot \
  -k /Library/Keychains/System.keychain /usr/local/etc/ssl/certs/self-signed.crt
Updated Jul 18, 2020