How to force Laravel Project to use HTTPS for all routes?

Viewed 252909

I am working on a project that requires a secure connection.

I can set the route, uri, asset to use 'https' via:

Route::get('order/details/{id}', ['uses' => 'OrderController@details', 'as' => 'order.details', 'https']);

url($language.'/index', [], true)

asset('css/bootstrap.min.css', true)

But setting the parameters all the time seems tiring.

Is there a way to force all routes to generate HTTPS links?

19 Answers

Place this in the AppServiceProvider in the boot() method

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

Here are several ways. Choose most convenient.

  1. 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;
    }
    
  2. Set your environment variable APP_URL using https:

    APP_URL=https://example.com
    
  3. Use helper secure_url() (Laravel5.6)

  4. Add following string to AppServiceProvider::boot() method (for version 5.4+):

    \Illuminate\Support\Facades\URL::forceScheme('https');
    

Update:

  1. Implicitly setting scheme for route group (Laravel5.6):

    Route::group(['scheme' => 'https'], function () {
        // Route::get(...)->name(...);
    });
    

I used this at the end of the web.php or api.php file and it worked perfectly:

URL::forceScheme('https');

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]

Force Https in Laravel 7.x (2020)


"2020 Update? Url::forceScheme was acting funky for me, but this worked liked a dime."


  1. https code snippet.

    resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');


  1. Add that snippet within any Service Provider Boot Method

  • 1: Open app/providers/RouteServiceProvider.php.
  • 2: Then add the https code snippet to the boot method.
    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');

        parent::boot();
    }
  • 3: Lastly run php artisan route:clear && composer dumpautoload to clear Laravel's cached routes and cached Service Providers.

I would prefer forceScheme instead of doing it on a web server. So Laravel app should be responsible for it.

So right way is to add if statement inside boot function in your app/Providers/AppServiceProvider.php

    if (env('APP_ENV') === 'production') {
        \Illuminate\Support\Facades\URL::forceScheme('https');
    }

Tip: to prove that you have APP_ENV configured correctly. Go to your Linux server, type env

This was tested on Laravel 5, specifically 5.6.

public function boot()
{
  if(config('app.debug')!=true) {
    \URL::forceScheme('https');
  }
}

in app/Providers/AppServiceProvider.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:

App\Http\Middleware\TrustProxies.php

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

In your .env file, just use

FORCE_HTTPS=true

This worked for me and you can also together set APP Url to https://your-site.com as an additional step

I figured out how to do this in a load-balanced infrastructure.

You need to add in you Nginx config:

location ~ \.php$ {
            include snippets/fastcgi-php.conf;
    #       # With php-fpm (or other unix sockets):
            fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;

            add_header X-Forwarded-Proto https;
            add_header X-Forwarded-Port 443;
            add_header Ssl-Offloaded "1";
            add_header Access-Control-Allow-Origin "*";
            fastcgi_param  HTTPS "on";
            fastcgi_param  HTTP_X_FORWARDED_PROTO "https";
    }

The importer pieces are the add_headers and pastcgi_params, it works like a charm through an AWS load balancer.

Here's another option, this works on laravel 8.*. I'm not sure of lower versions though:

Add the ASSET_URL variable to your .env file.

For example:

ASSET_URL=https://secure-domain.com

You can find more info here: Laravel Helpers

Hint: pay attention to the comments in the link above.

try this - it will work in RouteServiceProvider file

    $url = \Request::url();
    $check = strstr($url,"http://");
    if($check)
    {
       $newUrl = str_replace("http","https",$url);
       header("Location:".$newUrl);

    }

The better way to solute this issue is : -> go to public folder, ->edit .htaccess just add this code below :

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

-> and save. -> close and re-open browser.

Add this before the class name of this file app\Providers\AppServiceProvider.php

use Illuminate\Support\Facades\URL;

Then paste this code inside the boot function of app\Providers\AppServiceProvider.php file

if (config('app.env') === 'production') {
    URL::forceScheme('https');
}

What about just using .htaccess file to achieve https redirect? This should be placed in project root (not in public folder). Your server needs to be configured to point at project root directory.

<IfModule mod_rewrite.c>
   RewriteEngine On
   # Force SSL
   RewriteCond %{HTTPS} !=on
   RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
   # Remove public folder form URL
   RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

I'm using Apache server, the most efficient I think just change the virtual host configuration. Change it like this

<VirtualHost *:80>
   ServerName www.yourdomain.com
   Redirect / https://www.yourdomain.com
</VirtualHost>

<VirtualHost _default_:443>
   ServerName www.yourdomain.com
   DocumentRoot /usr/local/apache2/htdocs
   SSLEngine On
# etc...
</VirtualHost>

Use the function secure_url() from laravel 5.2

$url = secure_url('user/profile');

{{ secure_url('your-link') }} //instead url()

reference laravel secure_url() function

Related