In Laravel 5, implementing HTTPS redirection involves utilizing either a middleware or an event listener. A middleware is a cleaner and more straightforward approach.
Create a middleware class:
namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\App; class HttpsProtocol { public function handle(Request $request, Closure $next) { if (!$request->secure() && App::environment() === 'production') { return redirect()->secure($request->getRequestUri()); } return $next($request); } }
Register the middleware in the Kernel.php file:
protected $middleware = [ // Other middleware 'App\Http\Middleware\HttpsProtocol', ];
If using Cloudflare, you may encounter redirection loops. Add the following line to your middleware:
$request->setTrustedProxies([$request->getClientIp()]);
This trusts the headers CloudFlare is sending, preventing the redirect loop.
In previous versions of Laravel, env('APP_ENV') === 'production' was used. In Laravel 5.7 and above, replace this with App::environment() === 'production'.
Implementing HTTPS redirection with middleware or event listeners allows you to force HTTPS connections for your Laravel application. Remember to consider Cloudflare settings if necessary and adjust the environment-sensitive redirection accordingly.
The above is the detailed content of How to Redirect to HTTPS in Laravel 5?. For more information, please follow other related articles on the PHP Chinese website!