nginxnginx-upstreams

Setup NGINX to serve several sites on the same host


Trying to figure out how I could setup NGINX to serve several sites on the same host, with subfolder unified config. trying to have mydomain.com/blue and mydomain.com/red serving 2 different NodeJS websites.

So far I did this : 2 configs, which are in sites-availables with symlink in sites-enables

they both have the same config, unless for the upstream, where I change the name and the port.

# path: /etc/nginx/sites-available/blue.conf


# Server
upstream blue {
    server 127.0.0.1:1337;
}

server {
    # Listen HTTP
    listen 80;
    server_name mydomain.com;

    # Redirect HTTP to HTTPS
    return 301 https://$host$request_uri;
}

server {
    # Listen HTTPS
    listen 443 ssl http2;
    server_name mydomain.com;

    # SSL config
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    # Static Root
    location / {
        root /var/www;
    }

    # API and Admin
    location /blue/ {
        rewrite ^/blue/?(.*)$ /$1 break;
        proxy_pass http://blue/;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_pass_request_headers on;
    }
}

For the other conf, it's the same with those differences :

# Server
upstream red {
    server 127.0.0.1:2160;
}

    # API and Admin
    location /red/ {
      rewrite ^/red/?(.*)$ /$1 break;
      proxy_pass http://red/;
      ...
    }

It is currently not working, after setting up second site and relaoding nginx, I got a 403 forbidden or the first one, the second one works tho

Any clue ?


Solution

  • Finally fixed the issue.

    The problem is that I had 2 conf, both with the same domain, each of them had their own server block.

    Had to put all subfolders location directives in an unique server block, instead of one per site.