Troubleshooting


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:

  1. Set APP_URL environment variable to reflect your domain

    .env
    APP_URL=http://your-laravel-domain.local
    
  2. Next, you need to modify the RouteServiceProvider.php file to enable the use of the forceRootUrl() method. This step is crucial to ensure that Laravel generates correct URLs when working behind a reverse proxy.

    app/Providers/RouteServiceProvider.php
    public function boot(): void
    	{
    		$url = $this->app['url'];
    		$url->forceRootUrl(config('app.url'));
    		...
    	}
    
  3. (Optional) If you use HTTPS, you will need to force it in Laravel by editing app/Providers/AppServiceProvider.php

    app/Providers/AppServiceProvider.php
    public function register(): void
    	{
    		...
    		$this->app['request']->server->set('HTTPS', true);
    		...
    	}
    

Enable hot-reloads (HMR)

Edit vite.config.js file by adding:

vite.config.js
...
export default defineConfig({
	server: {
			hmr: {
					protocol: "wss", // for http use ws
					host: "vite.local", // your Vite domain
					clientPort: 443, // for http use 80
			},
			cors: {
					origin: false, // disable CORS
			},
	},

After completing these steps, Laravel will be correctly configured to work behind the LocalCan reverse proxy.

© 2024 LocalCan™. All rights reserved.