NelmioCorsBundle

repository·master·Indexed 24 days ago

https://github.com/nelmio/nelmiocorsbundle

A Symfony bundle for managing Cross-Origin Resource Sharing (CORS) headers. It provides ACL-style per-URL configuration to handle CORS preflight OPTIONS requests and add CORS headers to application responses.

Tokens
1.5K
Snippets
5
Records
6
Agent score
34%

What's inside NelmioCorsBundle

  1. Overview of NelmioCorsBundle features

    master

    NelmioCorsBundle allows you to send Cross-Origin Resource Sharing (CORS) headers using ACL-style per-URL configuration.

    Key features include:

    • Handling CORS preflight OPTIONS requests.
    • Adding CORS headers to your application responses.

    Important Note on Static Files: Because configuration happens at the PHP/application level, requests serving static files that do not pass through the Symfony kernel will not have CORS headers added. If you need to serve CORS for static files, you should configure these headers directly in your web server (e.g., Nginx or Apache).

  2. Manually enable NelmioCorsBundle in Symfony

    master

    If you are not using Symfony Flex, add the bundle to your configuration files.

    For modern Symfony (using config/bundles.php):

    // config/bundles.php
    
    return [
        // ...
        Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
        // ...
    ];

    For older Symfony versions (using app/AppKernel.php):

    // app/AppKernel.php
    
    class AppKernel extends Kernel
    {
        public function registerBundles()
        {
            $bundles = [
                // ...
                new Nelmio\CorsBundle\NelmioCorsBundle(),
            ];
    
            // ...
        }
    }
    <?php
    // config/bundles.php
    
    return [
        // ...
        Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
        // ...
    ];
  3. Install NelmioCorsBundle via Composer

    master

    To install the bundle, require nelmio/cors-bundle in your composer.json and update your dependencies using Composer. If you are using Symfony Flex, the bundle will be automatically enabled.

    composer require nelmio/cors-bundle
  4. Install NelmioCorsBundle

    master

    To install the bundle, require the nelmio/cors-bundle package via Composer.

    If you are using Symfony Flex, the bundle will be enabled automatically.

    If you are not using Flex, you must manually register the bundle in config/bundles.php (for modern Symfony) or app/AppKernel.php (for older Symfony versions).

    $ composer require nelmio/cors-bundle
  5. Configure NelmioCorsBundle via YAML

    master

    Configuration is handled in config/packages/nelmio_cors.yaml. The configuration is split into defaults and paths.

    Configuration Structure

    • defaults: Defines values applied to all matching paths unless overridden. To apply defaults to everything, use the path ^/.
    • paths: A list of URL patterns (regex) and their specific CORS settings. At least one path must be defined.

    Key Options

    • allow_origin: List of allowed origins. Can be set to ['*'] to accept any value. If origin_regex is true, this must be a list of regular expressions.
    • allow_headers: List of allowed headers. Can be set to ['*'] to accept any value.
    • allow_methods: List of allowed HTTP methods (e.g., ['GET', 'POST']). Note: These must be explicitly listed; * is not supported here.
    • expose_headers: List of headers the browser is allowed to access. Can be set to ['*'] if allow_credentials and allow_private_network are both false.
    • max_age: How long (in seconds) preflight requests can be cached.
    • origin_regex: Boolean. If true, allow_origin values are treated as regular expressions.
    • forced_allow_origin_value: Overrides the default behavior of mirroring the Origin request header. Use this to set a specific static value.
    • hosts: A list of allowed hosts.
    • allow_credentials: Boolean. Whether to allow credentials.
    • allow_private_network: Boolean. Whether to allow private network access.
    nelmio_cors:
        defaults:
            allow_credentials: false
            allow_origin: []
            allow_headers: []
            allow_methods: []
            allow_private_network: false
            expose_headers: []
            max_age: 0
            hosts: []
            origin_regex: false
            forced_allow_origin_value: ~
            skip_same_as_origin: true
        paths:
            '^/api/':
                allow_origin: ['*']
                allow_headers: ['X-Custom-Auth']
                allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
                max_age: 3600
            '^/':
                origin_regex: true
                allow_origin: ['^http://localhost:[0-9]+']
                allow_headers: ['X-Custom-Auth']
                allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
                max_age: 3600
                hosts: ['^api\.']
  6. Ignore preflight requests on New Relic

    master

    In architectures with high preflight (OPTIONS) traffic, you can prevent these requests from being monitored by New Relic by creating a request listener that calls newrelic_ignore_transaction() when the method is OPTIONS.

    use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
    
    class PreflightIgnoreOnNewRelicListener
    {
        public function onKernelResponse(FilterResponseEvent $event)
        {
            if (!extension_loaded('newrelic')) {
                return;
            }
    
            if ('OPTIONS' === $event->getRequest()->getMethod()) {
                newrelic_ignore_transaction();
            }
        }
    }