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

How to Redirect to HTTPS in Laravel 5?

Linda Hamilton
Release: 2024-12-05 20:11:18
Original
598 people have browsed it

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);
        }
    }
Copy after login

Register the middleware in the Kernel.php file:

    protected $middleware = [
        // Other middleware
        'App\Http\Middleware\HttpsProtocol',
    ];
Copy after login

Cloudflare Considerations

If using Cloudflare, you may encounter redirection loops. Add the following line to your middleware:

    $request->setTrustedProxies([$request->getClientIp()]);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template