Docker环境下Nginx无法提供CSS/JS服务的配置问题求助
Hey there! Let's get this Nginx + PHP-FPM issue sorted out so your CSS and JS files load properly. That error message gives us the key clue: your Nginx setup is sending static assets (like styles.css) to PHP-FPM, but PHP's security.limit_extensions security setting blocks access to non-script files. Here's how to fix it:
The core problem is that your Nginx server block is forwarding every request to PHP-FPM—even static files that Nginx can serve directly. You need to update the config to only pass PHP-related files upstream, and handle static assets on its own.
Here's a corrected example server block you can adapt:
server { listen 80; root /var/www/sites/public; index index.php index.html index.htm; # Serve static files directly (skips PHP-FPM entirely) location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ { expires 1y; add_header Cache-Control "public, immutable"; } # Only send PHP files to PHP-FPM location ~ \.php$ { fastcgi_pass 172.21.0.3:9000; # Replace with your PHP-FPM container IP/hostname fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
- The
location ~* \.(css|js|...)$block tells Nginx to handle these static files directly, which is faster and avoids the PHP security block. - The
location ~ \.php$block only forwards files ending with.phpto PHP-FPM—exactly what we want.
security.limit_extensions (Trust Me) By default, PHP-FPM's security.limit_extensions is set to only allow .php and related script extensions. This is a critical security feature that prevents PHP from executing arbitrary files (like a maliciously uploaded .css file with hidden PHP code). Do NOT add .css or .js to this list—that's a bad idea. The real fix is getting Nginx to stop sending static files to PHP-FPM in the first place.
If you're curious to check the setting anyway, you can look at your PHP-FPM pool config (usually www.conf in /usr/local/etc/php-fpm.d/ or /etc/php/<your-version>/fpm/pool.d/):
security.limit_extensions = .php .php3 .php4 .php5 .php7
Leave this as-is.
After updating the config, apply the changes by reloading Nginx:
# If using docker-compose docker-compose exec nginx nginx -s reload # For a standalone Nginx container docker exec <your-nginx-container-name> nginx -s reload
If reload doesn't work, just restart the Nginx container entirely.
Most likely your original Nginx config had a catch-all location / block (like try_files $uri $uri/ /index.php?$query_string;) without excluding static files, or the order of your location blocks was wrong. Nginx processes regex location blocks first, so putting the static file block before the PHP block ensures static assets are handled correctly.
内容的提问来源于stack exchange,提问作者ticking-inceptor

