Routing
pyserve supports nginx-style routing patterns including exact matches, regex locations, and SPA fallback.
Location Types
= |
Exact match | =/health matches only /health |
~ |
Case-sensitive regex | ~^/api/v\d+/ matches /api/v1/ |
~* |
Case-insensitive regex | ~*\.(js|css)$ matches .JS and .css |
__default__ |
Default fallback | Matches when no other route matches |
Match Priority
Routes are processed in the following order:
- Exact matches (
=) — checked first - Regex patterns (
~and~*) — in definition order - Default fallback (
__default__) — last resort
Routing Configuration
Routing is configured via the routing extension:
extensions: - type: routing config: regex_locations: # Exact match for health check "=/health": return: "200 OK" content_type: "text/plain" # Static files with caching "~*\\.(js|css|png|jpg|gif|ico)$": root: "./static" cache_control: "public, max-age=31536000" # HTML files without caching "~*\\.html$": root: "./static" cache_control: "no-cache" # Default fallback "__default__": root: "./static" index_file: "index.html"
Location Directives
- root
- Base directory for serving files.
- index_file
- Index file name for directory requests. Default:
index.html - proxy_pass
- Upstream server URL for reverse proxy. See Reverse Proxy.
- return
- Return a fixed response. Format:
"status message"or"status" - content_type
- Response content type for
returndirective. - cache_control
- Cache-Control header value.
- headers
- List of additional headers to add. Format:
"Header-Name: value" - spa_fallback
- Enable SPA mode — serve index file for all routes.
- exclude_patterns
- URL patterns to exclude from SPA fallback.
Named Capture Groups
Regex locations support named capture groups that can be used in headers and proxy URLs:
"~^/api/v(?P<version>\\d+)/(?P<resource>\\w+)": proxy_pass: "http://backend:9001" headers: - "X-API-Version: {version}" - "X-Resource: {resource}"
Request to /api/v2/users will have headers:
X-API-Version: 2X-Resource: users
SPA Configuration
For Single Page Applications, use spa_fallback with exclude_patterns:
"__default__": spa_fallback: true root: "./dist" index_file: "index.html" exclude_patterns: - "/api/" - "/assets/" - "/static/"
This will:
- Serve
index.htmlfor routes like/about,/users/123 - Return 404 for
/api/*,/assets/*,/static/*if file not found
Static File Serving
Basic static file configuration:
"~*\\.(css|js|png|jpg|gif|svg|woff2?)$": root: "./static" cache_control: "public, max-age=86400" headers: - "X-Content-Type-Options: nosniff"
Note: pyserve automatically detects MIME types based on file extensions.