Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can allowed_origins_patterns include wildcards for subdomains
    laravel-cors


Can allowed_origins_patterns include wildcards for subdomains


Yes, you can use wildcards in the `allowed_origins_patterns` option in Laravel's CORS configuration to allow access from subdomains.

Here's an example configuration that allows access from any subdomain of `example.com`:

php
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => ['/^https?:\/\/(.+\.)?example\.com$/'],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

In this configuration, the `allowed_origins_patterns` option uses a regular expression pattern to match any subdomain of `example.com`. The pattern `/^https?:\/\/(.+\.)?example\.com$/` will match URLs like:

- `https://example.com`
- `https://example.com`
- `https://subdomain.example.com`
- `https://subdomain.example.com`

The `(.+\.)` part of the pattern matches one or more subdomains, followed by the base domain `example.com`.

Using wildcards in `allowed_origins_patterns` provides more flexibility compared to the `allowed_origins` option, which only allows you to specify exact domain matches or the wildcard `'*'` to allow all origins.

However, keep in mind that using regular expressions can be less performant than exact string matching, so it's generally recommended to use `allowed_origins` whenever possible, and only use `allowed_origins_patterns` when you need more complex origin matching.

Citations:
[1] https://laracasts.com/discuss/channels/vapor/laravel-vapor-random-cloudfront-cors-error
[2] https://laracasts.com/discuss/channels/laravel/laravel-10-cors
[3] https://www.twilio.com/en-us/blog/handling-cross-origin-resource-sharing-cors-requests-laravel-7
[4] https://www.linkedin.com/pulse/demystifying-cors-laravel-comprehensive-guide-resource-farhan-tanvir
[5] https://dev.to/keikesu0122/a-simple-way-to-enable-cors-on-laravel-55i