Laravel CORS errors when using reverse proxy
When using Laravel with a reverse proxy like LocalCan, it's essential to perform a few setup steps to ensure compatibility.
One common issue that arises is CORS (Cross-Origin Resource Sharing) errors, which can result from Laravel not properly rewriting the host name of the reverse proxy or requesting HTTP content from an HTTPS context (mixed content).
To address these issues, follow these steps:
-
Set
APP_URL
environment variable to reflect your domain.envINI / .envAPP_URL=http://your-laravel-domain.local
-
Because LocalCan handles HTTPS, Laravel needs to be told to generate
https
URLs. Openapp/Providers/AppServiceProvider.php
and addURL::forceScheme('https');
to theboot
method.app/Providers/AppServiceProvider.phpPHP / app/Providers/AppServiceProvider.php<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; + use Illuminate\Support\Facades\URL; class AppServiceProvider extends ServiceProvider { public function register(): void { // } public function boot(): void { + URL::forceScheme('https'); } }
-
If you use Laravel prior to 11, you need to modify the
RouteServiceProvider.php
file to enable the use of theforceRootUrl()
method. This step is crucial to ensure that Laravel generates correct URLs when working behind a reverse proxy.app/Providers/RouteServiceProvider.phpPHP / app/Providers/RouteServiceProvider.phppublic function boot(): void { + $url = $this->app['url']; + $url->forceRootUrl(config('app.url')); // ... }
Enable Vite and hot-reloads (HMR)
To make Vite development server work through LocalCan's proxy, you will need to:
-
Create a separade domain for Vite in LocalCan. For example
https://vite.local
with a Target Server set tohttps://127.0.0.1:5173
(Vite's default address) -
Edit
vite.config.js
file by adding theserver
code block. This tells Vite how to handle HMR requests through LocalCan's proxy.vite.config.jsJavaScript / vite.config.js// ... export default defineConfig({ // ... + server: { + hmr: { + protocol: 'wss', + host: 'vite.local', + clientPort: 443, + }, + cors: { + origin: true, + }, + }, })
After completing these steps, Laravel will be correctly configured to work behind the LocalCan reverse proxy.
© 2025 LocalCan™. All rights reserved.