Redirect URL in Python Flask

Flask – Redirect URL

In a flask application, we can redirect a URL to another URL using redirect() function.

The following is a simple code snippet to redirect /page-1 to /page-2.

def page2():
    return redirect("/page-2", code=302)

The second argument to redirect function specifies the type of redirect (temporary or permanent). Redirect code 301 indicates that page has been permanently moved to a new location, whereas redirect code 302 indicates that the page is moved to a new location temporarily.

We must import redirect from flask library before using it.


In this example, we build a flask application where we have following web pages.

  • page-1.html
  • page-2.html

When a request comes for page-1.html, we will redirect it to page-2.html, using redirect() function.

Project Structure

The following is the structure of our flask application.

Python Flask Application Project Structure

from flask import Flask, render_template, redirect

app = Flask(__name__)

def page_1():
    return redirect("/page-2", code=302)

def page_2():
    return render_template("page-2.html")

if __name__ == "__main__":"", port=8080, debug=True)


{% include "header.html" %}

<h1>Page 1</h1>
<p>Welcome to sample flask application.</p>

{% include "footer.html" %}


{% include "header.html" %}

<h1>Page 2</h1>
<h2>Another Page</h2>
<p>This is another page in this flask application.</p>

{% include "footer.html" %}


Open terminal at the root of the application, and run the Python file

Redirect URL in Python Flask

Now, open a browser of your choice and hit the URL

Python Flask - Redirect URL

As you can observe under the Network tab in browser, the server responds to the request URL /page-1 with a 302 redirect, just like what we said it to do, and redirects it to /page-2.

Project ZIP


In this Python Flask Tutorial, we learned how to redirect a URL, with the help of an example flask application.

Code copied to clipboard successfully 👍