Tuesday, 6 October 2020

Laravel: Force to use HTTPS for all routes and url (Support Cloudflare Flexible SSL)

Laravel - In some special cases but especially when you are using Cloudflare Flexible SSL. We 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.

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...*/
}
private function checkHTTPSStatus()
{
/*Select code in an option below*/
}

Option 1: Switch to https according to the configuration in the env file

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

In .env file you must to declare APP_HTTPS parameter

APP_HTTPS=true

Option 2: Automatically switch to https if the user comes from Cloudflare Flexible SSL

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

Option 3: Full SSL

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

Solved !

0 nhận xét:

Post a Comment