Nginx don't expose CORS headers for media files

I have a vuejs application consuming Django DRF API. All endpoints all working correctly with my current configuration. Except for media files.

In Mozilla Developer tools -> Network -> Headers, I check that all API endpoints include cors headers and media files don't.

I am using django-cors-headers with common configuration:

CORS_ALLOW_ALL_ORIGINS = True

... 

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    ...
]

INSTALLED_APPS = [
    ...
    'corsheaders'
]

I've tried with different CORS configuration, here in settings.py, as mentioned in several Stackoverflow questions, but nothing change the behavior.

I suspect the problem is on NGINX. This is my configuration file:

server {
    server_name my_domain;
    
    ...

    location /media {
        autoindex on;
        alias /home/myproject/media;
    }

    location / {
        proxy_set_header Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_pass http://localhost:8000/;
        
    }


    # these options are managed by Certbot, do i think it is ok.
    listen 443 ssl;
    ssl_certificate ...
    ssl_certificate_key ...
    include ...
    ssl_dhparam ...
}

server {
    if ($host = mydomain) {
        return 301 https://$host$request_uri;
    }

    server_name mydomain;
    listen 80;
    return 404;
}

I've also tried adding add_header Access-Control-Allow-Origin *;, but again, the cors headers are not exposed.

What am I missing here?

This answer finally gave me the clue:

https://stackoverflow.com/a/56092397

I was receiving a 301 error, so the problem wasn't the CORS policy, but an embarrasing mistake on the URL.

As Brad pointed in the linked answer:

... pretty common for error responses to not have the appropiate CORS headers...

So it is confusing to debug.

Back to Top