Skip to content

Instantly share code, notes, and snippets.

@olimortimer
Last active May 5, 2025 00:07
Show Gist options
  • Save olimortimer/3fc2347008402b51d564258d0d190b54 to your computer and use it in GitHub Desktop.
Save olimortimer/3fc2347008402b51d564258d0d190b54 to your computer and use it in GitHub Desktop.
Laravel: Bypass Maintenance Mode with Header Set Secret
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Http\MaintenanceModeBypassCookie;
class HeaderBypassForMaintenance
{
/**
* Handle an incoming request and allow bypassing Laravel maintenance mode
* via a custom HTTP header (X-MAINTENANCE-BYPASS), using the same secret
* as Laravel's native maintenance bypass.
*/
public function handle(Request $request, Closure $next): Response
{
// Check if the application is currently in maintenance mode
if (app()->isDownForMaintenance()) {
// Get the secret token from the custom header
$headerSecret = $request->header('X-MAINTENANCE-BYPASS');
// Path to Laravel's maintenance mode data file
$downFile = storage_path('framework/down');
// Ensure the maintenance file exists
if (file_exists($downFile)) {
// Decode the contents of the down file to get the Laravel-generated secret
$data = json_decode(file_get_contents($downFile), true);
$laravelSecret = $data['secret'] ?? null;
// If the header token matches Laravel's maintenance secret, allow the request
if ($headerSecret === $laravelSecret) {
// Create a valid cookie value (signed)
$cookie = MaintenanceModeBypassCookie::create($headerSecret);
// Inject directly into the request
$request->cookies->set('laravel_maintenance', $cookie->getValue());
return $next($request);
}
// For normal browsing, pass through to the next middleware
// Let Laravel's PreventRequestsDuringMaintenance handle the maintenance display
return $next($request);
}
// If maintenance file doesn't exist but app reports maintenance mode
throw new HttpException(503, 'Service Unavailable');
}
// If not in maintenance mode, continue as usual
return $next($request);
}
}
[...]
protected $middleware = [
[...]
\App\Http\Middleware\HeaderBypassForMaintenance::class,
\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
[...]
];
[...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment