nginx

Server Blocks

  • Create server blocks in /etc/nginx/sites-available. For example:

    # /etc/nginx/sites-available/kb.timothyandrew.net
    
    # Serve a website from `/var/www/kb.timothyandrew.net/html` at `kb.timothyandrew.net`
    
    server {
      listen 80;
      listen [::]:80;
    
      root /var/www/kb.timothyandrew.net/html;
      index index.html;
    
      server_name kb.timothyandrew.net;
    
      location / {
        try_files $uri $uri/ =404;
      }
    }
    
  • Once these server blocks are created, enable them by symlinking to sites-enabled:

    $ ln -s /etc/nginx/sites-available/kb.timothyandrew.net /etc/nginx/sites-enabled/
    
  • Validate config and restart nginx:

    $ nginx -t && systemctl restart nginx
    

njs

  • nginx allows scripting via (a variant of, it looks like) Javascript. To set this up, first install the package:
    $ apt-get install nginx-module-njs
    
  • And load it in /etc/nginx/nginx.conf:
    load_module modules/ngx*http_js*module.so;
    load_module modules/ngx_stream_js_module.so;
    
  • Write a new njs script (this example always redirects to today’s journal entry):
    // /etc/nginx/daily.js
    
    function daily(r) {
      var date = new Date();
      var iso = date.toISOString().split("T")[0];
      r.return(302, `https://journal.example.com/journal/${iso}.html`);
    }
    
  • Include and use the script in a server block file (in sites-available):
    # Redirect `daily.example.com` to _today's_ journal entry on `journal.example.com`
    
    js_include daily.js;
    
    server {
      listen 80;
      listen [::]:80;
      server_name daily.example.com;
      location / {
        js_content daily;
      }
    }
    
  • Finally, enable the server block and restart nginx.
  • This is very useful to help set up dynamic redirects to a statically-generated website without adding a new dynamic layer in between.
Edit