重定向到外部网站时,url 被附加到请求的 url 的末尾

Posted

技术标签:

【中文标题】重定向到外部网站时,url 被附加到请求的 url 的末尾【英文标题】:When redirecting to external website the url gets appended to the end of the requested url 【发布时间】:2021-09-10 18:52:31 【问题描述】:

我正在尝试将用户重定向到一个 URl,但它正在将我重定向到一个不正确的 url。

views.py:

def redirect_shortner(request):
    return redirect('www.google.com')

url.py:

urlpatterns = [
    path('', redirect_shortner, name='redirect_shortner'),
]

代码对我来说似乎是正确的,但用户被错误地重定向到当前 url 附加指定 url 的 url,即当 http://127.0.0.1:8000/ 是当前 url 时,用户被重定向到 http://127.0.0.1:8000/www.google.com

【问题讨论】:

你能尝试重定向这个吗? https://www.google.com/ 【参考方案1】:

当一个人想要重定向到其他网站时,应该为其他网站上的页面提供 absolute url(参见问题Absolute vs relative URLs)。 www.google.com 不是绝对 url,即它缺少协议 https://,因此它被视为来自用户当前所在页面的 相对 url,因此解析为 http://127.0.0.1:8000/www.google.com。相反,您希望将重定向编写为绝对的:

def redirect_shortner(request):
    return redirect('https://www.google.com/')

【讨论】:

以上是关于重定向到外部网站时,url 被附加到请求的 url 的末尾的主要内容,如果未能解决你的问题,请参考以下文章