Nginx – Single server, nginx as a reverse proxy, multiple domains/websites

domainnginxPROXYreverse-proxy

I have this nginx config for my website on https where nginx is used as a reverse proxy server:

  server {
      listen 80 default_server;
      listen [::]:80 default_server;
      server_name my_domain123.com www.my_domain123.com;
      return 301 https://$server_name$request_uri;
  }

  server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name localhost www.my_domain123.com;
    return 301 https://my_domain123.com$request_uri;
  }

  server {
      listen 443 ssl default_server;
      listen [::]:443 ssl default_server;
      server_name my_domain123.com;

    location / {
      proxy_redirect      http://localhost:4000 https://my_domain123.com;
      # ...........................

    }

How should I adjust it so that I can host multiple websites with different domain names on the same server?
Where in the config exactly should I insert the new configuration for that new website?

Or should I create one more site-available/enabled for it also? Yet, the question remains: how would I combine 2 or more configurations — same server, multiple domains — properly?

Best Answer

Normally you create a new config file /etc/nginx/sites-available/newserver.conf for the new server and link it from /etc/nginx/sites-enabled.
To use nginx as reverse proxy, you configure SSL in nginx (ssl_certificate, ...) and in the location section you use proxy_pass to the non SSL server at localhost. proxy_redirect is also needed, but that only modifies the Location header in case your non SSL local server sends one.
You find an example in the following article.

Multiple http servers on localhost using different ports

server {
    server_name mydomain-01.com;

    location / {
      proxy_redirect http://localhost:8001 https://mydomain-01.com;
      ...
    }
}
server {
    server_name mydomain-02.com;

    location / {
      proxy_redirect http://localhost:8002 https://mydomain-02.com;
      ...
    }
}

Single http server on localhost using hostname based sites

server {
    server_name mydomain-01.com;

    location / {
      proxy_redirect http://s1.localdomain:4000 https://mydomain-01.com;
      ...
    }
}
server {
    server_name mydomain-02.com;

    location / {
      proxy_redirect http://s2.localdomain:4000 https://mydomain-02.com;
      ...
    }
}