Bypass FastCGI Cache When Authorization Header

烈酒焚心 提交于 2020-03-05 01:34:06

问题


I have implemented FastCGI caching in Nginx for a Laravel API app but I realized I don't want endpoints that return user-related data to be cached. I'm using JWT Auth and I passing the token as Authorization: Bearer ... in the headers in order to authenticate user requests. I couldn't figure out a way to disable FastCGI cache if this header is present in the request. This is what I have in my Nginx:

fastcgi_cache_path /etc/nginx-cache levels=1:2 keys_zone=phpcache:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

location ~ \.php$ {
  try_files $uri /index.php =404;
  fastcgi_pass php-upstream;
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  include fastcgi_params;
  fastcgi_read_timeout 600;
  fastcgi_cache phpcache; # The name of the cache key-zone to use
  fastcgi_cache_key $scheme$host$request_uri$request_method;
  fastcgi_cache_valid 200 30s;
  fastcgi_cache_methods GET HEAD; # What to cache: only GET and HEAD requests (not POST)
  add_header X-Fastcgi-Cache $upstream_cache_status; # Add header so we can see if the cache hits or misses
  fastcgi_cache_use_stale updating error timeout invalid_header http_500;
  fastcgi_pass_header Set-Cookie;
  fastcgi_pass_header Cookie;
  fastcgi_hide_header X-Powered-By;
  fastcgi_cache_lock on;
  fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
  include fastcgi_params;
  fastcgi_cache_bypass $no_cache;
  fastcgi_no_cache $no_cache;
}

#Cache everything by default
set $no_cache 0;

#Don't cache the following URLs
if ($request_uri ~* "/admin/)")
{
  set $no_cache 1;
}

I have also added this to my .htaccess

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

回答1:


I think I figured it out. I modified these lines and now it's ignoring those requests that has Authorization in the header:

fastcgi_cache_bypass $no_cache $http_authorization;
fastcgi_no_cache $no_cache $http_authorization;


来源:https://stackoverflow.com/questions/60378224/bypass-fastcgi-cache-when-authorization-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!