Search code examples
pythonhttp-redirectdnstwisted

Twisted redirect subdirectory to another domain


I'm hosting a couple domains static files with Twisted. However, for a subdirectory of the domain, I want to redirect to another domain.

For example: Serve foo.com static files, but foo.com/bar goes to foobar.com/bar

I can't seem to find anything in the Twisted docs for this scenario.

Update

I replied to Glyph that it wasn't working, but I had placed it in the wrong spot. His suggestion was, of course, absolutely correct. I should have provided more initial info. Here it is implemented:

from twisted.application import internet, service
from twisted.web import static, server, vhost, script
from twisted.web.util import Redirect


root = vhost.NameVirtualHost()

# Add a default -- htdocs
root.default=static.File("/home/foo")
root.putChild("myredirect", Redirect("http://othersite.com/myredirect"))

# Add a simple virtual host -- bar.com
root.addHost("bar", static.File("bar"))

# Add a simple virtual host -- foo.com
root.addHost("foo", static.File("/home/foo"))

application = service.Application('web')
sc = service.IServiceCollection(application)
site = server.Site(root)
i = internet.TCPServer(80, site)
i.setServiceParent(sc)

Solution

  • This is pretty straightforward, although it depends on how your site is set up.

    Basically though,

    from twisted.web.util import Redirect
    fooDotComResource.putChild("bar", Redirect("http://foobar.com/bar"))