Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dunderrrrrr/78b89a036d0ad805dd7129d3803aab55 to your computer and use it in GitHub Desktop.
Save dunderrrrrr/78b89a036d0ad805dd7129d3803aab55 to your computer and use it in GitHub Desktop.

NGINX Self-Signed Cert with 301 redirect (and reverse proxy)

First, generate your cert. Make sure your FQDN is matching your url. This is the easy way, if production you should also get yourself a DH-key and make some other changes to your SSL configuration. More reading here.

$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt

Once you're done filling all cert-information, add certs and the 302 redirect (from http to https) to the nginx configuration. Here's a sample.

server {
    server_name sub.domain.tld;
    location / {
        proxy_pass http://127.0.0.1:8080;
    }
    listen 443 ssl;
    ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
    ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key; 
}

# 301 redirect from http to https
server {
    if ($host = sub.domain.tld) {
        return 301 https://$host$request_uri;
    } 

    listen 80;
    server_name sub.domain.tld;
    return 404; 

}

Test nginx config with sudo nginx -t and reload if it checks out good, sudo systemctl reload nginx.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment