2

I am trying to redirect the user to a URl but it is redirecting me to an incorrect url.

views.py:

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

url.py:

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

The code appears correct to me but the user is incorrectly redirected to a url with the current url appended with the specfied url, i.e. the user is redirected to http://127.0.0.1:8000/www.google.com when http://127.0.0.1:8000/ is the current url.

Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
sm_man
  • 23
  • 3

1 Answers1

2

When one wants to redirect to some other website, one should provide the absolute url (See the question Absolute vs relative URLs) for the page on the other website. www.google.com is not an absolute url, namely it is missing the protocol https:// hence it is considered as a relative url from the page the user is currently on and hence resolves to http://127.0.0.1:8000/www.google.com. Instead you want to write the redirect to be absolute as:

def redirect_shortner(request):
    return redirect('https://www.google.com/')
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33