Skip to content

Instantly share code, notes, and snippets.

@mkscrg
Created December 23, 2013 03:21
Show Gist options
  • Save mkscrg/8091269 to your computer and use it in GitHub Desktop.
Save mkscrg/8091269 to your computer and use it in GitHub Desktop.
Serve a directory on a port with Nginx, with access logs to STDOUT and error logs to STDERR.
#!/usr/bin/env bash
set -e
usage() {
echo "usage: serve PORT [DIR]"
exit 1
}
conf_template='
worker_processes 1;
daemon off;
events {
worker_connections 1024;
}
error_log "$$ERR_LOG$$";
http {
include /usr/local/etc/nginx/mime.types;
default_type text/plain;
access_log "$$ACC_LOG$$";
server {
listen $$PORT$$;
location / {
root "$$ROOT$$";
autoindex on;
}
}
}
'
if [[ -z "$1" ]]; then
usage
else
port="$1"
fi
if [[ -z "$2" ]]; then
root="$(cd ./ && pwd)"
else
root="$(cd "$2" && pwd)"
fi
tmpdir="$(mktemp -dt serve)"
conf="${tmpdir}/conf"
err_log="${tmpdir}/err.log"
acc_log="${tmpdir}/acc.log"
touch "$acc_log" "$err_log"
echo -n "$conf_template" | sed \
-e "s@\\\$\\\$ERR_LOG\\\$\\\$@${err_log}@" \
-e "s@\\\$\\\$ACC_LOG\\\$\\\$@${acc_log}@" \
-e "s@\\\$\\\$PORT\\\$\\\$@${port}@" \
-e "s@\\\$\\\$ROOT\\\$\\\$@${root}@" > $conf
trap 'kill $(jobs -p)' EXIT
tail -f "$err_log" 1>&2 &
tail -f "$acc_log" &
nginx -p "$root" -c "$conf"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment