繁体   English   中英

如何使用 Django/Heroku 实现 301 重定向

[英]How to Implement 301 Redirects with Django/Heroku

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

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

我看到 rails 有机架重写,但我还没有看到 Django 有这样的东西。

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

这里还有一个通用的重定向视图:

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

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

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

它对我有用。

在此处输入图片说明

尝试redirect_to

来自 301 重定向文档的示例:

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

虽然接受的答案中提到的重定向应用程序是一个非常好的解决方案,但它也涉及每个 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')),
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM