简体   繁体   中英

Django alias for static file path

I have a Django 4.1 project and want to make an alias to the directory with static files. So, in settings.py I have

STATIC_URL = "static/"

All my static files are in the example.com/static/... . I want to make a shortcut to one of directories of static files. For example example.com/magic/... should be the same as example.com/static/physics/... . That shoudn't be a redirect , because if it is a redirect, I won't be able to download file using curl without any special options.

How can I do this? Maybe with some special paths in urls.py ?

You can put the static url to

STATIC_URL = "http://example.com/static/"

Making shortcuts do directories/redirecting without a redirect like that is better done with a server like Nginx. Example config for nginx:

server {
    # the port your site will be served on
    listen      80;
    # the domain name it will serve for
    server_name localhost; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    location /static{
        proxy_pass http://example.com/static;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /magic{
        proxy_pass http://example.com/static/physics;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }


    # Finally, send all non-static requests to the Django server.
    location / {
        proxy_pass http://127.0.0.1:8080; # This will be your production server. Please do not use django's built in runserver.
    }

}

This will basically pass-through the requests in nginx, straight to the domain (example.com), this way, the redirect happens in the backend, and the user (or curl in your case) won't notice a thing. It doesn't involve the slow python interpreter, nginx is made straight in C.

If you go the nginx route, https://django-server-example.com/static/ is the static url, not https://example.com/static/ , it will be run on the same domain, but it will (again), pass through the requests. So https://django-server-example.com/static/ will lead to https://example.com/static/ (without a redirect).

If you do nginx, set the static url to STATIC_URL = "/static/"

So remember, django does not handle your staticfiles anymore. But still do set the STATIC_URL , this way your {% static %} templatetag works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM