Question

I need to redirect back to an external url after completing an action in my flask application. The code looks like this

if form.next.data is not None:
    return redirect(form.next.data)

where form.next.data can be an absolute url for an external domain like "www.google.com". However on passing the next value as an external url, this redirect is instead redirecting to http://mysitename/www.google.com and failing with a 404.

How do I specify that the redirect is to an external domain and stop Flask from appending it to my domain root?

Was it helpful?

Solution

I think you need to append a prefix http:// or https:// to "www.google.com". Otherwise Flask is treating that as a relative url inside app. So below will be a 404 as it's going to "localhost:5000/www.google.com"

@app.route('/test')
def test():
    return redirect("www.google.com")

But if you try with http://, it should work fine.

@app.route('/test')
def test():
    return redirect("http://www.google.com")

OTHER TIPS

Make sure you append "http://" in front of the url before passing it in redirect.

s = form.next.data
if s is not None:
    if s.find("http://") != 0 and s.find("https://") != 0:
        s = "http://" + s
    return redirect(s)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top