php - Django URL 重定向所有 PHP 请求

标签 php python django .htaccess redirect

如何重定向 URL 中任意位置包含 PHP 的所有请求?

我用它来重定向任何以 .php 结尾的内容

url(r'^(?P<path>.*)\.php$', 
    RedirectView.as_view(
        url='http://www.php.net/', permanent=True)),

现在,我想捕获并重定向所有在 URL 中任何位置包含关键字 php 的 URL 请求,即使没有点 . 之类的内容,例如 blah/php/blahblahPHPblah

类似这样的事情:

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/

相关文章:

python - Django:用元组过滤组合列

django - 多对多以及如何从查询集中获取查询集

php - 通过 PHP cURL 获取文件内容

php - mongodb php扩展安装给出配置错误

python - 在构建 RPM 包时传送 *.so 和二进制文件

python - 在 login_user 函数 View 中获取 member_id 的 KeyError

php - MySQL在同一列中搜索多个关键字

php - URL重写和设计文件

python - CNN 返回相同的分类结果(keras)

python - 我正在尝试进行分类分析 我想将计数值转换为百分比,但出现错误