在 bottle-py 中将所有非 www 请求重定向到 www

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

我想为所有请求发出一个 301 重定向,请求的主机不同于被识别为 canonical.

类似于以下内容,但没有在每条路线中复制它:

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)
    ...

我终于找到了 this 2013 SO's answer 并根据需要对其进行了调整:

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())