Search code examples
pythonwebsubdomainflaskwildcard-subdomain

Dynamic Subdomain Handling in a Web App (Flask)


I'm going to be using flask to create a web application, and part of the application will involve a subdomain (for example, user1.appname.org).

I'm not sure how to go about creating these subdomains dynamically in the flask configuration, or how to deploy them to a production server.

What is the best way of doing this?


Solution

  • All Flask's routing constructs support the subdomain keyword argument (this includes support for route variables).

    @app.route("/", subdomain="static")
    def static_index():
        """Flask supports static subdomains
        This is available at static.your-domain.tld"""
        return "static.your-domain.tld"
    
    @app.route("/dynamic", subdomain="<username>")
    def username_index(username):
        """Dynamic subdomains are also supported
        Try going to user1.your-domain.tld/dynamic"""
        return username + ".your-domain.tld"