该网站会生成不同的网址,这些网址看起来都像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'指向正确的目的地。我做错了什么?
答案 0 :(得分:1)
尝试默认设置 PREPEND_WWW
https://docs.djangoproject.com/en/1.10/ref/settings/#prepend-www