Configure nginx to return different files to different authenticated users with the same URI

前端 未结 3 1067
被撕碎了的回忆
被撕碎了的回忆 2021-01-22 11:54

I\'m using nginx to serve static files in an embedded system, with no CGI back-end. I have basic-authentication up with multiple username/passwords. I\'d like to have a specific

3条回答
  •  太阳男子
    2021-01-22 12:59

    Although I'm accepting Alexy Ten's answer, as his insight was what got me there, I ended up using a slightly different scheme.

    Instead of having the user-specific files residing in a completely separate tree, I chose to have them live right next to the generic files, but adding a standard prefix of _user__. For instance, I might have the following two files in the webroot:

    1. /scripts/menus.js
    2. /scripts/_user_developer_menus.js

    Then, if logged in as user "developer", a request for /scripts/menus.js would be served the second file, but with any other user the first file would be served.

    Here is the core of my nginx configuration:

    location ~ "^.*/_user_[^/]*$" {
        internal;
    }
    
    location ~ "^(.*)/([^/]*)$" {
        auth_basic_user_file /opt/product/cfg/nginx_conf/htpasswd;
        try_files   $1/_user_${remote_user}_$2$is_args$args
                    $1/_user_${remote_user}_$2/index.html$is_args$args
                    $1/$2$is_args$args
                    $1/$2/index.html$is_args$args
                    =404;
    }
    

    Since both locations are as specific (both regexes) they're searched in order. So, the first location blocks direct access to any of the _user__ files. The second location matches any URL, with the path up to the file name left in $1, and the file name left in $1. Then, the try_files looks for a user-specific file, a user-specific directory, a common file, and a common directory, in that order, until it gives up with a 404 error.

提交回复
热议问题