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

How to Force HTTPS in Laravel Applications?

Linda Hamilton
Release: 2024-12-11 15:57:14
Original
994 people have browsed it

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

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

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

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

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!

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