Laravel 5.2 – Forcing HTTPS Routes when using SSL
January 31, 2016 by Jeff Mould 23 Comments
There is an increasing push for privacy and security on the web and a lot of this starts with sites using SSL to encrypt their traffic. With SSL certificates now free from companies like Amazon recently launching their AWS Certificate Manager and initiatives like Let’s Encrypt there really is no reason now that sites should not have SSL.
This article though is not about encryption, installing SSL, or your need for SSL in general. Instead I want to focus on after you have chosen to implement SSL on your site. Particularly if you are using AWS Certificate Manager (ACM) with an Amazon Elastic Load Balancer (ELB) in front of a Laravel 5.2 site. You may like many others choose to keep it simple and have the ELB forward port 443 (HTTPS) to port 80 (HTTP) on your EC2 instance. In this case there you may not have a certificate residing on the EC2 instance(s) and you may not have the EC2 instance configured to handle requests on port 443. If you are using Laravel 5.2 this may present some challenges. Since Laravel 5.2 only sees the HTTP traffic, it builds the links with http instead of with https. This will create problems as you will now have unsecure links being shown on your site.
Luckily the fix for this is fairly simply. You can simply add three lines of code to the AppServiceProvider.php file and presto all your links will now be created using HTTPS instead of HTTP.
代碼: 選擇全部
public function boot()
{
if (!\App::environment('local')) {
\URL::forceSchema('https');
}
}