问题原文
原帖链接 · Darksworm · CC BY-SA 3.0
I need to set up NGINX so that different locations would have different expire times for caching and some would have caching disabled. This is my current setup:
fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=CACHE:200m inactive=100m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
server {
...
set $no_cache 1;
...
if ($request_uri ~* "/some/cached/route") {
set $no_cache 0;
}
...
location ~ \.php$ {
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
fastcgi_cache CACHE;
fastcgi_cache_valid 200 30m;
fastcgi_cache_bypass $no_cache;
fastcgi_no_cache $no_cache;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
...
}
With this setup I can control when the response should be cached but cannot control how long the cache will be valid.
How could I make the cache valid time variable?
已采纳解答
原帖链接 · Darksworm · CC BY-SA 4.0
Recently I ran into this limitation again.
To reiterate the problem more clearly: cache multiple different PHP responses for different lengths of time.
I came up with this hack:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ /resource/.* {
try_files $uri $uri/ //index.php?$query_string;
}
location ~ /longresource/.* {
try_files $uri $uri/ ///index.php?$query_string;
}
location ~ //index\.php$ {
fastcgi_cache resources_cache;
fastcgi_cache_valid 200 60m;
fastcgi_cache_methods GET;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ ///index\.php$ {
fastcgi_cache resources_cache;
fastcgi_cache_valid 200 180m;
fastcgi_cache_methods GET;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
This code snippet is from a laravel project, where everything goes through the index.php file.
This works because //index.php and /index.php (and the same location with any number of preceding slashes) resolves to the same file, but to a different nginx location block.
This is an utterly terrible hack production tested and not DRY at all, but it works and you can avoid using if.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
