I've got a Python Flask app running on Heroku (Cedar stack) with two custom domains (one with and one without the www subdomain). I'd like to redirect all incoming requests to the www. version of the resource requested (the inverse of this question). I think I need some WSGI middleware for this but I can't find a good example.
How do I do this?
An easier solution than to create a separate Heroku app would be a before_request
function.
from urllib.parse import urlparse, urlunparse
@app.before_request
def redirect_nonwww():
"""Redirect non-www requests to www."""
urlparts = urlparse(request.url)
if urlparts.netloc == 'example.com':
urlparts_list = list(urlparts)
urlparts_list[1] = 'www.example.com'
return redirect(urlunparse(urlparts_list), code=301)
This will redirect all non-www requests to www using a "HTTP 301 Moved Permanently" response.
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