cla*_*rkk 7 javascript php nginx expires-header
我有一个expires由PHP生成的javascript文件的标题问题..
该网站有两种类型的JavaScript文件.一部分是静态javascript文件,一部分是由PHP动态生成的.
这里没有expires标题添加到.js文件中(所有文件都返回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;
}
Run Code Online (Sandbox Code Playgroud)
为.js文件添加位置时,将返回所有动态生成的文件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";
}
Run Code Online (Sandbox Code Playgroud)
如何.js使用expires标头处理静态和动态生成的文件?
所有动态生成的javascript文件都被命名 *-php.js
/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
Run Code Online (Sandbox Code Playgroud)
www.example.com/ -> index.php
www.example.com/js -> static content
www.example.com/js/dynamically_generated-php.js -> js-dynamically_generated.php
Run Code Online (Sandbox Code Playgroud)
对于nginx,PHP绝不是Javascript.Nginx无法区分呈现html的PHP和呈现javascript的PHP(如果我错了请纠正我).
所以要走的路要么是设置一个单独的文件夹,其中包含生成所有JS的PHP文件(代码未经过测试!):
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;
}
Run Code Online (Sandbox Code Playgroud)
...或者使用PHP本身发送标题:
<?php
header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); // 1 hour
Run Code Online (Sandbox Code Playgroud)