Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon What is the difference between allowed_origins and allowed_origins_patterns in Laravel CORS
    Laravel CSRF


What is the difference between allowed_origins and allowed_origins_patterns in Laravel CORS


The `allowed_origins` and `allowed_origins_patterns` options in the Laravel CORS configuration serve different purposes:

1. allowed_origins:
- This option specifies the list of origins that are allowed to access the resources.
- The origins can be specified as exact string matches, e.g., `'https://example.com'`.
- You can also use the wildcard `'*'` to allow access from any origin.

2. allowed_origins_patterns:
- This option allows you to specify a list of regular expression patterns that match the allowed origins.
- This is useful when you need more flexibility in defining the allowed origins, such as allowing subdomains or dynamic origins.
- The patterns should be valid regular expressions, e.g., `'/^https?:\/\/(.+\.)?example\.com$/'`.

The main differences between the two options are:

- Flexibility: `allowed_origins_patterns` provides more flexibility in defining the allowed origins, as you can use regular expressions to match complex patterns.
- Performance: `allowed_origins` is generally faster and more efficient than `allowed_origins_patterns`, as it doesn't require regular expression matching for each request.

In most cases, using the `allowed_origins` option with exact string matches or the wildcard `'*'` is sufficient. However, if you need to allow a more complex set of origins, such as subdomains or dynamic origins, then the `allowed_origins_patterns` option can be more useful.

Here's an example configuration that uses both options:

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

In this example, the configuration allows access from the exact origins `'https://example.com'` and `'https://subdomain.example.com'`, as well as any other subdomains of `'example.com'` using the regular expression pattern.

Citations:
[1] https://laracasts.com/discuss/channels/laravel/laravel-10-cors
[2] https://dev.to/keikesu0122/a-simple-way-to-enable-cors-on-laravel-55i
[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://github.com/fruitcake/laravel-cors