Working on my first Laravel 5 project and not sure where or how to place logic to force HTTPS on my app. The clincher here is that there are many domains pointing to the app and only two out of three use SSL (the third is a fallback domain, long story). So I'd like to handle this in my app's logic rather than .htaccess.
In Laravel 4.2 I accomplished the redirect with this code, located in filters.php
:
App::before(function($request)
{
if( ! Request::secure())
{
return Redirect::secure(Request::path());
}
});
I'm thinking Middleware is where something like this should be implemented but I cannot quite figure this out using it.
Thanks!
UPDATE
If you are using Cloudflare like I am, this is accomplished by adding a new Page Rule in your control panel.
An other option that worked for me, in AppServiceProvider place this code in the boot method:
The function written before forceSchema('https') was wrong, its forceScheme
This worked out for me. I made a custom php code to force redirect it to https. Just include this code on the header.php
Alternatively, If you are using Apache then you can use
.htaccess
file to enforce your URLs to usehttps
prefix. On Laravel 5.4, I added the following lines to my.htaccess
file and it worked for me.Similar to manix's answer but in one place. Middleware to force HTTPS
for laravel 5.4 use this format to get https redirect instead of .htaccess
Here's how to do it on Heroku
To force SSL on your dynos but not locally, add to end of your .htaccess in public/:
You can test this out on your local machine with:
That sets the header X-forwarded to the form it will take on heroku.
i.e. it simulates how a heroku dyno will see a request.
You'll get this response on your local machine:
That is a redirect. That is what heroku is going to give back to a client if you set the .htaccess as above. But it doesn't happen on your local machine because X-forwarded won't be set (we faked it with curl above to see what was happening).