Basic File Serving
By default, Nginx serves files from its standard web root directory. Placing a file, for instance archive.zip, inside a subfolder such as data/ within the root allows direct access via URL. Navigating to http://yourdomain:8080/data/archive.zip will initiate a download for most file types.
Forcing File Downloads
Certain file formats, like images or PDFs, are rendered directly in the browser instead of being downloaded. To enforce a download prompt, append the Content-Disposition header to the specific location block.
location /data {
add_header Content-Disposition "attachment;";
}This ensures that any request targeting the /data path triggers a download action rather than inline rendering.
Modifying the Storage Directory
To serve files from a directory outside the default installation path, modify the root directive within the desired location block. For example, to map requests to the /srv/files directory:
location / {
root /srv/files;
index index.html index.htm;
}Complete Configuration Example
Below is a consolidated Nginx configuration demonstrating a file server listening on port 9090, serving custom directories, and enforcing downloads for a specific path.
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 9090;
server_name localhost;
location / {
root /srv/files;
index index.html index.htm;
}
location /downloads {
root /srv/files;
add_header Content-Disposition "attachment;";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}