You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为Laravel站点配置Nginx FastCGI缓存出现空白页问题求助

Fixing Nginx FastCGI Cache Blank Pages for Laravel + Better Caching Strategies

Let’s dive into why you’re seeing blank pages (even with cache files being created) and get this sorted, then cover more Laravel-friendly caching options.

Why the Blank Page Happens (Even With Cache Files)

Your WordPress setup works because it’s simpler in how it handles output and sessions, but Laravel has specific quirks that your current Nginx config isn’t accounting for:

  • Output Buffering Mismatch: Laravel relies heavily on output buffering. With fastcgi_intercept_errors off in your config, incomplete or error responses from Laravel can get cached silently without triggering logs, resulting in blank pages.
  • Ignoring User Sessions: Your $no_cache variable is stuck at 0, so Nginx is caching responses even for authenticated users. If Laravel tries to render user-specific content but the cache doesn’t include session data, you’ll get broken/blank cached pages.
  • Insufficient Buffers: Laravel’s responses are often larger than basic PHP apps—your small buffer sizes might be truncating the response before it’s fully cached.

Updated Nginx Config for Laravel

Here’s a revised config tailored to Laravel’s needs, with explanations of key changes:

fastcgi_cache_path /tmp/cache levels=1:2 keys_zone=MYAPP:100m inactive=60m;
# Include Laravel session cookies in cache key to avoid mixing authenticated/anonymous content
fastcgi_cache_key "$scheme$request_method$host$request_uri$cookie_laravel_session$cookie_XSRF-TOKEN";

server {
    listen 80;
    listen [::]:80;
    server_name site.com www.site.com;
    root /var/www/site/public;
    index index.php index.html index.htm;

    # Smart cache bypass logic for Laravel
    set $no_cache 0;
    # Bypass cache for POST requests (dynamic actions)
    if ($request_method = POST) {
        set $no_cache 1;
    }
    # Bypass cache for users with active Laravel sessions/XSRF tokens
    if ($http_cookie ~* "laravel_session|XSRF-TOKEN") {
        set $no_cache 1;
    }

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt { access_log off; log_not_found off; }

    access_log off;
    error_log /var/log/nginx/myapp-error.log error;
    sendfile off;
    client_max_body_size 100m;

    location ~ \.php$ {
        fastcgi_cache MYAPP;
        fastcgi_cache_valid 200 60m;
        fastcgi_cache_methods GET HEAD;
        add_header X-Fastcgi-Cache $upstream_cache_status;

        fastcgi_cache_bypass $no_cache;
        fastcgi_no_cache $no_cache;

        # Catch Laravel's internal errors and log them properly
        fastcgi_intercept_errors on;

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        # Add parameters Laravel expects for path handling
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param HTTP_PROXY "";

        # Larger buffers to handle Laravel's full response output
        fastcgi_buffer_size 32k;
        fastcgi_buffers 8 32k;
    }

    location ~ /\.ht { deny all; }
}

Key fixes in this config:

  1. Cache Key Adjustment: Includes Laravel’s session and XSRF cookies to ensure authenticated users don’t get cached anonymous pages.
  2. Smart Cache Bypass: Skips caching for POST requests and logged-in users, which prevents broken dynamic content.
  3. Error Interception: Enables fastcgi_intercept_errors on to catch and log Laravel’s internal errors, so you won’t get silent blank pages.
  4. Increased Buffers: Larger buffer sizes ensure Laravel’s full response is cached properly.

Better Caching Strategies for Laravel

While Nginx FastCGI cache works, Laravel has native tools that integrate more seamlessly with your app:

  • Custom Cache Middleware: Build a middleware to cache responses directly in Laravel, giving you full control over which routes are cached and when to bypass. Example:
    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Cache;
    use Illuminate\Support\Facades\Auth;
    
    class CachePublicRoutes
    {
        public function handle($request, Closure $next)
        {
            // Skip cache for authenticated users
            if (Auth::check()) {
                return $next($request);
            }
    
            $cacheKey = 'route-cache:' . md5($request->fullUrl());
            if (Cache::has($cacheKey)) {
                return response(Cache::get($cacheKey));
            }
    
            $response = $next($request);
            // Cache public pages for 60 minutes
            Cache::put($cacheKey, $response->getContent(), 60);
            return $response;
        }
    }
    
  • Laravel Octane: For newer Laravel versions, Octane uses Swoole/RoadRunner to keep your app in memory, delivering massive performance gains without needing external page cache for most routes.
  • Database/Query Caching: Use Laravel’s built-in Redis or Memcached driver to cache frequent database queries, configs, and computed data—pair this with route caching for full-page speed.
  • Edge Caching: For static assets and public pages, use a CDN to cache content at the edge, reducing server load even more than Nginx cache.

内容的提问来源于stack exchange,提问作者spdude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:20:59