Skip to content

Instantly share code, notes, and snippets.

@MatthewCallis
Created July 12, 2015 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthewCallis/29e64c576a9ad93455c7 to your computer and use it in GitHub Desktop.
Save MatthewCallis/29e64c576a9ad93455c7 to your computer and use it in GitHub Desktop.
Quick Local Nginx Server
#!/usr/bin/env python
"""\
Usage: %prog [path:.] [port:12345]
"""
import os
import sys
import subprocess
conf_template = """\
error_log stderr;
worker_processes 1;
daemon off;
events {
worker_connections 1024;
}
http {
%(include_mime)s
default_type application/octet-stream;
server {
listen %(port)s;
location / {
root "%(root)s/";
autoindex on;
index index.html index.htm;
}
}
}
"""
def include_mime():
# default location when nginx is installed by home brew in Mac OS
default_location = "/usr/local/etc/nginx/mime.types"
if os.path.exists(default_location):
mime_file = default_location
else:
file_to_locate = "*/nginx/mime.types"
output = subprocess.check_output(["locate", file_to_locate])
files = filter(os.path.exists, output.split("\n"))
if files:
mime_file = files[0]
else:
print >>sys.stderr, "We could not locate %r file." % file_to_locate
mime_file = None
if mime_file:
return "include %s;" % mime_file
else:
return ""
def get_realpath(path):
return os.path.realpath(os.path.join(os.path.abspath(os.curdir), path))
def main():
try:
path = sys.argv[1]
except:
path = "."
root = get_realpath(path)
try:
port = sys.argv[2]
except:
port = "12345"
address = "http://localhost:%s" % port
conf = "/tmp/nginx.conf"
with open(conf, "w") as f:
conf_data = conf_template % dict(root=root, port=port, include_mime=include_mime())
f.write(conf_data)
print >>sys.stderr, "%r serving in %r" % (root, address)
os.execvp("nginx", ["nginx", "-c", conf])
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment