troccoli's avatar

Force external URLs to use https

In my app I have some external URLs to a legacy app that will always have to be https. However, the app itself will not always be over https, for example locally and during CI.

I have created routes for them as such (this is just one of them of course)

Route::domain(config('app.legacy_domain'))
    ->name('legacy.')
    ->group(function (): void {
        Route::get('contact')->name('contact-us');
    });

I'm using the configuration so I can switch between UAT and Production.

However, the protocols used is always the one for the app, so for example during CI these URLs are over http and not https.

I have also tried adding the protocol to the domain itself, something like

Route::domain('https://' . config('app.legacy_domain'))

but to no avail.

I dig into the Laravel code and I can see that that's how it's supposed to work.

But does anyone have any idea how I can solve this problem?

0 likes
1 reply
LaryAI's avatar
Level 58

To ensure that external URLs always use HTTPS, regardless of the environment your application is running in, you can create a custom URL generator or use middleware to enforce HTTPS for specific routes. Here's a solution using a custom URL generator:

  1. Create a Custom URL Generator:

    You can extend Laravel's URL generator to force HTTPS for specific routes. First, create a new service provider to bind your custom URL generator.

  2. Create a Service Provider:

    Run the following command to create a new service provider:

    php artisan make:provider CustomUrlServiceProvider
    
  3. Extend the URL Generator:

    In your CustomUrlServiceProvider, extend the URL generator to force HTTPS for specific routes:

  4. Register the Service Provider:

    Register your new service provider in config/app.php:

    'providers' => [
        // Other Service Providers
    
        App\Providers\CustomUrlServiceProvider::class,
    ],
    
  5. Use Named Routes:

    Ensure that you are using named routes for your legacy URLs, as the custom URL generator checks for route names starting with legacy. to enforce HTTPS.

This solution will ensure that any route with a name starting with legacy. will always be generated with an https protocol, regardless of the environment.

Please or to participate in this conversation.