Redirecting between pages
Redirects tell the browser to visit another URL. They are commonly used after login, form submission, logout, or changing an old page address.
1. Redirect one page to another
def old_about(req: Request) -> Response:
return Response.redirect("/about", status=302)
app.get("/old-about", old_about)
Visit /old-about. Your browser will navigate to /about.
Check the HTTP response:
curl -i http://127.0.0.1:8000/old-about
HTTP/1.1 302 Found
Location: /about
A 302 redirect is temporary.
2. Redirect after a form is submitted
def save_contact(req: Request) -> Response:
var name = req.form.get("name", "")
if name == "":
return Response.html("<p>Name is required</p>", status=422)
# Save the submitted contact in your application.
return Response.redirect("/contact/success", status=303)
def success(req: Request) -> Response:
return Response.html("<h1>Message received</h1>")
app.post("/contact", save_contact)
app.get("/contact/success", success)
After POST, 303 See Other tells the browser to load the success page with GET. Refreshing the success page will not resubmit the form.
3. Redirect users to login
def dashboard(req: Request) -> Response:
if req.session.get("user_id", "") == "":
return Response.redirect("/login", status=303)
return Response.html("<h1>Dashboard</h1>")
app.get("/dashboard", dashboard)
A visitor without a login session goes to /login; an authenticated visitor sees the dashboard.
4. Redirect an old permanent URL
def old_blog(req: Request) -> Response:
return Response.redirect("/articles", status=301)
app.get("/blog", old_blog)
Use 301 when the address has permanently changed. Browsers and search engines may cache this redirect.
5. Redirect after logout
def logout(req: Request) -> Response:
req.session.clear()
return Response.redirect("/login", status=303)
app.post("/logout", logout)
The server invalidates the session and sends the visitor to the login page.
6. Follow redirects with curl
# Show the redirect status and Location header
curl -i http://127.0.0.1:8000/old-about
# Follow the redirect automatically
curl -i -L http://127.0.0.1:8000/old-about
| Status | Typical use |
|---|---|
| 301 | Permanent URL change |
| 302 | Temporary redirect |
| 303 | Redirect to GET after submitting a form |
| 307 | Temporary redirect preserving the HTTP method |
| 308 | Permanent redirect preserving the HTTP method |
See Sessions and cookies and Requests and forms.