Solving Laravel HTTPS to HTTP Proxy Issue

When you’re dealing with a setup where a client communicates with an SSL load balancer over HTTPS, and the load balancer talks to a backend server over HTTP, you might encounter issues with Laravel generating URLs with an http:// schema. To address this issue, you can implement the following workaround:

Step 1: Modify routes.php

Open your Laravel project’s routes.php file and add the following code snippet at the top of the file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$proxy_url = getenv('PROXY_URL');
$proxy_schema = getenv('PROXY_SCHEMA');

if (!empty($proxy_url)) {
    URL::forceRootUrl($proxy_url);
}

if (!empty($proxy_schema)) {
    URL::forceScheme($proxy_schema);
}

This code sets the root URL and schema for Laravel’s URL generation based on environment variables.

Step 2: Update the .env File

Next, you’ll need to update your Laravel project’s .env file to include the PROXY_URL and, if necessary, the PROXY_SCHEMA. Add these lines to the .env file:

1
2
PROXY_URL=http://igateway.somedomain.com
PROXY_SCHEMA=https

Replace http://igateway.somedomain.com with the actual URL of your backend server and adjust the schema (https or http) as needed.

Explanation

Here’s how this workaround works:

  1. In the routes.php file, you check for the presence of PROXY_URL and PROXY_SCHEMA environment variables.
  2. If PROXY_URL is set, you force Laravel to use this URL as the root URL for generating URLs. This ensures that URLs generated by Laravel use the correct base URL.
  3. If PROXY_SCHEMA is set, you force Laravel to use this schema (either http or https) for generating URLs. This ensures that URLs are generated with the appropriate schema.

By following these steps, you can configure Laravel to generate URLs correctly, even in a setup where there’s a proxy between the client and the backend server with different schemas (HTTPS to HTTP). This workaround ensures that your application generates URLs with the schema and root URL you specify in the .env file, making it compatible with your proxy setup.

0%