Blog-Core framework

Fork me on GitHub

Running with Nginx

Nginx is a web server that is frequently used in front of the actual web applications. It provides the following features:

  • Multiple domains on a single IP address.
  • SSL termination.
  • Static file serving.
  • Canonical hostnames.
  • Sanitation.
  • etc.

And in the context of Blog-Core, it also provides custom 404 pages which is otherwise not possible with the current SWI HTTP implementation (at least in 7.3.13 and older versions).

The example configuration assumes some familiarity with basic Nginx concepts. Most options are explained in the configuration comments. This configuration does not include SSL termination. The SSL configuration depends on the certificate provider and other guides have to be consulted for that.

server {

    index index.html index.htm;
    
    # Host name served by this block.
    # This does not hande www.example.com which
    # should have its own block.
    
    server_name example.com;
    
    # Sets static file directory location.
    # This assumes that the site is installed
    # into /sites/example.com
    
    root /sites/example.com/public;
    
    # These following directives implement
    # custom 404 pages. The site must reply
    # a valid page on the /404 path.
    
    error_page 404 /404;
    proxy_intercept_errors on;

    # Removes the /t-<timestamp> cache buster prefix.

    location ~ ^/t-\d+/(.*)$ {
        access_log off;
        rewrite ^/t-\d+/(.*)$ /$1 last;
    }
    
    # Tries to serve static files directly.
    # Adds caching header. Disables access log.
    
    location ~* \.(ico|css|js|gif|jpe?g|png)$ {
    
        access_log off;
        expires max;
    
        try_files $uri @upstream;
    }
    
    # Otherwise tries to serve through the reverse proxy.
    
    location / {
    
        try_files $uri @upstream;
    }

    # Defines a pseudo location for serving
    # non-static files from the site through
    # a reverse proxy.

    location @upstream {

        # Disables HEAD requests to the site.
        # SWI-Prolog currently does not support
        # head requests very well.

        if ($request_method = HEAD) {
    
            return 405;
        }
    
        # The site must be running on the same
        # machine on the port 8080.
    
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Nginx-Proxy true;
        proxy_redirect off;
    }
}

server {

    # This server block handles www-prefixed hostname
    # and redirects to the www-less host.

    server_name www.example.com;
    return 301 http://example.com$request_uri;
}