Symfony4. Missing ACAO headers only in static files

470 views Asked by At

I have Symfony Rest API on /api context and everything works fine. Additionally, I host static pdf files in the /public/uploads directory. When getting file path through frontend browser throws error

Access to fetch at 'http://127.0.0.1:8000/uploads/b8b3a04a69f59a6c20c9c153281657d5.pdf' from origin 'http://192.168.8.111:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

It is like nelmio cors did not add the Access-Control-Allow-Origin header to the downloaded files but whole api works good without problems. I don't have an .htaccess file that overwrites the headers.

nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Content-Type', 'Authorization', 'origin', 'accept', 'bearer']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/uploads':
            allow_origin: [ '%env(CORS_ALLOW_ORIGIN)%' ]
            allow_methods: [ 'GET', 'OPTIONS' ]
            allow_headers: [ 'Content-Type', 'Authorization', 'origin', 'accept', 'bearer' ]
            max_age: 3600
        '^/': ~

allow_origin is set on '*' in .env

When I run CORS Chrome extension everything is ok.

Do you have any idea why headers aren't added to the files?

2

There are 2 answers

0
Mikhail Prosalov On BEST ANSWER

In this case, when you download files directly, you're bypassing your PHP application, so no CORS headers were added. Of course, you have an option to implement an endpoint to download files from this folder. The other option is to add required headers using your web server (Apache or Nginx).

0
Peep On

Solution

Create new apache confing

<VirtualHost *:7777>
    DocumentRoot /var/www/html/document_repository

    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "GET, OPTIONS"
    Header always set Access-Control-Allow-Headers "origin"
    Header always set Access-Control-Expose-Headers "Content-Security-Policy, Location"
    Header always set Access-Control-Max-Age "3600"

    <Directory /var/www/html/document_repository>
        AllowOverride None
        Order Allow,Deny
        Allow from All
    </Directory>

    ErrorLog /var/log/httpd/document_repository_error.log
    CustomLog /var/log/httpd/document_repository_access.log combined
</VirtualHost>

Response