我最近使用指定的确切说明在我的网站上安装了Django的default redirects app:
当我的网址干净时,该应用效果很好,如下所示:
重定向设置:/ page /到/ redirect /
当我访问https://www.example.com/page/ =>重定向到https://www.example.com/redirect/
但是,当URL参数附加到我的URL末尾时,重定向不起作用,如下所示:
重定向设置:/ page /到/ redirect /
当我访问https://www.example.com/page/?url_parameter=true =>抛出Http404错误(找不到页面)
理想情况下,我希望我的重定向能够保留URL参数,如下所示:
重定向设置:/ page /到/ redirect /
当我访问https://www.example.com/page/?url_parameter=true =>重定向到https://www.example.com/redirect/?url_parameter=true
有没有办法强制重定向应用保留上述的URL参数?
答案 0 :(得分:4)
1.您需要按子类django.contrib.redirects.middleware.RedirectFallbackMiddleware
编写自己的CustomRedirectFallbackMiddleware并覆盖process_response
的{{1}}方法。
custom_redirect_middleware.py
django.contrib.redirects.middleware.RedirectFallbackMiddleware
在此import urlparse
from django import http
from django.conf import settings
from django.contrib.redirects.models import Redirect
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.redirects.middleware import RedirectFallbackMiddleware
class CustomRedirectFallbackMiddleware(RedirectFallbackMiddleware):
response_gone_class = http.HttpResponseGone
response_redirect_class = http.HttpResponsePermanentRedirect
def process_response(self, request, response):
if response.status_code != 404:
return response
full_path = request.get_full_path()
"""
Seperate query parameters and url if full absolute path contains
query parameters using python urlparse library
"""
parsed_url = None
if "?" in full_path:
parsed_url = urlparse.urlparse(full_path)
# Now full path contains no query parameters
full_path = parsed_url.path
current_site = get_current_site(request)
r = None
try:
r = Redirect.objects.get(site=current_site, old_path=full_path)
except Redirect.DoesNotExist:
pass
if r is None and settings.APPEND_SLASH and not request.path.endswith('/'):
try:
if parsed_url is not None:
r = Redirect.objects.get(
site=current_site,
old_path= full_path + '/',
)
else:
r = Redirect.objects.get(
site=current_site,
old_path=request.get_full_path(force_append_slash=True),
)
except Redirect.DoesNotExist:
pass
if r is not None:
if r.new_path == '':
return self.response_gone_class()
#Adding back the query parameters to redirecting path
if parsed_url is not None:
new_path_with_query_params = r.new_path + "?" + parsed_url.query
return self.response_redirect_class(new_path_with_query_params)
#Handles redirections for urls without query parameters
return self.response_redirect_class(r.new_path)
return response
我。简单地将
CustomRedirectFallbackMiddleware
与URL parameters
分开。II。接下来准确
full_absolute_path
分隔redirect_path
表格full_absolute_path
数据库。III。然后将与
django.contrib.redirects
分开的URL parameters
附加到full_absolute_path
。
2.从redirect_path
移除'django.contrib.redirects.middleware.RedirectFallbackMiddleware'
,并将以下行添加到settings.py
的{{1}}。
MIDDLEWARE
所有以下情况都很好。
没有网址参数。
使用一个URL参数。
有多个网址参数。
更新:修正了在没有尾部斜杠的网址时提升404的问题。
希望这有帮助。