How to force Laravel Project to use HTTPS for all

2020-02-17 06:41发布

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?

8条回答
家丑人穷心不美
2楼-- · 2020-02-17 07:06

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(...);
    });
    
查看更多
一夜七次
3楼-- · 2020-02-17 07:06

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!

查看更多
Lonely孤独者°
4楼-- · 2020-02-17 07:07
public function boot()
{
  if(config('app.debug')!=true) {
    \URL::forceScheme('https');
  }
}

in app/Providers/AppServiceProvider.php

查看更多
何必那么认真
5楼-- · 2020-02-17 07:07

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

    }
查看更多
霸刀☆藐视天下
6楼-- · 2020-02-17 07:11

Place this in the AppServiceProvider in the boot() method

if($this->app->environment('production')) {
    \URL::forceScheme('https');
}
查看更多
看我几分像从前
7楼-- · 2020-02-17 07:19

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

查看更多
登录 后发表回答