Report this

What is the reason for this report?

Nginx not serving media files

Posted on October 26, 2020

Hi everyone, so I took over someone’s project and I am supposed to deploy it on a new server. We have an Nginx server that is supposed to be handling a Django application static media files but I keep getting a 404 not found error here is the Nginx.conf file:

server {

    listen 80;
    server_name localhost;

    return 301 https://$host$request_uri;

}

server {

    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    server_name localhost;
    charset utf-8;
    client_max_body_size 150M;

    include /config/nginx/proxy-confs/*.subfolder.conf;

    include /config/nginx/ssl.conf;

    location /static {
        sendfile  on;
        sendfile_max_chunk 25m;
        alias /static;
    }

    location /media/user {
        sendfile  on;
        sendfile_max_chunk 50m;
        internal;
        alias /media/user;
    }

    location /admin/login {
        return 301 " /login";
    }

    location /media/protected {
        if ($http_user_agent ~* (360Spider|80legs.com|Abonti|AcoonBot|Acunetix|adbeat_bot|AddThis.com|adidxbot|ADmantX|AhrefsBot|AngloINFO|Antelope|Applebot|BaiduSpider|BeetleBot|billigerbot|binlar|bitlybot|BlackWidow|BLP_bbot|BoardReader|Bolt\ 0|BOT\ for\ JCE|Bot\ mailto\:craftbot@yahoo\.com|casper|CazoodleBot|CCBot|checkprivacy|ChinaClaw|chromeframe|Clerkbot|Cliqzbot|clshttp|CommonCrawler|comodo|CPython|crawler4j|Crawlera|CRAZYWEBCRAWLER|Curious|Curl|Custo|CWS_proxy|Default\ Browser\ 0|diavol|DigExt|Digincore|DIIbot|discobot|DISCo|DoCoMo|DotBot|Download\ Demon|DTS.Agent|EasouSpider|eCatch|ecxi|EirGrabber|Elmer|EmailCollector|EmailSiphon|EmailWolf|Exabot|ExaleadCloudView|ExpertSearchSpider|ExpertSearch|Express\ WebPictures|ExtractorPro|extract|EyeNetIE|Ezooms|F2S|FastSeek|feedfinder|FeedlyBot|FHscan|finbot|Flamingo_SearchEngine|FlappyBot|FlashGet|flicky|Flipboard|g00g1e|Genieo|genieo|GetRight|GetWeb\!|GigablastOpenSource|GozaikBot|Go\!Zilla|Go\-Ahead\-Got\-It|GrabNet|grab|Grafula|GrapeshotCrawler|GTB5|GT\:\:WWW|Guzzle|harvest|heritrix|HMView|HomePageBot|HTTP\:\:Lite|HTTrack|HubSpot|ia_archiver|icarus6|IDBot|id\-search|IlseBot|Image\ Stripper|Image\ Sucker|Indigonet|Indy\ Library|integromedb|InterGET|InternetSeer\.com|Internet\ Ninja|IRLbot|ISC\ Systems\ iRc\ Search\ 2\.1|jakarta|Java|JetCar|JobdiggerSpider|JOC\ Web\ Spider|Jooblebot|kanagawa|KINGSpider|kmccrew|larbin|LeechFTP|libwww|Lingewoud|LinkChecker|linkdexbot|LinksCrawler|LinksManager\.com_bot|linkwalker|LinqiaRSSBot|LivelapBot|ltx71|LubbersBot|lwp\-trivial|Mail.RU_Bot|masscan|Mass\ Downloader|maverick|Maxthon$|Mediatoolkitbot|MegaIndex|MegaIndex|megaindex|MFC_Tear_Sample|Microsoft\ URL\ Control|microsoft\.url|MIDown\ tool|miner|Missigua\ Locator|Mister\ PiX|mj12bot|Mozilla.*Indy|Mozilla.*NEWT|MSFrontPage|msnbot|Navroad|NearSite|NetAnts|netEstate|NetSpider|NetZIP|Net\ Vampire|NextGenSearchBot|nutch|Octopus|Offline\ Explorer|Offline\ Navigator|OpenindexSpider|OpenWebSpider|OrangeBot|Owlin|PageGrabber|PagesInventory|panopta|panscient\.com|Papa\ Foto|pavuk|pcBrowser|PECL\:\:HTTP|PeoplePal|Photon|PHPCrawl|planetwork|PleaseCrawl|PNAMAIN.EXE|PodcastPartyBot|prijsbest|proximic|psbot|purebot|pycurl|QuerySeekerSpider|R6_CommentReader|R6_FeedFetcher|RealDownload|ReGet|Riddler|Rippers\ 0|rogerbot|RSSingBot|rv\:1.9.1|RyzeCrawler|SafeSearch|SBIder|Scrapy|Scrapy|Screaming|SeaMonkey$|search.goo.ne.jp|SearchmetricsBot|search_robot|SemrushBot|Semrush|SentiBot|SEOkicks|SeznamBot|ShowyouBot|SightupBot|SISTRIX|sitecheck\.internetseer\.com|siteexplorer.info|SiteSnagger|skygrid|Slackbot|Slurp|SmartDownload|Snoopy|Sogou|Sosospider|spaumbot|Steeler|sucker|SuperBot|Superfeedr|SuperHTTP|SurdotlyBot|Surfbot|tAkeOut|Teleport\ Pro|TinEye-bot|TinEye|Toata\ dragostea\ mea\ pentru\ diavola|Toplistbot|trendictionbot|TurnitinBot|turnit|Twitterbot|URI\:\:Fetch|urllib|Vagabondo|Vagabondo|vikspider|VoidEYE|VoilaBot|WBSearchBot|webalta|WebAuto|WebBandit|WebCollage|WebCopier|WebFetch|WebGo\ IS|WebLeacher|WebReaper|WebSauger|Website\ eXtractor|Website\ Quester|WebStripper|WebWhacker|WebZIP|Web\ Image\ Collector|Web\ Sucker|Wells\ Search\ II|WEP\ Search|WeSEE|Wget|Widow|WinInet|woobot|woopingbot|worldwebheritage.org|Wotbox|WPScan|WWWOFFLE|WWW\-Mechanize|Xaldon\ WebSpider|XoviBot|yacybot|Yahoo|YandexBot|Yandex|YisouSpider|zermelo|Zeus|zh-CN|ZmEu|ZumBot|ZyBorg) ) {
            return 410;
        }
        sendfile  on;
        sendfile_max_chunk 50m;
        internal;
        alias /media/protected;
    }

    location /media {
        sendfile  on;
        sendfile_max_chunk 25m;
        alias /media;
    }

    location /media/images/company {
        alias /media/images/company;
    }

    location / {
        proxy_pass http://web:8000;
        proxy_redirect off;
        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-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

}

if anyone can offer any insights that would be great!



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Your alias statements could be wrong in location branches. Point those to full pathes.

    location /media {
        add_header Cache-Control "public, stale-if-error=144000";
        expires 30d;
        alias /mnt/volume_nyc3_whatever/whatever/media;
    }

@mjnicholson @AlexeiRamone so this is an example of a file I’am trying to access: https://ace-concordia.com/media/protected/2020/Aly_Gasser_40135687/transcript/9c0be77746d84dceaec44dc2e5b64b07/Sample.pdf

I went inside the Nginx container to this directory:/media/protected/2020/Aly_Gasser_40135687/transcript/9c0be77746d84dceaec44dc2e5b64b07
and the file is actually there! Nginx is just not getting it for some reason, the error logs have nothing on this but the access logs show it and that it gets 404 answer

Thanks, folks your help is really appreciated!

Heya,

The issue with Nginx not serving media files in your Django application can be due to incorrect or missing configurations in the Nginx setup. Let’s review and address potential problems in your provided Nginx configuration:

Checking the Alias Directives

In your nginx.conf file, you have specified several alias directives for serving static and media files. It’s important to ensure that these alias paths are correctly pointing to the actual locations of your static and media files on the server.

  1. Correct File Paths: Make sure the paths specified in alias directives are correct and point to the directories where your Django project’s static and media files are located. For example, if your static files are in /home/user/myproject/static, the directive should be alias /home/user/myproject/static;.

  2. Remove Trailing Slashes: It’s common to miss the detail of trailing slashes. When using alias, the path should not have a trailing slash. For example, use alias /path/to/media; instead of alias /path/to/media/;.

location /media {
    alias /path/to/media;  # Corrected path
    # Other directives...
}

Permissions

  1. File Permissions: Ensure that the user running Nginx (usually www-data or nginx) has read permissions to the directories and files inside your media and static directories.

Reviewing Configuration

  1. Server Block Context: Double-check that these location blocks are in the correct server block that handles your Django application.

  2. Reload Nginx: After making changes, reload Nginx to apply them:

sudo systemctl reload nginx
  1. Debugging: To further debug, check the Nginx error logs (/var/log/nginx/error.log) for specific messages related to the 404 errors.

Example Configuration

Here’s a simplified example of what part of your Nginx configuration might look like, adjusted for clarity:

server {
    listen 443 ssl http2;
    server_name localhost;  # Replace with your domain name

    # SSL configuration
    # include /config/nginx/ssl.conf;

    root /path/to/django/project;  # Django project root

    location /static/ {
        alias /path/to/static;  # Corrected static files path
    }

    location /media/ {
        alias /path/to/media;  # Corrected media files path
    }

    location / {
        # Proxy pass to Django
        proxy_pass http://web:8000;
        # Additional proxy settings...
    }

    # Other locations...
}

dditional Points

  • Django’s DEBUG Mode: If your Django app is still in DEBUG mode (DEBUG = True in settings.py), Django will handle static files, which could be masking issues with Nginx’s configuration. Ensure DEBUG is set to False in your production settings.

  • Media URL: Check your Django settings to make sure MEDIA_URL is correctly set.

  • Django Collectstatic: Run python manage.py collectstatic on your Django application to ensure all static files are collected to the STATIC_ROOT location.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.