How to serve media file using Nginx and django?

2019-08-14 06:24发布

问题:

Good evening,

I am currently facing an issue on my home project.

I set up a django project, with gunicorn and nginx.

Nginx seems to serve my statics normally but when it comes to media files it does not work and i have the following message displayed in my error log: failed (2: No such file or directory)

I tried to use different users for nginx.conf but it is still the same.

I am missing something somewhere but i can not find out.

I attach my nginx file (updated):

upstream app_server {
    server unix:/home/project/saleor.sock fail_timeout=0;
}

server {
    listen 80;

    server_name my_server_ip;

    access_log /home/project/logs/nginx-access.log;
    error_log /home/project/logs/nginx-error.log;

    location /media  {
      root    /home/user/project/test/media/;
      expires 1d;
    }

    location /static {
      root /home/user/project/test/static/;
      expires 1d;
      autoindex on;
    }


    location / {
        try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_pass http://app_server;
    }
}

UPDATE: I removed the following portion:

location ~ ^/(images|javascript|js|css|flash|media|static)/  {
  root   /home/user/project/test;
  expires 30d;
}

and added:

    location /media {
      root /home/user/project/test/media/;
      expires 1d;
      autoindex on;
    }

    location /static {
      root /home/user/project/test/static/;
      expires 1d;
      autoindex on;
    }

Here is a sample of my settings.py:

ALLOWED_HOST = my_server_ip
PROJECT_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'

UPDATE:

Here is a sample of my nginx error log:

[error] 11475#11475: *1 open() "/home/user/project/test/media/media/sized/products/picture.JPG" failed (2: No such file or directory), client: some_client_ip, server: my_server_ip, request: "GET /media/sized/products/picture.JPG HTTP/1.1", host: "my_website_ip", referrer: "http://my_website_ip/en/"

Do you have any idea where it could come from? (I am quite sure it is something stupid =/)

回答1:

You forgot to specify media part to your Nginx conf file, also you should do the same for you static files

server {
        ....
        # There is for media, Put your path here :)
        location /media {
            autoindex on;
            alias /home/myusername/myproject/media/;
        }
        ....
    }