[英]Django-hosts redirect form non-www to www
The site generates different URLs that all look like http://example.com/ 'somepath'. 该网站会生成不同的URL,它们看起来都像http://example.com/'somepath '。 What I want to do is to redirect users from http://example.com/ 'somepath' to http://www.example.com/ 'somepath'.
我要做的是将用户从http://example.com/'somepath '重定向到http://www.example.com/'somepath '。 As I found out it's possible to do with django-hosts.
正如我发现的那样,可以使用django-hosts。
As it's said in instructions I have the following in settings.py: 正如说明中所述,我在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"
In hostsconf/urls: 在hostsconf / url中:
from django.conf.urls import url
from .views import wildcard_redirect
urlpatterns = [
url(r'^(?P<path>.*)', wildcard_redirect),
]
In hostsconf/views: 在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)
But looks like it doesn't work because if I go to http://example.com/ 'somepath' it returns "400 Bad Request" and http://www.example.com/ 'somepath' points to the correct destination. 但是看起来不起作用,因为如果我转到http://example.com/'somepath ',它将返回“ 400 Bad Request”,而http://www.example.com/“somepath ”指向正确的目的地。 What am I doing wrong?
我究竟做错了什么?
Try the default settings PREPEND_WWW 尝试默认设置PREPEND_WWW
https://docs.djangoproject.com/en/1.10/ref/settings/#prepend-www https://docs.djangoproject.com/zh/1.10/ref/settings/#prepend-www
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.