Search code examples
laravellaravel-artisanlaravel-middleware

Laravel maintenance mode on specific subdomain


I know that you can except some URIs of your main app like if you want to except example.com/page, you can just simply add it to the CheckForMaintenanceMode.php, like this:

In app/Http/Middleware/CheckForMaintenanceMode.php

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;

class CheckForMaintenanceMode extends Middleware
{
    /**
     * The URIs that should be reachable while maintenance mode is enabled.
     *
     * @var array
     */
    protected $except = [
        '/page'
    ];
}

Now, my app has a couple subdomains using one app; I have a subdomain for my main app: app.example.com, a subdomain for my API endpoints: api.example.com and the main website: www.example.com

How can I possibly except the specific subdomain instead of URI for maintenance mode? Like having api.example.com and app.example.com in maintenance mode but not the main website www.example.com?

I'm trying to figure out it on my own and even make my own middleware just to do this, but is it possible to do this using the built-in maintenance mode of laravel with php artisan:down?

Something like:

// app.example.com and api.example.com is in maintenance mode except:

protected $except = [
    'example.com'
    'www.example.com'
];

Solution

  • See the Illuminate\Foundation\Http\Middleware\CheckMaintenanceMode middleware class:

    It checks the elements of the $except property using the function fullUrlIs() from the Illuminate\Http\Request class, which itself calls the Str::is() helper (also known as the str_is() function if you're using Laravel helper function globals):

    protected function inExceptArray($request)
        {
            foreach ($this->except as $except) {
                if ($except !== '/') {
                    $except = trim($except, '/');
                }
    
                if ($request->fullUrlIs($except) || $request->is($except)) {
                    return true;
                }
            }
    
            return false;
        }
    

    See https://laravel.com/docs/7.x/helpers#method-str-is

    You should then be able to check for an url like this, to exclude this domain from the maintenance mode (i.e. it will always be up):

    protected $except = [
        'https://www.example.com/*'
    ];