import http.server import os import socketserver from pathlib import Path class CleanURLHandler(http.server.SimpleHTTPRequestHandler): def translate_path(self, path): # Remove query string or fragment if '?' in path: path = path.split('?')[0] if '#' in path: path = path.split('#')[0] # Serve index.html for directory paths if path.endswith('/'): path = path + 'index.html' # If no extension and .html version exists, serve that if not os.path.splitext(path)[1]: html_path = Path(self.directory) / (path.lstrip('/') + '.html') if html_path.is_file(): return str(html_path) return super().translate_path(path) def end_headers(self): self.send_header('Access-Control-Allow-Origin', '*') super().end_headers() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--directory', default='public') parser.add_argument('--port', type=int, default=9120) parser.add_argument('--bind', default='0.0.0.0') args = parser.parse_args() directory = Path(args.directory).resolve() CleanURLHandler.directory = str(directory) os.chdir(directory) with socketserver.TCPServer((args.bind, args.port), CleanURLHandler) as httpd: print(f"Serving {directory} at http://{args.bind}:{args.port}") httpd.serve_forever()