【问题标题】:Django-hosts redirect form non-www to wwwDjango-hosts 将非 www 重定向到 www
【发布时间】:2017-04-13 21:38:18
【问题描述】:

该站点生成不同的 URL,它们看起来都像 http://example.com/'somepath'。我想要做的是将用户从http://example.com/'somepath' 重定向到http://www.example.com/'somepath'。正如我发现的那样,可以使用 django-hosts。
正如说明中所说,我在 settings.py 中有以下内容:

ALLOWED_HOSTS = ['www.example.com', 'example.com']

INSTALLED_APPS = [
   ...,
   'django_hosts',
]

MIDDLEWARE = [
   'django_hosts.middleware.HostsRequestMiddleware',
   ...
   'django_hosts.middleware.HostsResponseMiddleware',
]

ROOT_URLCONF = 'appname.urls'
ROOT_HOSTCONF = 'appname.hosts'
DEFAULT_HOST = 'www'
DEFAULT_REDIRECT_URL = "http://www.example.com"
PARENT_HOST = "example.com"

在 hostsconf/urls 中:

from django.conf.urls import url
from .views import wildcard_redirect

urlpatterns = [
    url(r'^(?P<path>.*)', wildcard_redirect),
]

在 hostsconf/views 中:

from django.conf import settings
from django.http import HttpResponseRedirect

DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.example.com")

def wildcard_redirect(request, path=None):
    new_url = DEFAULT_REDIRECT_URL
    if path is not None:
        new_url = DEFAULT_REDIRECT_URL + "/" + path
    return HttpResponseRedirect(new_url)

但看起来它不起作用,因为如果我转到 http://example.com/'somepath' 它会返回“400 Bad Request”并且http://www.example.com/'somepath' 指向正确的目的地。我做错了什么?

【问题讨论】:

    标签: django redirect hosts


    【解决方案1】:

    【讨论】:

    • 你从中得到了什么? 400你可以得到如果没有设置ALLOWED_HOSTS,你确定你做了吗?显示追溯删除 django-hosts,他不想重定向到 www
    • 我设置了 allowed_hosts 和 PREPEND_WWW 返回相同的错误“400 Bad Request”
    • 显示回溯,但不显示错误代码,因为您需要找到错误发生的位置和原因,请查看日志
    猜你喜欢
    • 2018-06-06
    • 1970-01-01
    • 2019-03-09
    • 2021-08-03
    • 2011-11-05
    • 2011-12-01
    • 2013-12-20
    • 2022-03-04
    相关资源
    最近更新 更多