Skip to content

Instantly share code, notes, and snippets.

@apackeer
Forked from martijnvermaat/server.py
Created September 1, 2016 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save apackeer/c88de40b3329ec8055fb6267d91de5f2 to your computer and use it in GitHub Desktop.
Save apackeer/c88de40b3329ec8055fb6267d91de5f2 to your computer and use it in GitHub Desktop.
SimpleHTTPServer with history API fallback
#!/usr/bin/env python
"""
Modification of `python -m SimpleHTTPServer` with a fallback to /index.html
on requests for non-existing files.
This is useful when serving a static single page application using the HTML5
history API.
"""
import os
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
urlparts = urlparse.urlparse(self.path)
request_file_path = urlparts.path.strip('/')
if not os.path.exists(request_file_path):
self.path = 'index.html'
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
host = '0.0.0.0'
try:
port = int(sys.argv[1])
except IndexError:
port = 8000
httpd = BaseHTTPServer.HTTPServer((host, port), Handler)
print 'Serving HTTP on %s port %d ...' % (host, port)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment