Caching web routes with forced url in laravel

Viewed 594

I'm running a laravel project behind a reversed proxy which is why I need to force the root url and scheme:

URL::forceRootUrl($proxy_url);
URL::forceScheme($proxy_schema);

I've added this to the top of my /routes/web.php and it's working fine until I run:

php artisan optimize

It caches the routes in /bootstrap/cache without the forced url and scheme, so now all my urls are pointing to the wrong root url.

I've tried to move the code to /Providers/AppServiceProvider.php (both register and boot) in order to make it take effect when caching the routes but no luck.

I have to manually delete the routes cache file in /bootstrap/cache to make my routes work again.

Have do I make it take effect when caching the routes?

Edit: I have also tried to create a global middleware where I do the force url and schema. Again it works fine before caching the routes, but when running php artisan optimize the routes are once again incorrect.

2 Answers

php artisan optimize removed since laravel 5.6 (source, source2)

enter image description here

Using URL::forceRootUrl and URL::forceScheme seems like a work-around for working with reverse proxies. The clean solution for it would be to add a trusted proxies in your configuration. This post explains the feature in full. But it comes down to:

  1. Use the App\Http\Middleware\TrustProxies middleware
  2. Edit the middleware $proxies property with the IP(s) of your load balancer
    protected $proxies = [
        '192.168.1.1',
        '192.168.1.2',
    ];
  1. Remove the following code from /routes/web.php
URL::forceRootUrl($proxy_url);
URL::forceScheme($proxy_schema);
Related