Skip to content

Instantly share code, notes, and snippets.

@outiy5
Last active May 17, 2022 09:45
Show Gist options
  • Save outiy5/57cb1a824a0c6d2dd527fb7f3e6be121 to your computer and use it in GitHub Desktop.
Save outiy5/57cb1a824a0c6d2dd527fb7f3e6be121 to your computer and use it in GitHub Desktop.
twisted reverse proxy: one file reverse proxy. No nginx and stunnel.

HTTPS to HTTP

reverse_proxy.py:

import sys
from twisted.internet import ssl, protocol, task, defer
from twisted.python import log
from twisted.internet import reactor
from twisted.web import proxy, server

log.startLogging(sys.stdout)
from OpenSSL import crypto
privkey=open('privkey.pem', 'rt').read() # copy letsencrypt cerficate here
certif=open('cert.pem', 'rt').read()
chain=open('chain.pem', 'rt').read()
privkeypyssl=crypto.load_privatekey(crypto.FILETYPE_PEM,privkey)
certifpyssl=crypto.load_certificate(crypto.FILETYPE_PEM,certif)
chainpyssl=[crypto.load_certificate(crypto.FILETYPE_PEM,chain)]
contextFactory=ssl.CertificateOptions(privateKey=privkeypyssl,certificate=certifpyssl,extraCertChain=chainpyssl)
site = server.Site(proxy.ReverseProxyResource("127.0.0.1", 8000, b""))
reactor.listenSSL(443, site, contextFactory)
reactor.run()

HTTP to HTTP

from twisted.internet import reactor
from twisted.web import proxy, server

site = server.Site(proxy.ReverseProxyResource("example.com", 80, b""))
reactor.listenTCP(8080, site)
reactor.run()

Dependencies

sudo pip install service_identity twisted
sudo python reverse_proxy.py

Reference

https://stackoverflow.com/questions/38766244/pyopenssl-twisted-with-lets-encrypt-servers-certificate-chain-is-incomplete twisted letsencrypt https://twistedmatrix.com/documents/current/web/examples/ reverse proxy https://twistedmatrix.com/documents/current/core/howto/ssl.html https https://twistedmatrix.com/documents/13.1.0/core/examples/index.html examples

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment