Home > Backend Development > PHP Tutorial > How to Redirect All Laravel 5 Requests to HTTPS with Domain Exceptions?

How to Redirect All Laravel 5 Requests to HTTPS with Domain Exceptions?

Mary-Kate Olsen
Release: 2024-12-04 21:13:13
Original
398 people have browsed it

How to Redirect All Laravel 5 Requests to HTTPS with Domain Exceptions?

Laravel 5: Enforce HTTPS Redirection

Question: How do I redirect all requests to HTTPS in a Laravel 5 application, while allowing exceptions for specific domains?

Answer:

To enforce HTTPS redirection, you can utilize a Middleware class. Here's how:

namespace MyApp\Http\Middleware;

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

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

        return $next($request);
    }
}
Copy after login

Application:

Register the middleware in the Kernel.php file:

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

Cloudflare Configuration:

If you're using Cloudflare, you may encounter a redirect loop. To resolve this:

  1. Add the following line to your middleware:

    $request->setTrustedProxies([$request->getClientIp()]);
    Copy after login
  2. In Cloudflare's control panel, create a new Page Rule:

    • Match URL: *
    • Settings: Always Use HTTPS

Laravel v5.3 and Later:

For Laravel v5.3 and later, simply include the middleware in the web group:

protected $middlewareGroups = [
    'web' => [
        ...
        'MyApp\Http\Middleware\HttpsProtocol'
    ],
];
Copy after login

Other Notes:

  • Ensure that your SSL is properly configured for the domains you specify.
  • The environment you redirect from (HTTP) must be different from the production environment (HTTPS).
  • You can further fine-tune the middleware behavior by checking the request domain or other factors.

The above is the detailed content of How to Redirect All Laravel 5 Requests to HTTPS with Domain Exceptions?. 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