我在serverfault上问了这个问题,但没有人回答。希望,stackoverflow人更了解Nginx:)
我想处理从缓存到/ api的所有[GET]请求,并处理所有其他请求,就像在最后一个位置块(没有缓存)一样。使用PUT,POST,DELETE方法对/ api的所有请求也都不能使用缓存。
我看到了类似的问题here,但在我的案例中仍然无法理解如何使用它。
提前致谢。
我的配置:
location / {
root /var/www/project/web;
# try to serve file directly, fallback to app.php
try_files $uri /app.php$is_args$args;
}
location ~ ^/api {
root /var/www/project/web/app.php;
fastcgi_send_timeout 600s;
fastcgi_read_timeout 600s;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/?.*)$;
include fastcgi_params;
fastcgi_cache fcgi;
fastcgi_cache_valid 200 5m;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
}
location ~ ^/(app|app_dev|config)\.php(/|$) {
root /var/www/project/web;
fastcgi_send_timeout 600s;
fastcgi_read_timeout 600s;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/?.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
}
答案 0 :(得分:6)
谢天谢地,这很简单。 Nginx的模块(proxy,fastcgi,uwsgi等)都能够通知请求不使用缓存。
location ~ ^/api {
root /var/www/project/web/app.php;
fastcgi_send_timeout 600s;
fastcgi_read_timeout 600s;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/?.*)$;
include fastcgi_params;
# Don't cache anything by default
set $no_cache 1;
# Cache GET requests
if ($request_method = GET)
{
set $no_cache 0;
}
fastcgi_cache_bypass $no_cache;
fastcgi_no_cache $no_cache;
fastcgi_cache fcgi;
fastcgi_cache_valid 200 5m;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
}
根据Richard Smith的建议,使用maps指令的更优雅的解决方案如下:
map $request_method $api_cache_bypass {
default 1;
GET 0;
}
location ~ ^/api {
root /var/www/project/web/app.php;
fastcgi_send_timeout 600s;
fastcgi_read_timeout 600s;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/?.*)$;
include fastcgi_params;
fastcgi_cache_bypass $api_cache_bypass;
fastcgi_no_cache $api_cache_bypass;
fastcgi_cache fcgi;
fastcgi_cache_valid 200 5m;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
}
该位置的添加实质上是告诉Nginx使用或忽略缓存,具体取决于动词。它将$ no_cache设置为1,它将绕过所有请求的缓存,除非该方法是GET,当它设置为0时指示它使用缓存(如果可用)。