DEV Community

Cover image for Laravel: Force to use HTTPS for URL with Cloudflare Flexible SSL
Yegor Shytikov
Yegor Shytikov

Posted on

Laravel: Force to use HTTPS for URL with Cloudflare Flexible SSL

When are you using Cloudflare Flexible SSL you need a solution so that all URL on our website (created by URL, route function) must be HTTPS even though our server currently doesn't support SSL.

Alt Text

Solution:

Edit App\Providers\AppServiceProvider.php in the boot() method

public function boot()
{
        // custom for cloudflase flexible ssl
        if($this->checkHTTPSStatus()){
            URL::forceScheme('https');
        }
    /*...some other code...*/
}
Enter fullscreen mode Exit fullscreen mode

private function checkHTTPSStatus()
{
/Select code in an option below/
}

Option 1: Switch to https according to the configuration in the env file
Enter fullscreen mode Exit fullscreen mode

private function checkHTTPSStatus()
{
return env('APP_HTTPS',false) === true;
}

In .env file you must to declare APP_HTTPS parameter
Enter fullscreen mode Exit fullscreen mode

APP_HTTPS=true


Option 2: Automatically switch to https if the user comes from Cloudflare Flexible SSL
Enter fullscreen mode Exit fullscreen mode

private function checkHTTPSStatus()
{
return (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])&&$_SERVER['HTTP_X_FORWARDED_PROTO']==='https');
}

Option 3: Full SSL
Enter fullscreen mode Exit fullscreen mode

private function checkHTTPSStatus()
{
return !empty($_SERVER['HTTPS']);
}



Enter fullscreen mode Exit fullscreen mode

Top comments (0)