Home >Backend Development >PHP Tutorial >How to Force HTTPS in Laravel 5 Using Middleware?
In Laravel 5, you can enforce HTTPS for your application using a Middleware class. Here's how you can achieve this:
Middleware Class:
namespace MyApp\Http\Middleware; use Closure; class HttpsProtocol { public function handle($request, Closure $next) { if (!$request->secure()) { return redirect()->secure($request->getRequestUri()); } return $next($request); } }
Applying Middleware:
The next step is to apply this Middleware to all incoming requests. In the Kernel.php file, add it to the $middleware array:
protected $middleware = [ // Existing middleware... // Custom middleware 'MyApp\Http\Middleware\HttpsProtocol', ];
Production Environment Validation:
The provided middleware redirects all HTTP requests to HTTPS, but you may want to limit this behavior to production environments only. You can do this by checking the application environment:
if (!$request->secure() && App::environment() === 'production') { return redirect()->secure($request->getRequestUri()); }
Cloudflare Considerations:
If you're using Cloudflare, you may encounter a redirect loop because Cloudflare forwards requests using HTTP. To fix this, add the following line to your Middleware:
$request->setTrustedProxies([$request->getClientIp()]);
Web Group (Laravel v5.3 ):
Instead of adding it to the $middleware array, you can add it to the web group in Kernel.php:
protected $middlewareGroups = [ 'web' => [ // ... // Custom middleware 'MyApp\Http\Middleware\HttpsProtocol', ], ];
Remember that the web group is applied to all routes by default.
Additional Notes:
The above is the detailed content of How to Force HTTPS in Laravel 5 Using Middleware?. For more information, please follow other related articles on the PHP Chinese website!