I am attempting to write a web application using the Twisted framework for python. I want the application to work if run as a standalone server (ala twistd), or if Apache reverse proxies to it. E.g.
Apache https://example.com/twisted/ --> https://internal.example.com/
After doing some research, it seemed like I needed to use the vhost.VHostMonsterResource to make this work. So I set up apache with the following directive:
ProxyPass /twisted https://localhost:8090/twisted/https/127.0.0.1:443
Here is my basic SSL server:
from twisted.web import server, resource, static
from twisted.internet import reactor
from twisted.application import service, internet
from twisted.internet.ssl import SSL
from twisted.web import vhost
import sys
import os.path
from textwrap import dedent
PORT = 8090
KEY_PATH = "/home/waldbiec/projects/python/twisted"
PATH = "/home/waldbiec/projects/python/twisted/static_files"
class Index(resource.Resource):
def render_GET(self, request):
html = dedent("""\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Index</h1>
<ul>
<li><a href="/files/">Files</a></li>
</ul>
</body>
</html>
""")
return html
class ServerContextFactory:
def getContext(self):
"""
Create an SSL context.
Similar to twisted's echoserv_ssl example, except the private key
and certificate are in separate files.
"""
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.use_privatekey_file(os.path.join(KEY_PATH, 'serverkey.pem'))
ctx.use_certificate_file(os.path.join(KEY_PATH, 'servercert.pem'))
return ctx
class SSLService(internet.SSLServer):
def __init__(self):
root = resource.Resource()
root.putChild("", Index())
root.putChild("twisted", vhost.VHostMonsterResource())
root.putChild("files", static.File(PATH))
site = server.Site(root)
internet.SSLServer.__init__(self, PORT, site, ServerContextFactory())
application = service.Application("SSLServer")
ssl_service = SSLService()
ssl_service.setServiceParent(application)
It almost works-- but the "files" link on the index page does not behave how I want it to when using apache as a reverse proxy, because it is an absolute link.
My main question is, other than using a relative link, is there some way to compute what the full URL path of the link ought to be in such a way that the link still works in standalone server mode? A second question would be, am I using VHostMonsterResource correctly? I did not find much documentation, and I pieced together my code from examples I found on the web.