nginxsslport

How to use one ssl certificate for different ports on nginx


I am trying to configure my nginx to support ssl for different ports. If i do it for port 3000 where my react app is running then only that becomes https which means it doesnot allow port 5000 requests to pass through as 5000 is still http. I am using aws ec2. Below is my code for nginx default file.

server {
    listen 80;
    listen [::]:80;
    server_name merkle.org www.merkle.org;
    return 301 https://merkle.org$request_uri;
}

server {
    listen 443 ssl;
    server_name merkle.org web.merkle.org;
    # Certificate
    ssl_certificate /etc/nginx/ssl/merkle_org.crt;
    
    # Private Key
    ssl_certificate_key /etc/nginx/ssl/private.key;
    location / {
        # My react 
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    
    location /5000 {
        # This is my nodejs API 
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Solution

  • I am trying to configure my nginx to support ssl for different ports

    I assume you actually want to support SSL on a single port (the default, 443) for different backend ports, correct?

    In this case you first need to think of a way to clearly distinguish incoming requests. There are (at least) two popular approaches here:

    1. Have a separate (sub)domain for the API, e.g. api.example.com
    2. Route by URL path, e.g. /api

    Note that for the first approach you'd need a separate certificate (or a single certificate that includes this name).