URL Building, Redirects and Static Files

URL Building, Redirects and Static Files in Flask: --- A large teaching hospital is a maze of departments -- Radiology, Phlebotomy, Ward 4 -- and it is…


The Analogy: The Hospital's Central Wayfinding Directory

A large teaching hospital is a maze of departments -- Radiology, Phlebotomy, Ward 4 -- and it is renovated constantly, so the room a department occupies this year is not the room it occupied last year. The hospital tames the chaos with a central wayfinding directory: every department has a stable name, and the directory maps that name to its current room. Every corridor sign, every kiosk, and every porter consults the directory rather than a memorised room number. Ask for "Radiology" and you are told where Radiology is today. The department name is your route's endpoint, the directory lookup is url_for, and the room number it hands back is the URL -- resolved fresh each time, never written down.

When a patient turns up where a department used to be, or at a general reception whose only job is to route people onward, a porter walks them to the right place: "Phlebotomy is on Level 2 now, this way." The patient does not remain at the desk; they are sent onward to a different location, and they can tell it was a forwarding rather than the destination itself. That escorted forwarding is an HTTP redirect: the server answers not with the page but with "go here instead" -- a 302 and a new location -- and the browser follows it.

Alongside the moving departments, the building has fixtures that never change and exist simply to be used: the fire-evacuation maps by each stairwell, the cafeteria menu board, the framed floor plan. Nobody looks these up in the directory; they are mounted at standard, well-known spots and read as-is. Those are your static files -- the stylesheet, the images, the logo -- served straight from a conventional /static location. And when a patient finishes a form at a desk, the clerk does not leave them standing there holding it; they are sent to a waiting area carrying a slip that reads "form received," shown once. Refreshing the waiting-room screen does not resubmit the form. That is the post/redirect/get pattern with a one-time flash message.

The failure begins with a clerk who finds the directory a nuisance and starts writing the literal current room number onto every printed referral: "Radiology, Room 118." It saves a lookup and works perfectly until the next renovation moves Radiology to Room 240. Now every one of the thousands of printed referrals sends patients to what is today a supply closet; the signs and porters that used the directory are all still correct, but the hardcoded slips are uniformly wrong and there is no way to mend them but to reprint every one. Writing a URL path as a literal string instead of asking url_for is exactly this -- a single route change silently breaks every place that hardcoded the old path.


Syntax or Core Structure

url_for builds a URL from an endpoint name and its parameters, so your links and redirects reference what they point to, never a literal path. The endpoint is, by default, the view function's name. Values that match a route's variables fill the path; any extra keyword arguments are appended as a query string. Flask registers a static endpoint automatically, so the same mechanism builds the URL for your assets.

from flask import Flask, url_for

app = Flask(__name__)


@app.route("/")
def home():
    return "home"


@app.route("/products/<int:pid>")
def product(pid):
    return "product"


with app.test_request_context():
    print(url_for("home"))
    print(url_for("product", pid=42))
    print(url_for("product", pid=42, ref="email"))
    print(url_for("static", filename="app.css"))

Output:

/
/products/42
/products/42?ref=email
/static/app.css

url_for("product", pid=42) fills the <int:pid> slot to produce /products/42, and the extra ref="email" -- which is not a route variable -- becomes the query string ?ref=email. In a template you write the identical call: <link rel="stylesheet" href="{{ url_for('static', filename='app.css') }}">. Change the route to /catalogue/<int:pid> later and every one of these URLs updates itself, because none of them hardcoded the path.


Technical Depth: Redirects, Flash Messages, and Serving Assets

Building URLs is half the story; the other half is sending the browser to one and serving the files that never move. A redirect is an HTTP response whose status code says "the thing you asked for is elsewhere" and whose Location header says where. The code you choose matters, because it tells the browser whether the move is permanent and whether to keep the original method.

CodeMeaningMethod afterwardUse for
301Moved PermanentlyMay change to GETA URL that moved for good
302Found (temporary)May change to GETFlask's default redirect
303See OtherAlways GETPost/redirect/get after a form
307Temporary RedirectPreservedTemporary move that must keep POST
308Permanent RedirectPreservedPermanent move that must keep POST

Redirecting between views

redirect(url_for(...)) is the idiom: build the target by name, then hand it to redirect, which defaults to a 302. The response carries no body worth reading -- only the Location header the browser follows.

from flask import Flask, redirect, url_for

app = Flask(__name__)


@app.get("/new")
def new():
    return "new home", 200


@app.get("/old")
def old():
    return redirect(url_for("new"))


client = app.test_client()
r1 = client.get("/old")
print("status:", r1.status_code)
print("location:", r1.headers["Location"])
r2 = client.get("/old", follow_redirects=True)
print("final:", r2.status_code, r2.get_data(as_text=True))

Output:

status: 302
location: /new
final: 200 new home

The first request returns 302 with Location: /new and stops there; follow_redirects=True tells the test client to chase it, landing on the 200 and the real body. Note the Location is the path url_for produced -- rename new's route and the redirect still points at the right place.

