Home >Backend Development >PHP Tutorial >How to Redirect to HTTPS in Laravel 5?

How to Redirect to HTTPS in Laravel 5?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 20:11:18597browse

How to Redirect to HTTPS in Laravel 5?

Laravel 5 - Redirect to HTTPS

In Laravel 5, implementing HTTPS redirection involves utilizing either a middleware or an event listener. A middleware is a cleaner and more straightforward approach.

Using Middleware

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',
    ];

Cloudflare Considerations

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.

Environment-Based Redirection

In previous versions of Laravel, env('APP_ENV') === 'production' was used. In Laravel 5.7 and above, replace this with App::environment() === 'production'.

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn