如何强制Laravel Project为所有路由使用HTTPS?

问题描述 投票:14回答:6

我正在开发一个需要安全连接的项目。

我可以设置路线,uri,资产使用'https'通过:

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

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

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

但是始终设置参数似乎很累人。

有没有办法强制所有路由生成HTTPS链接?

php ssl https routes laravel-5.2
6个回答
17
投票

你可以在'url' => 'https://youDomain.com'中设置config/app.php,或者你可以使用中间件类Laravel 5 - redirect to HTTPS


11
投票

这有几种方法。选择最方便。

  1. 配置Web服务器以将所有非安全请求重定向到https。 nginx配置示例: server { listen 80 default_server; listen [::]:80 default_server; server_name example.com www.example.com; return 301 https://example.com$request_uri; }
  2. 使用https设置环境变量APP_URLAPP_URL=https://example.com
  3. 使用助手secure_url()(Laravel5.6)
  4. 将以下字符串添加到AppServiceProvider :: boot()方法(对于版本5.4+): \Illuminate\Support\Facades\URL::forceScheme('https');

更新:

  1. 路由组的隐式设置方案(Laravel5.6): Route::group(['scheme' => 'https'], function () { // Route::get(...)->name(...); });

10
投票

将它放在boot()方法的AppServiceProvider中

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

6
投票

将其添加到.htaccess代码中

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

将www.yourdomain.com替换为您的域名。这将强制您域中的所有网址都使用https。确保在您的域上安装并配置了https证书。如果您没有看到绿色的https为安全,请在chrome上按f12并修复控制台选项卡中的所有混合错误。

希望这可以帮助!


6
投票

我在web.phpapi.php文件的末尾使用了它,它完美地工作:

URL::forceScheme('https');

4
投票

使用.htaccess文件中的以下代码会自动将访问者重定向到您网站的HTTPS版本:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
© www.soinside.com 2019 - 2024. All rights reserved.