我如何重定向到www。 Heroku上我的Flask站点的版本? [英] How do I redirect to the www. version of my Flask site on Heroku?

查看:101
本文介绍了我如何重定向到www。 Heroku上我的Flask站点的版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python Flask应用程序在Heroku(Cedar stack)上运行,有两个自定义域(一个没有www子域)。我想将所有传入的请求重定向到www。请求的资源版本(这个问题)。我想我需要一些WSGI中间件,但是我找不到一个好例子。

我该怎么做? 解决方案

创建一个单独的Heroku应用程序将是一个 before_request 函数。

  from urlparse导入urlparse,urlunparse 

@ app.before_request
def redirect_nonwww():
将非www请求重定向到www。
urlparts = urlparse(request.url)
if urlparts.netloc =='example.com':
urlparts_list = list(urlparts)$ b $ urlparts_list [1] ='www.example.com'
return redirect(urlunparse(urlparts_list),code = 301)

这将重定向所有非www使用HTTP 301永久移动响应向www请求。


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

这篇关于我如何重定向到www。 Heroku上我的Flask站点的版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