【问题标题】:How to Implement 301 Redirects with Django/Heroku如何使用 Django/Heroku 实现 301 重定向
【发布时间】:2013-08-30 10:54:52
【问题描述】:

我希望将旧 URL 列表重定向到 Django/Heroku 应用程序中的新 URL 列表。

由于我使用的是 Heroku,我不能只使用 .htaccess 文件。

我看到 rails 有 rack-rewrite,但我还没有看到 Django 类似的东西。

【问题讨论】:

    标签: python django heroku


    【解决方案1】:

    Django 有重定向应用程序,它允许在数据库中存储重定向列表: https://docs.djangoproject.com/en/dev/ref/contrib/redirects/

    这里还有一个通用的 RedirectView:

    https://docs.djangoproject.com/en/1.3/ref/class-based-views/#redirectview

    而最底层是HttpResponseRedirect:

    https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponseRedirect

    【讨论】:

    • 重定向应用正是我所需要的。它适用于应用程序列表,并且似乎比将所有内容添加到我的 urls conf 中要干净得多。谢谢
    【解决方案2】:

    试试redirect_to

    文档中的 301 重定向示例:

    urlpatterns = patterns('django.views.generic.simple',
        ('^foo/(?P<id>\d+)/$', 'redirect_to', {'url': '/bar/%(id)s/'}),
    )
    

    【讨论】:

      【解决方案3】:

      您可以使用重定向。请检查以下代码。

      from django.shortcuts import redirect
      return redirect(
                      '/', permanent=True
                  )
      

      它对我有用。

      【讨论】:

        【解决方案4】:

        虽然在接受的答案中提到的redirects app 是一个非常好的解决方案,但它还涉及每个 404 错误的数据库调用。我想避免这种情况,所以最终只是在 URL conf 中手动实现。

        """redirects.py that gets included by urls.py"""
        from django.urls import path, reverse_lazy
        from django.views.generic.base import RedirectView
        
        
        def redirect_view(slug):
            """
            Helper view function specifically for the redirects below since they take
            a kwarg slug as an argument.
            """
            return RedirectView.as_view(
                url=reverse_lazy('app_name:pattern_name', kwargs={'slug': slug}),
                permanent=True)
        
        urlpatterns = [
            path('example-redirect/', redirect_view('new-url')),
        ]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-04
          • 2012-02-06
          • 1970-01-01
          • 2021-06-02
          • 2011-05-26
          • 2020-03-28
          • 1970-01-01
          • 2020-01-24
          相关资源
          最近更新 更多