如何在nginx / django / python中拒绝对root的访问但允许子目录访问?

时间:2018-12-14 20:16:54

标签: python django nginx

我当前的nginx配置如下:

server {
    listen       443 ssl http2 default_server;
    listen       [::]:443 ssl http2 default_server;
    server_name  _;
    root         /usr/share/nginx/html;

    ssl_certificate "PEM";
    ssl_certificate_key "PEM";
    # It is *strongly* recommended to generate unique DH parameters
    # Generate them with: openssl dhparam -out /etc/pki/nginx/dhparams.pem 2048
    #ssl_dhparam "/etc/pki/nginx/dhparams.pem";
    ssl_session_cache shared:SSL:1m;
    ssl_session_timeout  10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP;
    ssl_prefer_server_ciphers on;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location / {
        proxy_pass http://127.0.0.1:80;
    }

    error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}

# configuration of the server
server {
    # the port your site will be served on
    listen      80;
    # the domain name it will serve for
    server_name SERVER;
    charset     utf-8;

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

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /etc/nginx/uwsgi_params; 
        rewrite ^(/[^/]+)/frontend/$ $1/ last;
    }
}
]

我想禁止访问root并允许访问子目录/ dir1 /。但是,这样做是行不通的,因为我遇到了重复的位置“ /”问题(由于https的设置方式)。有什么建议吗?

location ^~ /dir1/ {
    allow all;
}

location ^~ / { 
    deny all; 
}

1 个答案:

答案 0 :(得分:3)

您可以尝试定义完全匹配的位置(此类位置优先于其他任何位置):

location = / {
    deny all;
}

请注意,这不会保护对根目录中任何文件的请求。为了保护这些文件,您可以执行类似的操作

location ~^/[^/]+$ {
    deny all;
}

但这会干扰您的django路线。

在这种情况下,您可以使用以下重写规则将任何根级别的请求your_domain/path重写为your_domain/path/

rewrite ^(/[^/]+)$ $1/ last;