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:
-
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.
-
Create a Service Provider:
Run the following command to create a new service provider:
php artisan make:provider CustomUrlServiceProvider -
Extend the URL Generator:
In your
CustomUrlServiceProvider, extend the URL generator to force HTTPS for specific routes:<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Routing\UrlGenerator; class CustomUrlServiceProvider extends ServiceProvider { /** * Register services. * * @return void */ public function register() { // } /** * Bootstrap services. * * @return void */ public function boot() { $this->app->singleton('url', function ($app) { $routes = $app['router']->getRoutes(); return new class($routes, $app->rebinding( 'request', $this->requestRebinder() )) extends UrlGenerator { public function route($name, $parameters = [], $absolute = true) { $url = parent::route($name, $parameters, $absolute); // Check if the route name is one of the legacy routes if (str_starts_with($name, 'legacy.')) { $url = preg_replace('/^http:/i', 'https:', $url); } return $url; } }; }); } /** * Get the request rebinder callback. * * @return \Closure */ protected function requestRebinder() { return function ($app, $request) { $app['url']->setRequest($request); }; } } -
Register the Service Provider:
Register your new service provider in
config/app.php:'providers' => [ // Other Service Providers App\Providers\CustomUrlServiceProvider::class, ], -
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.