Created
July 12, 2015 02:21
-
-
Save MatthewCallis/29e64c576a9ad93455c7 to your computer and use it in GitHub Desktop.
Quick Local Nginx Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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