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)
Creating A Flask Application And Route This code imports the Flask library, creates an app and defines the homepage for a simple web server. from flask import Flask app = Flask(__name__) @app. route('/') def home(): return 'Hello World! '
flask route paramsA parameter can be a string (text) like this: /product/cookie . So you can pass parameters to your Flask route, can you pass numbers? The example here creates the route /sale/<transaction_id> , where transaction_id is a number.
For Flask, you define the routes using decorator functions. When you navigate to a URL that matches the decorator, it will execute the decorated function. In this example, if I navigate to "/" on my webserver, the hello function will execute.
In some cases you can reuse a Flask route function for multiple URLs. Or you want the same page/response available via multiple URLs. In that case you can add a second route to the function by stacking a second route decorator to the function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With