Laravel与Vue.js环境下配置CORS:限制API仅允许指定前端域名访问
How to Restrict CORS to Only Allow Your Frontend Domain (frontend.com)
Got it, let's tweak your Laravel CORS configuration so only your frontend at frontend.com can make requests to your backend.com API. Right now your allowed_origins is set to ['*'], which opens up your API to every possible source—we need to lock that down.
Here's the updated cors.php config you should use:
<?php return [ 'paths' => ['api/*'], 'allowed_methods' => ['*'], // Restrict origins to only your frontend domain (include both HTTP and HTTPS if needed) 'allowed_origins' => ['https://frontend.com', 'http://frontend.com'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ];
Quick Notes:
- If your frontend only uses HTTPS (which it should in production), you can remove the
http://frontend.comentry to be even stricter. - If you need to allow local development origins (like
http://localhost:3000), you can add them to theallowed_originsarray temporarily, but make sure to remove them when deploying to production. - Keep
allowed_methodsas['*']if you want to allow all HTTP verbs (GET, POST, PUT, DELETE, etc.)—if you only need specific ones, replace*with a list like['GET', 'POST']. - Set
supports_credentialstotrueif your frontend needs to send cookies or authentication headers with requests; otherwise, leave it asfalse.
After updating the config, remember to clear your Laravel cache to make sure the changes take effect:
php artisan config:clear
内容的提问来源于stack exchange,提问作者dokohew




