Django 项目的 301 重定向路由器
301 redirect router for Django project
我有一个用 Django 创建的网站构建工具,我想向它添加简单的用户定义的 301 重定向。
Webflow 有一个非常容易理解的 301 重定向工具。您添加一条路径(不仅仅是一个 slug),然后定义该路径应该引导用户的位置。
我想为我正在处理的 Django 项目做同样的事情。我目前允许用户设置一个重定向 /<slug:redirect_slug>/
的 slug,他们可以设置为转到任何 URL。但我希望他们能够添加,例如,旧博客的路径 post '/2018/04/12/my-favorite-thing/'
在 Django 中使用什么是最好的 URL conf 来安全地接受用户想要的任何路径?
您可以使用 Path Converters 将路径参数转换为适当的类型,其中还包括一个 url 转换器。
示例如下:
path('api/<path:encoded_url>/', YourView.as_view()),
根据文档:
Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than just a segment of a URL path as with str.
在您看来,您可以这样获得 URL:
encoded_url = self.kwargs.get('encoded_url')
添加一个 RerouteMiddleware
,它首先检查 urls.py
中现有的 URL 是否可以满足请求。如果无法提供服务,请检查请求的路径是否来自 old -> new URLs 映射,如果找到匹配项,则将其重定向到新的 URL .
试用一段代码示例。
try:
resolve(request.path_info)
except Resolver404:
# Check if the URL exists in your database/constants
# where you might have stored the old -> new URL mapping.
if request.path is valid:
new_url = # Retrieve the new URL
return redirect(new_url)
response = self.get_response(request)
return response
我有一个用 Django 创建的网站构建工具,我想向它添加简单的用户定义的 301 重定向。
Webflow 有一个非常容易理解的 301 重定向工具。您添加一条路径(不仅仅是一个 slug),然后定义该路径应该引导用户的位置。
我想为我正在处理的 Django 项目做同样的事情。我目前允许用户设置一个重定向 /<slug:redirect_slug>/
的 slug,他们可以设置为转到任何 URL。但我希望他们能够添加,例如,旧博客的路径 post '/2018/04/12/my-favorite-thing/'
在 Django 中使用什么是最好的 URL conf 来安全地接受用户想要的任何路径?
您可以使用 Path Converters 将路径参数转换为适当的类型,其中还包括一个 url 转换器。
示例如下:
path('api/<path:encoded_url>/', YourView.as_view()),
根据文档:
Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than just a segment of a URL path as with str.
在您看来,您可以这样获得 URL:
encoded_url = self.kwargs.get('encoded_url')
添加一个 RerouteMiddleware
,它首先检查 urls.py
中现有的 URL 是否可以满足请求。如果无法提供服务,请检查请求的路径是否来自 old -> new URLs 映射,如果找到匹配项,则将其重定向到新的 URL .
试用一段代码示例。
try:
resolve(request.path_info)
except Resolver404:
# Check if the URL exists in your database/constants
# where you might have stored the old -> new URL mapping.
if request.path is valid:
new_url = # Retrieve the new URL
return redirect(new_url)
response = self.get_response(request)
return response