skip to Main Content

I’m trying to deploy a Laravel 10 installation to a Ubuntu 20.04.2 LTS server running LEMP (Linux/Nginx/MySQL/PHP). I’m also using Cloudflare SSL/TLS encryption on Full (strict) mode.

Everything works locally via Laravel Sail (Docker).

Standard PHP files (in production) work too. If I place a test.php in my public directory everything seems to work fine.

However, whenever I try to access my Laravel application I always get a 302 ERR_TOO_MANY_REDIRECTS (I’ve tried clearing my cache).

ERR_TOO_MANY_REDIRECTS

My SSL seems to be set up correctly.

SSL Results

The following is the template my project uses to build a virtual host during initial deployment (it allows for a subdomain and different environments for CI/CD). This essentially merges the configuration found in Laravel’s docs with some SSL settings.

server {

    # Listen on port 80.
    listen 80;
    listen [::]:80;

    # Production
    server_name {{ subdomain }}.redacted-domain.net;

    # Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response.
    return 301 https://$host$request_uri;

}

server {

    server_name {{ subdomain }}.redacted-domain.net;
    root /var/www/{{ environment }}/release/public;

    # Listen with SSL on port 443
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # SSL
    ssl_certificate {{ ssl_directory }}/star-redacted-domain-net_chain.crt;
    ssl_certificate_key {{ ssl_directory }}/star-redacted-domain-net.key;

    # Logs
    access_log /var/log/nginx/{{ environment }}.vhost.access.log;
    error_log /var/log/nginx/{{ environment }}.vhost.error.log;

    # Laravel security recommendation
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    # Only index directory using PHP files
    index index.php;

    # Set default character set to utf-8
    charset utf-8;

    # Handle relative, root and query string locations
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Handle favicon and robots
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    # Tell 404 to simple render Laravel's php page
    error_page 404 /index.php;

    # PHP settings
    location ~ .php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # Deny any non well known files
    location ~ /.(?!well-known).* {
        deny all;
    }

}

For my "plain" PHP files to work, my suspicions are that Laravel is the culprit and that it’s clashing with Cloudflare’s HTTP to HTTPS redirection.

I’ve tried forcing a HTTPS schema (in AppServiceProvider.php) as following but this hasn’t resolved the issue…

/**
 * Bootstrap any application services.
 */
public function boot() : void {

    $this->forceHTTPSIfNotLocal();

}

/**
 * @return void
 */
private function forceHTTPSIfNotLocal() : void {

    if( !app()->isLocal() ) URL::forceScheme( 'https' );

}

Any help is much appreciated!

2

Answers


  1. Chosen as BEST ANSWER

    After banging my head for some time I finally found a (simple) solution. For anyone else that was as stuck as I was...

    You need to add the TrustProxies middleware to your web middleware group (app/Http/Kernel.php)

    /**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareTrustProxies::class,                           // Added this to prevent Cloudflare Too Many Redirect issues
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
            AppHttpMiddlewareHandleInertiaRequests::class,
        ],
    

  2. In my case it was solved with the SSL/TLS configuration in the hosting. Configuring SSL URL in CloudFlare.
    Performing the installation of the SSL certificate.
    No edits to the Laravel code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search