6

My web app assigns a subdomain to users and optionally allows them to use a custom domain. This works except when the user visits their custom domain for a route without including a trailing slash.

GET requests to this url works as expected: http://user.example.com:5000/book/12345/

GET requests to this url works as expected: http://custom.com:5000/book/12345/

GET requests to this url attempt to redirect, but fail: http://custom.com:5000/book/12345

Flask ends up redirecting the browser to this url which, of course, doesn't work: http://<invalid>.example.com:5000/book/12345/

Is there a different way that I should handle custom domains? Here's a complete minimal example to reproduce this. I have set custom.com, example.com. and user.example.com to point to 127.0.0.1 in my /etc/hosts file in my development environment so that Flask receives the request.

from flask import Flask

app = Flask(__name__)

server = app.config['SERVER_NAME'] = 'example.com:5000'

@app.route('/', subdomain="<subdomain>")
@app.route('/')
def index(subdomain=None):

    return ("index")

@app.route('/book/<book_id>/', subdomain="<subdomain>")
@app.route('/book/<book_id>/')
def posts(post_id, subdomain=None):

    return (book_id)


if __name__ == '__main__':
    app.run(host='example.com', debug=True)
0

1 Answer 1

2

I'm not sure that's possible. host matching and subdomain matching are mutually exclusive (look at host matching parameter).

I'd love to be wrong though.

One way around this issue that I can think of is to use something in front of Flask (say nginx) that points custom.com to custom.com._custom.example.com or something like that. In your code you could create a custom url_for function that would recognize this as a custom domain. I would ask on the Flask mailing list as they would be able to give you a solid answer.

Sign up to request clarification or add additional context in comments.

2 Comments

That's a good suggestion. I just did emailed the Flask list. Thanks.
Please let us know the answer you get.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.