How to generate a self-signed certificate with OpenSSL

A self-signed certificate lets you serve HTTPS for local development or internal services without going through a certificate authority. Here is how to create one with openssl.

Mark van Eijk 1 minute read Security
  1. When to use a self-signed certificate
  2. Generate a certificate and key in one command
  3. Include Subject Alternative Names
  4. Use it in nginx
  5. Trust it locally

When to use a self-signed certificate

A self-signed certificate is signed by its own key rather than a trusted CA. That's perfect for local development, testing, and internal services where you control the clients. It is not suitable for a public website — browsers don't trust it and will show your connection is not private to every visitor.

Generate a certificate and key in one command

This creates a private key and a self-signed certificate valid for one year:

openssl req -x509 -newkey rsa:2048 -nodes \
  -keyout key.pem -out cert.pem -days 365 \
  -subj "/CN=localhost"
  • cert.pem — the certificate.
  • key.pem — the private key.

-nodes keeps the key unencrypted so a web server can read it without a passphrase.

Include Subject Alternative Names

Modern browsers ignore the Common Name and require the hostname under SAN, or they'll reject the certificate outright. Add it explicitly:

openssl req -x509 -newkey rsa:2048 -nodes \
  -keyout key.pem -out cert.pem -days 365 \
  -subj "/CN=localhost" \
  -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"

Use it in nginx

Point your server block at the two files:

ssl_certificate     /etc/ssl/cert.pem;
ssl_certificate_key /etc/ssl/key.pem;

Trust it locally

Your browser will still warn you because nothing vouches for the certificate. For a smoother local setup you can add cert.pem to your operating system or browser trust store, or use a tool like mkcert that installs a local CA for you.

When you're ready to serve real traffic, request a certificate from a CA with a CSR, or use a free automated certificate by installing Certbot. Either way, make sure you serve the full certificate chain.