Flash messages and post/redirect/get

When a POST succeeds, you should not render the result directly -- if the user hits refresh, the browser re-submits the form. The cure is post/redirect/get (PRG): the POST handler does its work, then redirects to a GET page. But the success message needs to survive that redirect, and flash is how. It stashes a message in the session; the next request that calls get_flashed_messages reads it out and it is gone -- shown exactly once, like a "received" slip handed over and never reprinted.

from flask import Flask, flash, get_flashed_messages, redirect, url_for

app = Flask(__name__)
app.secret_key = "test-key"


@app.post("/save")
def save():
    flash("Saved successfully")
    return redirect(url_for("result"))


@app.get("/result")
def result():
    return {"messages": get_flashed_messages()}


client = app.test_client()
client.post("/save")
r = client.get("/result")
print("first :", r.get_json()["messages"])
r2 = client.get("/result")
print("second:", r2.get_json()["messages"])

Output:

first : ['Saved successfully']
second: []

The first GET after the POST sees the flashed message; the second GET sees an empty list, because reading a flash consumes it. flash needs a secret_key because the message rides in the signed session cookie -- without one, Flask raises at the flash call. This is why PRG plus flash is the standard shape for any form that changes data.

Serving static files

CSS, JavaScript, images, and fonts do not change per request, so Flask serves them straight off disk from a folder named static next to your app, exposed at the /static URL prefix. You never write a route for them -- Flask registers the static endpoint automatically, which is why url_for("static", filename="app.css") worked earlier. Both the folder name and the URL prefix are configurable at construction: Flask(__name__, static_folder="assets", static_url_path="/files").

For files you serve dynamically -- a user's uploaded avatar, a generated report, a download behind a login -- do not build the path by hand. Use send_from_directory, which joins the directory and the requested name safely and refuses any name that tries to climb out with ../. Building the path yourself with string concatenation is how directory-traversal holes are born.

import os
from flask import Flask, send_from_directory, abort
from flask_login import login_required  # illustrative: gate the download

app = Flask(__name__)
REPORTS = "/srv/reports"


@app.get("/reports/<name>")
@login_required
def report(name):
    # send_from_directory rejects "../secrets.env" and absolute paths
    if not name.endswith(".pdf"):
        abort(404)
    return send_from_directory(REPORTS, name, as_attachment=True)

The key distinction: the static folder is for public, unchanging assets shipped with the app, and in production a reverse proxy such as Nginx usually serves it directly, bypassing Python entirely. send_from_directory is for files chosen at request time, where you control access and validate the name. Mixing the two -- serving user uploads out of static -- means anyone who can guess a filename can read anyone's files.


Real World Example: A Login That Sends Users Wherever the Link Says

Almost every login page carries a next parameter. A user clicks a link to /settings while logged out, gets bounced to /login?next=/settings, and after signing in the app redirects them back to /settings so the interruption is invisible. It is a small, universal courtesy, and the obvious implementation is to read next from the query string and redirect to it. The app below does exactly that, and also ships a hardened variant beside it so we can compare.

from flask import Flask, redirect, request, url_for
from urllib.parse import urlsplit

app = Flask(__name__)


def is_safe(target):
    if not target:
        return False
    parts = urlsplit(target)
    return parts.scheme == "" and parts.netloc == "" and target.startswith("/")


@app.get("/dashboard")
def dashboard():
    return "dashboard"


@app.get("/login")
def login():
    nxt = request.args.get("next", "")
    target = nxt if nxt else url_for("dashboard")   # VULNERABLE: trusts next
    return redirect(target)


@app.get("/login-safe")
def login_safe():
    nxt = request.args.get("next", "")
    target = nxt if is_safe(nxt) else url_for("dashboard")
    return redirect(target)


client = app.test_client()
for path in ["/login?next=/dashboard",
             "/login?next=https://evil.example/phish",
             "/login-safe?next=https://evil.example/phish"]:
    r = client.get(path)
    print(path, "->", r.headers["Location"])

Output:

/login?next=/dashboard -> /dashboard
/login?next=https://evil.example/phish -> https://evil.example/phish
/login-safe?next=https://evil.example/phish -> /dashboard

The first line is the happy path: next=/dashboard is a local path, and the user lands on their dashboard. The second line is the problem. The same handler happily emits Location: https://evil.example/phish -- a fully external URL -- because it never asked whether next pointed inside the site. The third line shows the fix working: is_safe rejects anything with a scheme or a host, and anything that does not start with a single /, so the external target is discarded and the user goes to the safe default.

The design flaw is an open redirect. Because /login forwards to any next value without validating it, an attacker sends victims a link to your trusted domain -- https://yourbank.example/login?next=https://evil.example/phish -- and your own server bounces them to a look-alike phishing page. The victim sees your real domain in the link, trusts it, clicks, and lands on the attacker's page with your brand still in their mind. Worse variants use next=//evil.example or next=https:evil.example, which some naive checks miss but urlsplit catches because it populates netloc. The rule is simple and absolute: never redirect to a location derived from user input unless you have confirmed it is a relative path on your own site -- empty scheme, empty netloc, leading slash -- and fall back to a known-safe default otherwise.


