How to force HTTPS on Laravel for all routes? Using Different Methods to make URLs secure

In this article I’ll show how to force Laravel project to use HTTPS for all links such as routes, assets. Some of the codes are taken from scratchcoding Laravel Code Examples. Let’s start to find out different methods of how to force https on laravel:

Do not forget to clear Laravel cache after making below changes.

AppServiceProvider in the boot()

Place this in the AppServiceProvider in the boot() method

File Path: app->providers->AppServiceProvider.php

if($this->app->environment('production')) {
    \URL::forceScheme('https');
}

Configure your web server

Configure your web server to redirect all non-secure requests to https. Example of a nginx config:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}

web.php or api.php

use the following line at the end of the web.php or api.php file and it worked perfectly:

File Path : routes->web.php / routes->api.php

URL::forceScheme('https');

config/app.php

You can set 'url' => 'https://youDomain.com' in config/app.php

.htaccess

Using the following code in your .htaccess file automatically redirects visitors to the HTTPS version of your site:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

.env

In your .env file, just use

FORCE_HTTPS=true

App\Http\Middleware\TrustProxies.php

For laravel 8, if you tried all of the above methods but got browser redirected you too many times error, please set proxies in TrustProxies middleware like the following:

/**
  * The trusted proxies for this application.
  *
  * @var array|string|null
*/
protected $proxies = '*';