Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Redirect to another domain from View

I'm trying to redirect from mydomain.com to google.com. There are a couple of answers on stackoverflow that asume the following is working:

return HttpResponseRedirect('google.com')

or

return redirect('google.com')

But it doesn't it. This just redirects the page to itself and appends the google.com part so it comes out like this:

www.mydomain.com/google.com

What throws a 404 of course.. My view now looks like the following:

class MyView(TemplateView):

    def get(self, request, *args, **kwargs):
        return HttpResponseRedirect('google.com')

Can anyone give me insights in what I'm doing wrong?

like image 399
Nebulosar Avatar asked Sep 17 '25 23:09

Nebulosar


1 Answers

They answers are in some sense correct: you do a redirect. But now the web browser needs to perform the redirect.

Usually paths that are not prepended with two consecutive slashes are assumed to be local: so that means it stays at the same domain.

In case you want to go to another domain, you need to add a protocol, or at least two consecutive slashes (such that the old protocol is reused):

return HttpResponseRedirect('https://google.com')  # use https

or:

return HttpResponseRedirect('//google.com')  # "protocol relative" URL

After all you only return a redirect answer to the browser. The browser can decide not to follow the redirect (some browsers do), or can interpret it in any way they like (although that means that the browser does not really does what we can expect it to do). We can not force a browser to follow the redirect.

like image 186
Willem Van Onsem Avatar answered Sep 22 '25 11:09

Willem Van Onsem