Back

Contents

Set up an nginx reverse proxy

Install nginx

$ sudo apt-get install nginx

Adding a HTTP(S) server block redirect

  1. Create logs directory.

     $ sudo mkdir -p /var/logs/nginx
  2. Create configuration file.

     $ sudo vi new_site

    e.g. to listen to a port listen_port and redirect to a host target_host:target_port, use:

     server {
         listen <listen_port>;
         allow <allowed_network_address>; 
         deny all;
         location / {
             proxy_pass <target_host>:<target_port>/;
             proxy_redirect off;
             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;
         }
         access_log /var/logs/nginx/nginx-access.log;
         error_log /var/logs/nginx/nginx-error.log;
     }

    where allowed_network_address is a whitelisted address.

  3. Copy the configuration file as the sites-available default (this will overwrite existing sites!)

     $ sudo cp new_site /etc/nginx/sites-available/default

    or, alternatively, copy as a new file into the sites-available directory and symlink from the sites-enabled directory (only sites in sites-enabled are included by nginx.conf, where sites-available/default is symlinked as standard).

  4. Check the new configuration file and reload nginx.

     $ sudo nginx -t
     $ sudo systemctl reload nginx

Adding a custom TCP stream

By default, nginx only proxies HTTP/HTTPS. Custom modules can be used to proxy custom TCP streams.

  1. Install additional nginx module.

     $ sudo apt-get install libnginx-mod-stream 
     $ sudo systemctl reload nginx
  2. Create folders for streams in etc/nginx copying sites-* nomenclature.

     /etc/nginx$ sudo mkdir streams-enabled
     /etc/nginx$ sudo mkdir streams-available
  3. Create file for new stream in streams-available, e.g.

     /etc/nginx$ sudo vi streams-available/new-stream

    and add stream rules:

     server {
       listen <listen_port>;
       proxy_pass <target_host>:<target_port>;
     }
  4. Link new stream configuration file from streams-enabled.

     /etc/nginx$ ln -s sites-available/new-stream sites-enabled/new-stream
  5. Edit nginx.conf to add the logic for stream inclusion.

     /etc/nginx$ vi nginx.conf

    Adding:

     stream {
         access_log off;
         error_log /var/log/nginx/error.stream.log;
    
         include /etc/nginx/streams-enabled/*;
     }

    after the http stanza.


Top