如何重定向 URL 中任意位置包含 PHP
的所有请求?
我用它来重定向任何以 .php 结尾的内容
url(r'^(?P<path>.*)\.php$',
RedirectView.as_view(
url='http://www.php.net/', permanent=True)),
现在,我想捕获并重定向所有在 URL 中任何位置包含关键字 php
的 URL 请求,即使没有点 .
之类的内容,例如 blah/php/blah
或 blahPHPblah
等
类似这样的事情:
url(r'^(?P<path>php*)',
RedirectView.as_view(
url='http://blah.com/', permanent=True)),
如果 .htaccess 规则是更好的解决方案,我也对此持开放态度!
最佳答案
一种解决方案是使用重定向中间件:
from django.shortcuts import redirect
class PHPRedirectMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
if ".php" in request.get_raw_uri():
return redirect(to="http://www.example.com")
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
您必须在 MIDDLEWARE
列表中的 settings.py
中注册。
关于php - Django URL 重定向所有 PHP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915221/