Force Laravel to Use HTTPS Connection for all Links

Published on March 13, 2021 1 min read

Hi artisans, in this article I’ll show how to force Laravel project to use HTTPS for all links such as routes, assets. Let’s start:

Table of Contents

  1. Common Config
  2. Force HTTPS for All Routes
  3. Force HTTPS for Pagination Links

Common Config

At first, you have to ensure that you’ve set up SSL & it is working perfectly. Then open the .env file and set the HTTPS link of your website to APP_URL:

APP_URL=https://domain.com

After updating the .env file in the production server, sometimes the updated variable doesn’t show updated content. In this situation, we have to clear cache of our application.

If your application is running on Apache, force HTTPS with .htaccess:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

For Nginx server:

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

Now you can visit your website URL and check it works or not. If it doesn’t work, then follow the next steps.

Force HTTPS for All Routes

Open app/Providers/AppServiceProvider.php file and update boot() method with this:

use Illuminate\Support\Facades\URL;

public function boot()
{
    URL::forceScheme('https');
}

If can also set condition like:

// condition 1
if (env('APP_ENV') === 'production') {
    URL::forceSchema('https');
}

// condition 2
if (env('APP_ENV') !== 'local') {
    URL::forceScheme('https');
}

// condition 3
if (env('APP_FORCE_HTTPS', false)) {
    URL::forceScheme('https');
}

Force HTTPS for Pagination Links

If you notice that all routes and assets links are using HTTPS connection but pagination links are using HTTP. In this situation, add this line in the AppServiceProvider‘s boot() method:

use Illuminate\Support\Facades\URL;

public function boot()
{
    if (env('APP_ENV') === 'production') {
        $this->app['request']->server->set('HTTPS','on'); // this line

        URL::forceSchema('https');
    }
}
That’s all. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow