You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

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.com entry to be even stricter.
  • If you need to allow local development origins (like http://localhost:3000), you can add them to the allowed_origins array temporarily, but make sure to remove them when deploying to production.
  • Keep allowed_methods as ['*'] 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_credentials to true if your frontend needs to send cookies or authentication headers with requests; otherwise, leave it as false.

After updating the config, remember to clear your Laravel cache to make sure the changes take effect:

php artisan config:clear

内容的提问来源于stack exchange,提问作者dokohew

火山引擎 最新活动