Search code examples
pythonbottle

Redirect all non-www requests to www in bottle-py


I want to issue a 301 redirect for all requests with a host different than the one identified as canonical.

Something like the following, without replicating it in every route:

CANONICAL_HOST = 'www.example.com'
@app.route('/')
def home():    
    if request.urlparts.netloc != CANONICAL_HOST:
        redirect_url = request.urlparts._replace(netloc=CANONICAL_HOST).geturl()
        return redirect(redirect_url, 301)
    ...

Solution

  • I finally found this 2013 SO's answer and I adapted it to my needs:

    from bottle import Bottle, request, redirect
    
    class RedirectToCanonicalURLPlugin():
        api = 2 
        CANONICAL_HOST = os.environ.get('CANONICAL_HOST')
        def apply(self, callback, route):
            def wrapper(*args, **kwargs):
                return (callback(*args, **kwargs)
                    if request.urlparts.netloc == self.CANONICAL_HOST 
                    else self._redirect())
            return wrapper  
                  
        def _redirect(self):
            return redirect(request.urlparts
                ._replace(netloc=self.CANONICAL_HOST).geturl(), 301)
    
    app = Bottle()
    app.install(RedirectToCanonicalURLPlugin())