Static Files
Nexios provides a simple way to serve static files, such as images, JavaScript, CSS, and other assets, using the StaticFilesHandler
. This handler maps a URL path to a directory on the filesystem and ensures that only safe files are served.
Setting Up Static File Handling
To serve static files in a Nexios application, you need to initialize and mount the StaticFilesHandler
with a specific directory and URL prefix.
Usage Example
Understanding the StaticFilesHandler
StaticFilesHandler
The StaticFilesHandler
is responsible for serving files from a specified directory while ensuring security and accessibility.
Constructor
directory
(str | Path) – The directory containing static files.url_prefix
(str) – The URL prefix under which static files are served. Defaults to/static/
.
Directory Validation
If the specified directory does not exist, it will be created automatically.
If the given path is not a directory, an error is raised.
Security Measures
To prevent unauthorized access to sensitive files, StaticFilesHandler
performs security checks:
Path Validation
Ensures the requested file is within the specified directory.
Prevents directory traversal attacks (e.g.,
../../etc/passwd
).
Safe Path Resolution
This ensures that only files within the allowed directory are served.
Request Handling
When a request is made to access a static file:
File Existence Check If the requested file does not exist or is not a valid file, it returns:
with a
404 Not Found
status.Serving the File If the file exists and is valid, it is served with
inline
content disposition:
Example Request
Assume we have a file at static/logo.png
and the StaticFilesHandler
is set up with /static/
as the URL prefix.
Request:
Response:
The server returns the file logo.png
if it exists, otherwise a 404 response.
Last updated