django : Serving static files through nginx

后端 未结 5 1795
醉话见心
醉话见心 2020-12-04 09:40

I\'m using apache+mod_wsgi for django.
And all css/js/images are served through nginx.
For some odd reason, when others/friends/colleagues try accessing

相关标签:
5条回答
  • 2020-12-04 10:19

    I think using root in location block is incorrect. I use alias and it works fine, even without re-configuring django.

    # django settings.py
    MEDIA_URL = '/static/'
    
    # nginx server config
    server {   
        ...
        location /static {    
            autoindex on;    
            alias /opt/aa/webroot/;    
        }
    }
    

    Hope this makes things simpler.

    0 讨论(0)
  • 2020-12-04 10:19

    MEDIA_URL shall not be used to serve the Static content like js etc. Django provides a separate STATIC_URL settings option that can be used.

    So this can be changed as

    <script type="text/javascript" src="{{STATIC_URL}}js/jquery-1.3.2.min.js"></script>
    

    Also, its more standard to use staticfile app templatetag like this:

    {% load static from staticfiles %}
    <script type="text/javascript" src="{% static 'js/jquery-1.3.2.min.js' %}"></script>
    

    Docs Here

    0 讨论(0)
  • 2020-12-04 10:28
    1. server_name must match hostname in link/script URLs. Either declare your configuration as default for this interface:port pair (listen 8000 default)
    2. Nginx must listen on the interface where your host's IP is bound (seems ok in your case)
    0 讨论(0)
  • 2020-12-04 10:29

    Fim & Alexander - Thanks for the hints those helped.
    Here is how I solved it for anyone stuck in the same boat -

    settings.py -

    >MEDIA_ROOT = ''    
    MEDIA_URL = 'http://x.x.x.x:8000/static/'    
    

    In my html -

    <script type="text/javascript" src="{{MEDIA_URL}}js/jquery-1.3.2.min.js"></script>
    

    In my views.py -

    return render_to_response('templates/login-register.html', {},
                              context_instance=RequestContext(request));    
    

    nginx inside the sites-available config file -

    listen x.x.x.x:8000;    
    server_name x.x.x.x.;
    

    Restarted nginx
    Restarted apache

    0 讨论(0)
  • 2020-12-04 10:30

    I also struggled with this. However, following trick worked for me:

    server {   
         listen   8000;   
         server_name  localhost;
    
         access_log  /var/log/nginx/aa8000.access.log;    
         error_log  /var/log/nginx/aa8000.error.log;    
    
           location / {   
               index  index.html index.htm;    
           }    
    
         location ^/static/ {    
            autoindex on;    
            root   /opt/aa/webroot/;    
         }    
     } 
    

    I just marked static as a regex with ^ and nginx started serving static files. No modification on Django side was needed.

    0 讨论(0)
提交回复
热议问题