Home >Backend Development >PHP Tutorial >How to Redirect All Laravel 5 Requests to HTTPS with Domain Exceptions?
Question: How do I redirect all requests to HTTPS in a Laravel 5 application, while allowing exceptions for specific domains?
Answer:
To enforce HTTPS redirection, you can utilize a Middleware class. Here's how:
namespace MyApp\Http\Middleware; use Closure; use Illuminate\Support\Facades\App; class HttpsProtocol { public function handle($request, Closure $next) { // In production environment, redirect non-secure requests if (!$request->secure() && App::environment() === 'production') { return redirect()->secure($request->getRequestUri()); } return $next($request); } }
Application:
Register the middleware in the Kernel.php file:
protected $middleware = [ ... 'MyApp\Http\Middleware\HttpsProtocol', ];
Cloudflare Configuration:
If you're using Cloudflare, you may encounter a redirect loop. To resolve this:
Add the following line to your middleware:
$request->setTrustedProxies([$request->getClientIp()]);
In Cloudflare's control panel, create a new Page Rule:
Laravel v5.3 and Later:
For Laravel v5.3 and later, simply include the middleware in the web group:
protected $middlewareGroups = [ 'web' => [ ... 'MyApp\Http\Middleware\HttpsProtocol' ], ];
Other Notes:
The above is the detailed content of How to Redirect All Laravel 5 Requests to HTTPS with Domain Exceptions?. For more information, please follow other related articles on the PHP Chinese website!