NGINX防止在拥有FCGI的同时缓存某些位置

时间:2019-10-10 17:03:48

标签: laravel nginx caching fastcgi

我有一个Laravel应用程序。这是我的NGINX配置文件:

server {                                                                                                                                                                          
     # Log files for Debugging
     access_log /var/log/nginx/access-test.log;
     error_log /var/log/nginx/access-test.log;                                                     

     # Webroot Directory for Laravel project                         
     root /var/www/html/deploy/website/current/public;             
     index index.php index.html index.htm;

     # Your Domain Name
     server_name test.example.com;

    location / {                                      
            try_files $uri $uri/ /index.php?$query_string;
    }                                    

     # PHP-FPM Configuration Nginx                    
     location ~ \.php$ {                  
             fastcgi_split_path_info ^(.+\.php)(/.+)$;
             fastcgi_pass unix:/run/php/php7.2-fpm.sock;
             fastcgi_index index.php;      
             fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
             include fastcgi_params;
     }          

listen 443 ssl; # managed by Certbot                      
ssl_certificate /etc/letsencrypt/live/test.example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/test.example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}   

我想防止在某些位置进行任何类型的缓存,例如'/ submit/*'。

我尝试在location /上方添加此内容:

    location ~ /submit {
             expires -1;
             add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0' always;
            try_files $uri $uri/ /index.php?$query_string;
    }    

我还在我的Laravel应用中添加了中间件到/submit子路径,该子路径将Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0Expires: <one day ago>Pragma: no-cache附加到响应中。

我在浏览器中看到的是设置了ExpiresPragma标头,但是Cache-Control不是我指定的,而是被设置为max-age=31536000

我怀疑NGINX中的某些内容会覆盖该标头,但我似乎无法通过阅读文档或谷歌搜索找到它。

任何帮助或线索都会受到赞赏。

顺便说一句,我在打开检查器并在“网络”选项卡中选中Disable cache的同时,在Firefox中测试了该页面。因此,我总是从服务器上看到新鲜的标题。

2 个答案:

答案 0 :(得分:0)

您不能在要代理的位置内使用add_header。在计算响应头时,nginx位于另一个位置块中。这就是add_header的工作方式。

您可以使用add_trailerdocs here),这应该可以解决您的用例

答案 1 :(得分:0)

我终于添加了以下位置限制:

location ~ /submit {
         expires -1;
         add_trailer 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0' always;
             fastcgi_split_path_info ^(.+\.php)(/.+)$;
             fastcgi_pass unix:/run/php/php7.2-fpm.sock;
             fastcgi_index index.php;
             fastcgi_param SCRIPT_FILENAME $document_root/index.php;
             include fastcgi_params;
}

现在可以正常工作了。

现在唯一的问题是复制,可以通过在单独的文件中使用fcgi命令并在两个位置include对其进行解决。

我对当前的解决方案并不满意,因此我仍然愿意接受新的或更好的方法。