Guest User

Simple Python HTTP with custom 404 support

a guest
Aug 20th, 2025
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. #!/bin/python3
  2.  
  3. import os
  4. from http.server import HTTPServer, SimpleHTTPRequestHandler
  5.  
  6. class Custom404Handler(SimpleHTTPRequestHandler):
  7.     def send_error(self, code, message=None, explain=None):
  8.         if code == 404:
  9.             # Serve custom 404.html if it exists
  10.             path = os.path.join(self.directory, "404.html")
  11.             if os.path.exists(path):
  12.                 self.send_response(404)
  13.                 self.send_header("Content-type", "text/html")
  14.                 self.end_headers()
  15.                 with open(path, "rb") as f:
  16.                     self.wfile.write(f.read())
  17.                 return
  18.         super().send_error(code, message, explain)
  19.  
  20.     def do_GET(self):
  21.         # Try to serve file, otherwise call send_error(404)
  22.         if self.path == "/":
  23.             return super().do_GET()
  24.         else:
  25.             # Remove query string, fragments
  26.             file_path = self.translate_path(self.path.split('?',1)[0].split('#',1)[0])
  27.             if os.path.exists(file_path) and not os.path.isdir(file_path):
  28.                 return super().do_GET()
  29.             else:
  30.                 self.send_error(404)
  31.  
  32. if __name__ == '__main__':
  33.     import sys
  34.     import os
  35.  
  36.     # Set working directory
  37.     directory = os.getcwd()
  38.     if len(sys.argv) > 1:
  39.         directory = sys.argv[1]
  40.     handler = Custom404Handler
  41.     handler.directory = directory
  42.  
  43.     server = HTTPServer(("0.0.0.0", 8080), handler)
  44.     print(f"Serving on http://localhost:8080 from {directory}")
  45.     server.serve_forever()
  46.  
  47.  
Advertisement
Add Comment
Please, Sign In to add comment