Torc
Torc

Reputation: 1322

NGINX Reverse Proxy Configuration Structure

Is there a "proper" structure for the directives of an NGINX Reverse Proxy? I have seen 2 main differences when looking for examples of an NGINX reverse proxy.

  1. http directive is used to house all server directives. Servers with data are listed in a pool within the upstream directive.
  2. server directives are listed directly within the main directive.

Is there any reason for this or is this just a syntactical sugar difference?

Example of #1 within ./nginx.conf file:

upstream docker-registry {
  server registry:5000;
}

http {
  server {
    listen 80;
    listen [::]:80;

    return 301 https://$host#request_uri;
  }

  server {
    listen 443 default_server;
    ssl on;
    ssl_certificate external/cert.pem;
    ssl_certificate_key external/key.pem;
    
    # set HSTS-Header because we only allow https traffic
    add_header Strict-Transport-Security "max-age=31536000;";

    proxy_set_header Host       $http_host;   # required for Docker client sake
    proxy_set_header X-Real-IP  $remote_addr; # pass on real client IP

    location / {
      auth_basic "Restricted"
      auth_basic_user_file    external/docker-registry.htpasswd;
      
      proxy_pass http://docker-registry; # the docker container is the domain name
    }
    
    location /v1/_ping {
      auth_basic off;
      proxy_pass http://docker-registry; 
    }
  }
}

Example of #2 within ./nginx.conf file:

server {
  listen 80;
  listen [::]:80;
  
  return 301 https://$host#request_uri;
}

server {
  listen 443 ssl;
  listen [::]:443 ssl;
  
  error_log  /var/log/nginx/error.log  info;
  access_log /var/log/nginx/access.log main;

  ssl_certificate     /etc/ssl/private/{SSL_CERT_FILENAME};
  ssl_certificate_key /etc/ssl/private/{SSL_CERT_KEY_FILENAME};

  location / {
    proxy_pass http://app1
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $remote_addr; # could also be `$proxy_add_x_forwarded_for`
    proxy_set_header X-Forwarded-Port $server_port;
    proxy_set_header X-Request-Start $msec;
  }
}

Upvotes: 0

Views: 182

Answers (1)

Tch
Tch

Reputation: 1055

I dont quite understand your question, but it seems to me that the second example is missing the http {}, I dont think that nginx will start without it. unless your example2 file is included somehow in the nginx.conf that has the http{}

Upvotes: 1

Related Questions