Running Nginx for local development

posted on 2013-12-29

Having a local webserver can come in very handy during development. These days it's no longer really a thing, as most programming languages are efficient enough to simply embed the HTTP server. Anything that is client-side only can be done with a simple Python command. However, if you want a powerful proxy or do some other Nginx testing, it can come in handy to have a local Nginx running under your own control. One other requirement is, I want to share this configuration via git, meaning that it should work without absolute paths.

To get this running, I created scripts to start and stop the server and finally the base configuration template. This example was tested with nginx version 1.4.4.

First the start script. Note that we have to give the full path to the configuration. Because we will be placing the configuration next to the start script and sharing this in git:

#!/bin/bash
set -x
RELD="`dirname "$0"`"
ABSD="`realpath "$RELD"`"

if [ ! -e "$ABSD"/nginx.conf ]; then
    sed "s,ROOT,$ABSD," < nginx.conf.template > nginx.conf
fi
exec nginx -c "$ABSD"/nginx.conf

The ABSD (absolute directory) variable will contain the full path to the directory containing start.sh. Because we need absolute paths in the nginx.conf, we replace ROOT in the nginx.conf.template file with the absolute directory of start.sh.

Next to the start.sh file we create nginx.conf.template containing:

worker_processes  1;

events {
    worker_connections  1024;
}

pid ROOT/nginx_user.pid;

http {
    access_log  ROOT/nginx_access.log;
    error_log   ROOT/nginx_error.log info;

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    
    server {
        listen       8080;
        server_name  localhost;

        charset utf-8;

        location / {
            root   ROOT;
            autoindex on;
            index  index.html index.htm;
        }
    }
}

The above template contains four mentions of ROOT, which the sed command will replace when start.sh is run for the first time.

Finally we need a stop.sh script:

#!/bin/bash
cd "`dirname "$0"`"
PIDFILE=nginx_user.pid
if [ -e "$PIDFILE" ]; then
    set -x
    kill `cat "$PIDFILE"`
    rm -f "$PIDFILE"
else
    echo "No pidfile found at $PIDFILE"
fi

This try to kill the PID mentioned in the nginx_user.pid file. Now when Nginx is killed, the PID file should be automatically removed. However, because we also use it as a trigger in stop.sh, I decided to add rm -f "$PIDFILE" in there for when Nginx crashed or something else horrible happened.

If you want, you can download the three files in a tar.gz file here. Happy hacking!