Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 72 ยท Routing and Views

Subdomains and Host Matching

Serve api.example.com, admin.example.com and per-customer subdomains from one Flask app. Learn SERVER_NAME, subdomain routes, host_matching, url_for across hosts and local testing.

Many sites are more than one hostname. www.example.com is the marketing page, api.example.com is the API, admin.example.com is the back office, and SaaS products give every customer their own address such as acme.example.com. Flask can route on the host name as well as the path, so one application (and one codebase) can serve all of them.

In this lesson you will configure SERVER_NAME, attach routes and blueprints to subdomains, capture a subdomain as a variable, build links across hosts with url_for, and try it all without owning a domain.

Two ways to match hosts

Flask offers two mechanisms. Pick one per application:

Feature Setting Good for
Subdomain matching SERVER_NAME set and Flask(__name__, subdomain_matching=True) all hosts share one parent domain: *.example.com
Host matching Flask(__name__, host_matching=True) completely different domains: example.com and example.org

The first is by far the more common, so we start there.

SERVER_NAME and subdomain=

SERVER_NAME tells Flask the parent domain (plus port, if any), and subdomain_matching=True in the Flask(...) call switches on matching of the part in front of it (without that flag every host is treated as the main domain). Routes then take a subdomain argument. A request to api.example.com is matched only against routes whose subdomain="api"; the empty subdomain "" (the default) is the bare example.com.

Python Routes on subdomains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last two requests return 404: Flask finds no rule for that host and path combination, exactly as if the URL were wrong. Note that base_url is how you tell the test client which host the "browser" typed.

When SERVER_NAME is set, Flask also refuses requests for any other host with a 404. That surprises people who test from 127.0.0.1 or a Docker hostname. Make sure the real host name, port included, matches the setting.

Capturing the subdomain as a variable

A multi-tenant app needs any subdomain, not a fixed list. Use a variable in the subdomain argument just like a URL variable. Flask passes it to your view.

Python One route, many customers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Always check the captured value against your own data (here a dictionary, in real life a database lookup) and return 404 for unknown tenants. The subdomain is typed by the visitor.

Blueprints on a subdomain

Rather than add subdomain="api" to every route, give the whole blueprint a subdomain when you register it. This keeps blueprint code unaware of where it lives.

Python register_blueprint(subdomain=...)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

url_for across subdomains

With SERVER_NAME configured, url_for knows every route's host. Inside a request it produces a relative URL if the target is on the same host and a full URL (_external is switched on automatically) when the target is on a different subdomain. Outside a request you must pass _external=True and be in an app context, as the example above did.

Because links are built from the route table, you never hard-code https://api.example.com/... in templates. See url_for for the basics.

Matching entirely different hosts

If hosts do not share a parent domain, switch the app to host matching. Every route must then say which host it answers, and static_host must be set if you serve static files.

Python host_matching for unrelated domains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Local development without a domain

You cannot visit api.example.com on your laptop, but you have several options:

  • *.localhost: modern browsers resolve any name ending in .localhost to your own machine, so api.localhost:5000 works with no setup. Set SERVER_NAME = "localhost:5000" and use subdomain="api".
  • The hosts file: add lines such as 127.0.0.1 example.test and 127.0.0.1 api.example.test to /etc/hosts (on Windows C:\Windows\System32\drivers\etc\hosts). A hosts file has no wildcards, so each subdomain needs its own line.
  • A local DNS tool such as dnsmasq, which supports wildcards.

Use a different config value for each environment (see Configuration): localhost:5000 in development, your real domain in production.

Cookies and sessions across subdomains

By default a session cookie belongs to one host. To share a login between www.example.com and app.example.com, set the cookie domain with a leading dot or let SESSION_COOKIE_DOMAIN default from SERVER_NAME:

Python
app.config["SESSION_COOKIE_DOMAIN"] = ".example.com"

Sharing cookies across subdomains also shares risk: any subdomain, including a forgotten one you do not control, can read or overwrite them. For multi-tenant apps where customers are not supposed to see each other's sessions, keep the default host-only cookie. Cookies explains the attributes.

Common mistakes

  • Setting SERVER_NAME and then testing through a different hostname or port: every route returns 404.
  • Forgetting that SERVER_NAME includes the port in development.
  • Using localhost and expecting localhost subdomain cookies to work in every browser.
  • Trusting the subdomain variable without checking it exists.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do you set so Flask knows the parent domain for subdomain routes?

    SERVER_NAME holds the domain (and port) such as example.com:5000, which Flask uses to split a request host into subdomain and domain.
  2. 2. How do you route requests for acme.example.com and globex.example.com to one view?

    The subdomain argument accepts variables like URL paths do. Flask passes the captured text to your view.
  3. 3. What happens when SERVER_NAME is set and a request arrives for an unrelated host?

    With SERVER_NAME set, Flask only matches routes for that domain, so other hosts get 404.
  4. 4. When should you choose host_matching=True?

    host_matching routes on the full host name, so it handles unrelated domains. Subdomain matching assumes a shared parent.

Summary

  • Flask can route on the host as well as the path: SERVER_NAME plus subdomain= for subdomains, host_matching=True plus host= for unrelated domains.
  • A variable subdomain (subdomain="<tenant>") supports multi-tenant apps; always validate the value.
  • Register a blueprint on a subdomain with register_blueprint(bp, subdomain="api").
  • url_for builds cross-host links, and _external=True is needed outside a request.
  • Locally use *.localhost or a hosts file, and test with test_client().get(..., base_url=...).
  • Cookies are host-only unless you set SESSION_COOKIE_DOMAIN, which shares them with every subdomain.

Next: stream large or never-ending responses with Streaming Responses and Server-Sent Events.