Django下带有静态文件的Nginx配置 [英] Nginx Configuration with Static Files under Django

查看:597
本文介绍了Django下带有静态文件的Nginx配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Django项目设置Nginx配置. 为了提供一些静态文件,而URL上未显示/static/, 我在Nginx配置中添加了一些重写规则.

I am setting an Nginx configuration with my Django project. In order to provide some static file without /static/ showing on the URL, I add some rewrite rules in Nginx configuration.

这是我的Nginx配置的一部分:

Here is part of my Nginx configuration:

    location /static/ {
        location ~* \.(png|jpg|jpeg|gif|css|js)$ {
            access_log off;
            expires 30d;
        }
        alias /path/to/myproject/static/;
    }

    location ~ ^/favicon.ico$ {
        rewrite ^/favicon.ico$ /static/favicon.ico;
    }

    location /foo/ {
        rewrite ^/foo/(.*)$ /static/abc/$1;
    }

    location /bar/ {
        rewrite ^/bar/(.*)$ /static/bar/$1;
    }

    location / {
        fastcgi_pass myproject;
        include django_fastcgi_params;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }

当我访问 https://myproject.com/foo 时,它将显示Django的404页.我认为这是因为Nginx中没有匹配的位置(应该以斜杠/结尾),而Django的urls.py中没有匹配的URL.

When I access https://myproject.com/foo, it will show 404 page of Django. I think it is because there is no matching location in Nginx (should end up with slash /) and no matching URL in Django's urls.py.

当我访问 https://myproject.com/foo/时,它将显示index.htmlmyproject/static/foo/文件夹下,如果没有index.html,则为403 Forbidden.

When I access https://myproject.com/foo/, it will show index.html under myproject/static/foo/ folder, or it will be 403 Forbidden if there is no index.html.

但是我发现...

当我访问 https://myproject.com/foo/abc 时,它将移动301永久地 https://myproject.com/static/foo/abc/

When I access https://myproject.com/foo/abc, it will 301 Moved Permanently to https://myproject.com/static/foo/abc/

当我访问 https://myproject.com/foo/abc/时,它将直接显示 https://myproject.com/foo/abc/,即index.html myproject/static/abc/

When I access https://myproject.com/foo/abc/, it will directly show https://myproject.com/foo/abc/, which is the index.html file under myproject/static/abc/

为什么这两个URL的工作方式不同?

Why these two URLs work differently?

我应该做些修改吗?

推荐答案

修改django项目settings.py中的APPEND_SLASH=False设置.有关更多信息,请参见- https://docs.djangoproject.com /en/2.2/ref/settings/#append-slash

Modify APPEND_SLASH=False setting in the settings.py of django project. For more information see this - https://docs.djangoproject.com/en/2.2/ref/settings/#append-slash

这篇关于Django下带有静态文件的Nginx配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