Home >Backend Development >PHP Tutorial >How to Force HTTPS in Laravel Applications?

How to Force HTTPS in Laravel Applications?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 15:57:14995browse

How to Force HTTPS in Laravel Applications?

Redirect to HTTPS in Laravel

In Laravel, forcing HTTPS on your application can be achieved by utilizing a Middleware class. Here's a sample implementation:

namespace MyApp\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class HttpsProtocol {

    public function handle($request, Closure $next)
    {
            if (!$request->secure() && App::environment() === 'production') {
                return redirect()->secure($request->getRequestUri());
            }

            return $next($request); 
    }
}

To activate this middleware, add it to the middleware group in the Kernel.php file:

protected $middleware = [
    // ...
    'MyApp\Http\Middleware\HttpsProtocol'       
];

By default, the web middleware group is applied to all routes, so no further configuration is necessary.

Cloudflare Considerations

If you're using Cloudflare, you may encounter a redirect loop. This is because Cloudflare forwards HTTP requests with a "X-Forwarded-Proto" header indicating HTTPS. To address this, add the following line to your middleware:

$request->setTrustedProxies([$request->getClientIp()]);

This trusts the IP and header provided by Cloudflare, breaking the loop.

Updates for Laravel Versions

For Laravel versions 5.3 onwards: Add the middleware class to the "web" middleware group in the Kernel.php file.

For Laravel versions 5.7 onwards:

  • Use App::environment() instead of env('APP_ENV') for environment-based checks.
  • URL::forceScheme('https') does not redirect but merely constructs links with HTTPS.

The above is the detailed content of How to Force HTTPS in Laravel Applications?. 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