To optimize Nginx for serving static assets such as images, CSS, and JavaScript files, you can follow these steps:
gzip on;
gzip_static on;
gzip_types text/plain text/css application/javascript image/svg+xml;
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires max;
log_not_found off;
access_log off;
}
listen 443 ssl http2;
tcp_nodelay on;
tcp_nopush on;
keepalive_timeout 30;
try_files
directive to check if the file exists and serve it directly, or pass the request to the backend server. Here's an example configuration:location /static/ {
try_files $uri $uri/ =404;
}
Ensure that you update the path according to your specific setup.
Enable SSL/TLS: If you're serving static assets over HTTPS, enable SSL/TLS encryption to secure the data transmission. Add the necessary SSL certificate and update the Nginx configuration accordingly.
Utilize a CDN: Consider using a Content Delivery Network (CDN) to offload the static asset delivery to edge servers closer to the end-users. A CDN can help improve the load time and reduce the load on your Nginx server.
Don't forget to reload or restart Nginx after making the changes to apply the optimizations.