I'm working with Craft CMS 5 using a local environment configured through DDEV, which defaults to NGINX. I typically work with Apache, so I've been adjusting my caching rules for NGINX to ensure static resources like images, CSS, and JavaScript files are properly cached. Here is the configuration I’ve implemented:
# Enable gzip compression for common text-based content
gzip on;
gzip_types text/html text/plain text/css text/javascript application/javascript application/json application/xml font/woff font/woff2;
gzip_min_length 1024;
gzip_comp_level 5;
gzip_vary on;
# Set cache control headers for all static assets (images, CSS, JavaScript, fonts)
location ~* \.(jpg|jpeg|png|gif|svg|css|js|woff|woff2|json)$ {
expires 1y;
add_header Cache-Control "public, max-age=31536000, immutable";
}
# Serve /templates/assets/js/ with cache headers via proxy
location ~* ^/templates/assets/js/(.*\.js)$ {
proxy_pass http://127.0.0.1:8080/index.php?p=assets/js/$1;
expires 1y;
add_header Cache-Control "public, max-age=31536000, immutable";
gzip on;
gzip_types application/javascript;
gzip_min_length 1024;
gzip_comp_level 5;
gzip_vary on;
}
Problem
This configuration works well for standard static assets. However, I have some JavaScript files generated dynamically through Craft CMS templates, which are served under /templates/assets/js/. For example, a file like /templates/assets/js/search.js relies on Twig templating within Craft.
Prior to adding this NGINX configuration, these files loaded correctly. Now, any attempt to access these JavaScript files results in 404 errors, as NGINX is looking for the actual files in /templates/assets/js/ rather than routing the requests to Craft's templating engine.
Attempts to Solve
- Adding specific routes in
config/routes.phpfor these JavaScript files did not resolve the issue. - Removing or adjusting the NGINX caching rules partially fixes the problem, but I lose caching for the rest of my static resources.
Question
What would be the best approach to configure NGINX to route these dynamic JavaScript files through Craft CMS without causing 404 errors, while still caching true static assets effectively?
Any guidance on modifying the NGINX configuration to handle these dynamic assets would be greatly appreciated. Thank you!
{% header ... %}tag: create/templates/assets/js/search.twigand place{% header 'Content-Type: text/javascript' %}at the top!try_filesdirective is for… When using regular expressions inlocationrules, the order of the rules also matters!