Expired Nginx in javascript files (dynamically generated by PHP)

I have a problem with expires headers in javascript files generated by PHP.

There are two types of javascript files on the website. One part is static javascript files, and one part is dynamically generated by PHP.

conf without header expiration

Here the expires headers are added to the .js files (all files are returned by HTTP 200 )

 location / { try_files $uri $uri/ /index.php; } location ~ \.php$ { include /var/ini/nginx/fastcgi.conf; fastcgi_pass php; fastcgi_param SCRIPT_FILENAME /var/www/index.php; } 

conf expiration headers

When adding locations for .js files then all dynamically generated files return HTTP 404

 location / { try_files $uri $uri/ /index.php; } location ~ \.php$ { include /var/ini/nginx/fastcgi.conf; fastcgi_pass php; fastcgi_param SCRIPT_FILENAME /var/www/dyndev.dk/public/secure/index.php; } location ~ \.(js|css)$ { expires 1y; add_header Cache-Control "public"; } 

How to handle both static and dynamically generated .js files with expires headers?

All javascript dynamic propagation files are called *-php.js

File structure

 /var/www/public/index.php # All none-static file requests are pointed to index.php /var/www/public/js/main.js # Static files /var/www/js-dynamically_generated.php # This file is outside the public www, but is routed by PHP since the file doesn't exists inside the public /js 

PHP routing

 www.example.com/ -> index.php www.example.com/js -> static content www.example.com/js/dynamically_generated-php.js -> js-dynamically_generated.php 
+7
javascript php nginx expires-header
source share
1 answer

For nginx, PHP is never Javascript. Nginx cannot distinguish between PHP which displays html and PHP which displays javascript (please correct me if I am wrong).

Thus, one could either set up a separate folder with PHP files that generate all JS (code not verified!):

 location ~ \normal_php/.php$ { include /var/ini/nginx/fastcgi.conf; fastcgi_pass php; fastcgi_param SCRIPT_FILENAME /var/www/dyndev.dk/public/secure/index.php; } location ~ \js_php/.php$ { expires 1y; add_header Cache-Control "public"; include /var/ini/nginx/fastcgi.conf; fastcgi_pass php; fastcgi_param SCRIPT_FILENAME /var/www/dyndev.dk/public/secure/index.php; } 

... or send a header with PHP itself:

 <?php header('Expires: '. gmdate('D, d MYH:i:s \G\M\T', time() + (60 * 60))); // 1 hour 
+6
source share

All Articles