Common Mistakes

  1. Hardcoding URLs in templates and redirects. Writing redirect("/products/42") or <a href="/login"> scatters literal paths through the codebase. The day you move a route under a blueprint prefix or change the pattern, every copy breaks silently. Always build with url_for.
  1. Passing the view function instead of its endpoint name. url_for(login) (the function object) raises; it must be url_for("login") (the string name). Inside a blueprint the name is prefixed: url_for("auth.login"). The error message is not always obvious, so learn to read it as "I gave a function where a name was expected."
  1. Trusting a next parameter without validation. redirect(request.args.get("next")) is an open redirect: an attacker crafts a link to your domain that bounces to a phishing page. Validate that the target is a local path (empty scheme, empty netloc, leading /) and fall back to a safe default otherwise.
  1. Using a 302 when the method must be preserved. The default redirect sends 302, which browsers may turn a POST into a GET on. If you must redirect a POST and keep it a POST, use redirect(url, code=307); for a permanent method-preserving move use 308.
  1. Calling flash without setting secret_key. Flash messages ride in the signed session cookie, so flash("...") raises RuntimeError if app.secret_key is unset. In production the key must be a long random value loaded from the environment, never a literal committed to source.
  1. Rendering a POST result directly instead of redirecting. If your POST handler returns a rendered page, hitting refresh re-submits the form -- duplicate orders, double charges. Do the work, then redirect to a GET page (post/redirect/get), carrying any message via flash.
  1. Building file paths from user input by hand. open(os.path.join(UPLOADS, request.args["name"])) lets name=../../etc/passwd escape the directory. Use send_from_directory, which rejects traversal and absolute paths, and still validate the extension.
  1. Serving private uploads from the static folder. Anything in static is world-readable by URL with no access check. User documents, invoices, or avatars that should be gated belong behind a route that checks permissions and uses send_from_directory, not in static.
  1. Ignoring the trailing-slash rule. A route defined as /items/ redirects /items to /items/, but a route defined as /items returns 404 for /items/. Pick a convention, know that url_for emits whichever form you registered, and do not rely on the browser papering over the difference.

Best Practices

  • Generate every internal URL with url_for. Templates, redirects, and API responses should all name endpoints, never literal paths. This makes routes refactorable and keeps blueprint prefixes and trailing-slash conventions correct automatically.
  • Validate any redirect target derived from user input. Treat next, return_to, and similar parameters as hostile. Confirm the parsed URL has no scheme and no netloc and begins with a single /, and redirect to a safe default when it does not.
  • Follow post/redirect/get for every state-changing form. POST handlers should finish with a redirect to a GET view so refresh and back-button do not re-submit. Use flash to carry the success or error message across the redirect.
  • Choose the redirect status code deliberately. Use 302 or 303 for ordinary post-action navigation, 301 or 308 only for URLs that have genuinely moved for good, and 307 or 308 when a POST must stay a POST. The wrong code confuses caches, crawlers, and browsers.
  • Serve public assets from static and let a proxy handle them in production. Ship CSS, JS, and images from the static folder, reference them with url_for("static", ...), and configure Nginx or a CDN to serve that path directly so Python is not in the hot path for every file.
  • Serve dynamic or gated files through send_from_directory. For uploads and generated downloads, route the request, check the user's permission, validate the requested name, and let send_from_directory resolve the path safely against traversal.
  • Load the secret key and file locations from configuration. SECRET_KEY, upload directories, and the static URL prefix belong in config read from the environment, so the same code runs in development and production without editing source.
  • Prefer relative endpoint references and add _external=True only when needed. Emails, webhooks, and OAuth callbacks need absolute URLs, so pass _external=True there; for in-page links keep the relative form, which is shorter and immune to host-header confusion.

Practice Exercises

  1. Build a two-route app: / returns "home" and /articles/<int:aid> returns the id. In a test_request_context, print url_for for the home page, for article 7, for article 7 with a page=2 query argument, and for the article page with _external=True. Confirm the external form includes the scheme and host while the others are relative paths.
  1. Implement post/redirect/get. Add a /subscribe POST route that flashes "Subscribed" and redirects to a /thanks GET route that renders the flashed messages. Using the test client, POST once then GET /thanks twice, and verify the message appears the first time and is gone the second time. Explain why refreshing /thanks never re-runs the subscription.
  1. Write an is_safe_target(url) helper and a /login route that redirects to a next query parameter only when it is a local path, otherwise to /dashboard. Test it against /dashboard, https://evil.example, //evil.example, and https:evil.example, and confirm only the first is accepted. State which property of urlsplit catches the //evil.example case.
  1. Add a /download/<name> route that serves files from a directory using send_from_directory, returning 404 for any name that does not end in .txt. Create a temporary directory with one .txt file, then use the test client to fetch the real file (expect 200), a .pdf name (expect 404), and ../secret.txt (expect the traversal to be blocked). Describe why send_from_directory is safer than opening the joined path yourself.