Home >Backend Development >PHP Tutorial >How to Force HTTPS in Laravel Applications?
In Laravel, forcing HTTPS on your application can be achieved by utilizing a Middleware class. Here's a sample implementation:
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); } }
To activate this middleware, add it to the middleware group in the Kernel.php file:
protected $middleware = [ // ... 'MyApp\Http\Middleware\HttpsProtocol' ];
By default, the web middleware group is applied to all routes, so no further configuration is necessary.
If you're using Cloudflare, you may encounter a redirect loop. This is because Cloudflare forwards HTTP requests with a "X-Forwarded-Proto" header indicating HTTPS. To address this, add the following line to your middleware:
$request->setTrustedProxies([$request->getClientIp()]);
This trusts the IP and header provided by Cloudflare, breaking the loop.
For Laravel versions 5.3 onwards: Add the middleware class to the "web" middleware group in the Kernel.php file.
For Laravel versions 5.7 onwards:
The above is the detailed content of How to Force HTTPS in Laravel Applications?. For more information, please follow other related articles on the PHP Chinese website!