108

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?

Nelson Melecio
  • 1,334
  • 3
  • 12
  • 19

19 Answers19

143

Place this in the AppServiceProvider in the boot() method

if($this->app->environment('production')) {
    \URL::forceScheme('https');
}
Amitesh Bharti
  • 14,264
  • 6
  • 62
  • 62
  • This is a good option, instead of updating any server file. – Ishaan Oct 10 '21 at 13:11
  • 1
    Thanks it worked laravel 7 and 8 perfectly thanks again – Tarik Manoar Dec 22 '21 at 08:30
  • 1
    When I used this my email verifications no longer worked. When clicking the verification link, users would get a 403: Invalid Signature – Jacey Mar 11 '22 at 15:45
  • @AmiteshBharti can you please help me look into this question? https://stackoverflow.com/questions/72844902/deployed-laravel-website-on-digital-ocean-showing-blank-screen-and-attempting-to – Flexi Jul 05 '22 at 22:23
  • Performance-wise, does it have any effect? Since it will be executed for every single request to the website. – Vinny Jun 06 '23 at 23:45
42

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(...);
    });
    
Prisacari Dmitrii
  • 1,985
  • 1
  • 23
  • 33
  • 3
    In my Laravel 5.7.26 *`5.`* somehow disabled the website, however ***`4.`* worked as charm** :) – jave.web Apr 29 '19 at 18:07
  • I am hosting my site on HostGator and I went into the cPanel tools and modified my Laravel 5.7 code and performed number 4 and when I go to my site by just typing mysite.tech, I still get sent to the not secure verion of my site. If I implicitely type https://mysite.tech then it works. Any idea why 4 did not work? – CodeConnoisseur Jul 04 '19 at 14:58
  • `4.` Resolved the issue for me – Martin Aug 26 '22 at 12:54
40

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

URL::forceScheme('https');
insign
  • 5,353
  • 1
  • 38
  • 35
lomelisan
  • 908
  • 10
  • 15
  • I have a hostgator account hosting my laravel app. If I put this in Routes/web.php, it doesn't re route my site to https and the ssl cert is on. – CodeConnoisseur Jul 04 '19 at 14:52
  • Have you checked for a .htaccess file? You could force https redirection there too. – lomelisan Jul 04 '19 at 15:13
  • I have two htaccess files, one in my main app directory and the other in my public DIR. I added the code in the post below yours into my main app .htaccess file. Should I also add it in my public .htaccess? – CodeConnoisseur Jul 04 '19 at 15:14
  • 1
    Yeah, I think that's the one is working. Cause that's the place of the index.php file. How does your url index page end? Anyway if that doesn't work for you, HostGator has an impressive support, you could comment their answer as well. – lomelisan Jul 04 '19 at 15:18
  • So that WORKED :D, the only thing now though is that when the site reidrects it adds "/public/" to the end of the url. Do you know how I can trim that off? – CodeConnoisseur Jul 04 '19 at 15:22
37

You can set 'url' => 'https://youDomain.com' in config/app.php or you could use a middleware class Laravel 5 - redirect to HTTPS.

Community
  • 1
  • 1
Mirceac21
  • 1,741
  • 17
  • 24
  • 14
    Middleware is the way to go. Setting the 'url' property didn't work for me (L 5.1). – KalC Jul 26 '17 at 18:35
  • 2
    this is still not satisfying. It only means that routes that lead to `http` will be forwarded to `https` routes but forwarding is detrimental to SEO rankings – IceFire Dec 14 '17 at 14:13
  • 1
    This should be set by APP_URL variable in .env – cmac Feb 27 '20 at 01:11
  • I have APIs in my project will this run APIs as it is? – Rutvi Trivedi Jul 16 '20 at 10:20
  • Can someone help me look into this question please https://stackoverflow.com/questions/72844902/deployed-laravel-website-on-digital-ocean-showing-blank-screen-and-attempting-to – Flexi Jul 05 '22 at 22:24
29

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]
majid nazari
  • 440
  • 5
  • 6
24

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.
  • Did you still have to configure in `.htaccess` or this alone was enough? – Nhan Oct 28 '20 at 15:19
  • 1
    THANKS! This is the only solution worked for me, I faced this issue only on AWS Elastic Beanstalk with load balancer. I think Laravel could not generate https toutes because the connection between the load balancer and the ec2 (ubunto server) is an http. – Husam Feb 03 '21 at 17:35
  • 1
    @Nhan did not have to configure .htaccess at the time, that may have been because it was already configured properly. – Clean Code Studio Apr 14 '21 at 22:02
  • @Husam Interesting, I was working on an AWS project at the time of this post as well! That being said - if I'm remembering properly - I used this https setup in local development. I'm not sure if the other implementations didn't work because we had some AWS things happening locally or if it's just an interesting coincidence. Either way, thanks for pointing out the AWS detail! – Clean Code Studio Apr 14 '21 at 22:07
20

Add this to your .htaccess code

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]

Replace www.yourdomain.com with your domain name. This will force all the urls of your domain to use https. Make sure you have https certificate installed and configured on your domain. If you do not see https in green as secure, press f12 on chrome and fix all the mixed errors in the console tab.

Hope this helps!

10

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.

laimison
  • 1,409
  • 3
  • 17
  • 39
9

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 = '*';
glinda93
  • 7,659
  • 5
  • 40
  • 78
8
public function boot()
{
  if(config('app.debug')!=true) {
    \URL::forceScheme('https');
  }
}

in app/Providers/AppServiceProvider.php

Markos F
  • 206
  • 3
  • 4
8

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');
}
Ahsan Khan
  • 678
  • 9
  • 12
8

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.

rogramatic
  • 141
  • 1
  • 5
5

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

James Idowu
  • 223
  • 3
  • 4
5

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sakai
  • 627
  • 5
  • 10
  • 1
    For some unknown reason, this is the only thing that worked for me. `HTTPS "on"` was the only thing I needed to add, although nginx includes a line like `fastcgi_param HTTPS $https if_not_empty` but it did not work as expected, so I had to manually add this and force backend to use HTTPS; – vfsoraki Jul 28 '21 at 13:43
  • Cheers! Solved the exact problem we were having on AWS load balancer. – Springie Aug 08 '22 at 09:45
3

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);

    }
Nikolaus
  • 1,859
  • 1
  • 10
  • 16
2

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.

icalvete
  • 987
  • 2
  • 16
  • 50
1

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>
Mohamed Raafat
  • 122
  • 1
  • 5
0

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>
  • it is not enough in my case (apache proxy -> php/nginx container with laravel 8.x), I have Letsencrypt certificate and virtualhost are ok, I should configure `app/Http/Middleware/TrustProxies.php` to add local IP proxy and it should be present in `protected $middleware` in `app/Http/kernel.php` – bcag2 Feb 11 '22 at 09:53
0

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

Rubén Ruíz
  • 453
  • 4
  • 9