Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@faelp22
Last active March 22, 2023 13:55
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save faelp22/36c9bfca83780d3da73f07d66a7ec2ae to your computer and use it in GitHub Desktop.
Save faelp22/36c9bfca83780d3da73f07d66a7ec2ae to your computer and use it in GitHub Desktop.
Python3 SimpleHTTPServer for Static Serving (VueJS/ React / Angular / Ember) in HTML5 mode (a la mod_rewrite)
#!/usr/bin/env python
'''
Based on https://gist.github.com/chrisbolin/2e90bc492270802d00a6
'''
import os
from http.server import HTTPServer, SimpleHTTPRequestHandler
from urllib.parse import urlparse
PORT = 8000
INDEXFILE = 'index.html'
class FakeModReWriteHandle(SimpleHTTPRequestHandler):
def do_GET(self):
# Parse query data to find out what was requested
parsedParams = urlparse(self.path)
# See if the file requested exists
if os.access('.' + os.sep + parsedParams.path, os.R_OK):
# File exists, serve it up
SimpleHTTPRequestHandler.do_GET(self)
# send index.html, but don't redirect
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
with open(INDEXFILE, 'rb') as fin:
self.copyfile(fin, self.wfile)
def server():
httpd = HTTPServer(("0.0.0.0", PORT), FakeModReWriteHandle)
print("HTTP Server run at port", PORT)
httpd.serve_forever()
def main():
try:
server()
except OSError:
print("\nError check if the PORT:[%s] address is already in use!\n" %PORT)
except KeyboardInterrupt:
print("\nBye Server Down!\n")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment