Search code examples
authenticationnginxbasic-authentication

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


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 URI deliver different content based on the name of the currently authenticated user.

For instance, let's say a browser requested URI /index.html. If the browser was authenticated as user "developer", then it could be served the file /index_developer.html. If instead the browser was authenticated as "administrator" it could be served the file /index_administrator.html.

I only want this redirection to occur on a small set of files; most will be served as-is. I'd also need to block direct access to the actual files so that nobody could do an end-run around the system.


Solution

  • First, there is variable $remote_user.

    I've end up with following structure:

    $ tree
    .
    ├── _auth
    │   ├── admin
    │   │   ├── f
    │   │   │   └── index.html
    │   │   ├── hello.html
    │   │   └── index.html
    │   └── user
    │       ├── f
    │       │   └── index.html
    │       └── index.html
    ├── f
    │   └── x.html
    ├── hello.html
    ├── test.html
    └── x
        └── index.html
    

    and this nginx config:

    auth_basic "Restricted area";
    auth_basic_user_file path/to/passwd/file;
    
    root /path/to/root;
    
    location / {
        try_files /_auth/$remote_user$uri
                  /_auth/$remote_user$uri/index.html
                  $uri $uri/index.html =404;
    }
    
    location /_auth/ {
        internal;
    }
    

    So request to / will end up in /_auth/USER/index.html, request to /test.html will serve /test.html. And request to /hello.html will serve /_auth/admin/hello.html for user admin and /hello.html for any other user.

    Direct access to /_auth/.. is forbidden by internal directive.