Laravel 5 - redirect to HTTPS
You can make it works with a Middleware class. Let me give you an idea.
namespace MyApp\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class HttpsProtocol {
public function handle($request, Closure $next)
{
if (!$request->secure() && App::environment() === 'production') {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Then, apply this middleware to every request adding setting the rule at Kernel.php
file, like so:
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
// appending custom middleware
'MyApp\Http\Middleware\HttpsProtocol'
];
At sample above, the middleware will redirect every request to https if:
- The current request comes with no secure protocol (http)
- If your environment is equals to
production
. So, just adjust the settings according to your preferences.
Cloudflare
I am using this code in production environment with a WildCard SSL and the code works correctly. If I remove && App::environment() === 'production'
and test it in localhost, the redirection also works. So, having or not a installed SSL is not the problem. Looks like you need to keep a very hard attention to your Cloudflare layer in order to get redirected to Https protocol.
Edit 23/03/2015
Thanks to @Adam Link
's suggestion: it is likely caused by the headers that Cloudflare is passing. CloudFlare likely hits your server via HTTP and passes a X-Forwarded-Proto header that declares it is forwarding a HTTPS request. You need add another line in your Middleware that say...
$request->setTrustedProxies( [ $request->getClientIp() ] );
...to trust the headers CloudFlare is sending. This will stop the redirect loop
Edit 27/09/2016 - Laravel v5.3
Just need to add the middleware class into web
group in kernel.php file
:
protected $middlewareGroups = [
'web' => [
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// here
\MyApp\Http\Middleware\HttpsProtocol::class
],
];
Remember that
web
group is applied to every route by default, so you do not need to setweb
explicitly in routes nor controllers.
Edit 23/08/2018 - Laravel v5.7
- To redirect a request depending the environment you can use
App::environment() === 'production'
. For previous version wasenv('APP_ENV') === 'production'
. - Using
\URL::forceScheme('https');
actually does not redirect. It just builds links withhttps://
once the website is rendered.
Laravel Redirect Http to Https
I solved with htaccess
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Redirect http to https in laravel 5.2
Your HTTP to HTTPS redirect needs to go near the top of your .htaccess
file, immediately after the RewriteEngine
directive and, importantly, before the Laravel front controller.
As a general rule, external redirects should always go before internal rewrites.
The front controller catches all requests (or rather requests that don't map to a physical file or directory) and rewrites these to index.php
(that ultimately handles the routeing). The problem is that your HTTP to HTTPS redirect occurs later and converts the now rewritten URL into an external redirect to index.php
.
Likewise, your # Handle Authorization Header
block should also go before the front controller (ideally). (It will work in its current state, in per-directory .htaccess
files, due to the looping nature of .htaccess
files, but if you moved these directives to the server config it would fail.)
Laravel redirect to action with https
The basic Laravel redirect to a controller action or a named route, was always going to HTTP instead of https. To get around this, I did a full URL redirect, like this:
return redirect()->to(env('APP_URL').'/login/ajax?email='.urlencode($request->email).'&password='.urlencode($request->password).'®ister_form=true');
This solved the issue for me.
How to force Laravel Project to use HTTPS for all routes?
You can set 'url' => 'https://youDomain.com'
in config/app.php
or you could use a middleware class Laravel 5 - redirect to HTTPS.
Related Topics
Are PHP Variables Passed by Value or by Reference
How to Find Out If You'Re Using Https Without $_Server['Https']
How to Increase the Execution Timeout in PHP
Having Issue With Matching Rows in the Database Using Pdo
How to Check Whether an Array Is Empty Using PHP
How to Extend Access Token Validity Since Offline_Access Deprecation
How to Create an Array from a CSV File Using PHP and the Fgetcsv Function
PHP Passing $_Get in the Linux Command Prompt
Reading Very Large Files in PHP
PHP/MySQL Insert Row Then Get 'Id'
How to Make a PHP Soap Call Using the Soapclient Class
Performance of Foreach, Array_Map With Lambda and Array_Map With Static Function
Html Element Array, Name="Something[]" or Name="Something"
Print Numeric Values to Two Decimal Places
Delete Directory With Files in It
How to Post Json to PHP With Curl
Diagnosing Memory Leaks - Allowed Memory Size of # Bytes Exhausted