Static File Offload with Nginx and Kestrel

AspNet Core’s Kestrel webserver is making great leaps and bounds in performance however it is still suggested to offload serving static files where possible. If you’ve set up Nginx to act as a reverse proxy which Microsoft currently suggest you should do for production, those requests are going to be handled by Nginx initially anyway, so why not get it to serve up those static files for you?

Configuration

Fortunately the configuration to do this is fairly easy by editing the Nginx config for your site. Assuming you’ve created a new AspNet Core web application in the path /var/www/demo/ by running

dotnet new -t web

Your minimalist Nginx config might look something like this:

server {                                           
        listen 80 default_server;                  
        listen [::]:80 default_server;             
                                                   
        server_name _;                             
                                                   
        location / {                               
                proxy_pass http://127.0.0.1:5000/; 
                include /etc/nginx/proxy_params;   
        } 
}                                                  

To add static file offload for one of your directories (for example images) I’ve added the /images/ location show below.

server {                                           
        listen 80 default_server;                  
        listen [::]:80 default_server;             
                                                   
        server_name _;                             
                                                   
        location / {                               
                proxy_pass http://127.0.0.1:5000/; 
                include /etc/nginx/proxy_params;   
        }
                                                           
        location /images/ {                        
                root /var/www/demo/wwwroot;        
        }                                          
}                                                  

Security

Nginx uses the root to block off directory traversal to prevent malicious hackers asking for an image like ../../../my-super-secret-stuff, to set the root at the appropriate level.

Trouble-shooting

Although this all seems very straight-forward if you have any problems the Nginx error log file is very instructive. The location of this is controlled in the nginx.conf file and defaults to /var/log/nginx/error.log

Final Thoughts

As with all things performance, YMMV, measure twice and cut once, and all that.

Photo Credit Adam Singer