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

sup*_*dee 1 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;
    }
}
]
Run Code Online (Sandbox Code Playgroud)

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

location ^~ /dir1/ {
    allow all;
}

location ^~ / { 
    deny all; 
}
Run Code Online (Sandbox Code Playgroud)

Iva*_*sky 5

您可以尝试使用精确匹配来定义位置(此类位置优先于任何其他位置):

location = / {
    deny all;
}
Run Code Online (Sandbox Code Playgroud)

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

location ~^/[^/]+$ {
    deny all;
}
Run Code Online (Sandbox Code Playgroud)

但这可能会干扰您的 Django 路线。

在这种情况下,你可以重写任何根级请求your_domain/pathyour_domain/path/这个重写规则:

rewrite ^(/[^/]+)$ $1/ last;
Run Code Online (Sandbox Code Playgroud)