Search code examples
pythonflaskheroku

Catching a subdomain in Flask but with custom domain name hosted on Heroku


Basically, I am trying to catch subdomains for my website (such as www.example.com or help.example.com). I followed the instructions of solutions such as this and this. For some reason, it identifies as:

This site can’t be reached. Check if there is a typo in www.example.com.

In general, this is what most answers said:

  1. Use the subdomain="<subdomain>" argument in the decorator declaration in Flask.
  2. Declare the server name i.e. app.config['SERVER_NAME'] = "example.com:33507" N.B. -> I wrote 33507 as the port Heroku uses.

But even after performing all of these steps, it still didn't work.


Solution

  • The following Flask example code will respond to a subdomain called "api" and serve up the decorated api_index route. Note for this to work I didn't specify the port for the server name config.

    from flask import Flask, jsonify
    
    app = Flask(__name__, subdomain_matching=True)
    app.config['SERVER_NAME'] = "example.com"
    
    
    @app.route("/")
    def index():
        return "Welcome"
    
    
    @app.route("/", subdomain="api")
    def api_index():
        return jsonify({"message": "Welcome"})
    
    

    In Heroku, you will need to add a custom domain for each subdomain you require. It is possible to use a wildcard but you will have to provide your own certificate.

    I've just tried this successfully on Heroku with the following Procfile

    web: gunicorn app:app --log-file=-
    

    And the following dependencies using Pipenv

    [[source]]
    url = "https://pypi.org/simple"
    verify_ssl = true
    name = "pypi"
    
    [packages]
    flask = "*"
    gunicorn = "*"
    
    [dev-packages]
    
    [requires]
    python_version = "3.11"
    

    If this doesn't help, you can edit your message to include your code?