1

I have a web application which is accessed through nginx, which acts as a reverse proxy. However, a subpath of this application is aliased to a directory. The server configuration is as follows:

server {
    # ...

    location /myapp/files {
      alias /var/www/myapp/files;
      auth_basic "Restricted";
      auth_basic_user_file /etc/nginx/htpasswd;
    }

    location /myapp/ {
      proxy_pass http://127.0.0.1:3000/;
      auth_basic "Restricted";
      auth_basic_user_file /etc/nginx/htpasswd;
    }
}

The above setup aliases all requests to /myapp/files regardless of the request method. Is there a way to alias only GET requests to /myapp/files, and proxy the DELETE method to the web application?

Limitations of if prevent something like this being written:

if ($request_method = "GET") {
    location /myapp/files {
      alias /var/www/myapp/files;
      auth_basic "Restricted";
      auth_basic_user_file /etc/nginx/htpasswd;
    }
}

As suggested in the comments, trying to do something like this with my configuration:

location /myapp/files {
    auth_basic Restricted;
    auth_basic_user_file /etc/nginx/htpasswd;

    if ($request_method = "GET") {
      alias /var/www/myapp/files;
    }

    if ($request_method = "DELETE") {
      proxy_pass http://127.0.0.1:3000/;
    }
  }
}

results in:

nginx: [emerg] "alias" directive is not allowed here in /etc/nginx/sites-enabled/default:44

How can I achieve this?

  • Why haven't you used `try_files`? – Michael Hampton Jan 16 '18 at 18:31
  • @MichaelHampton I don't think `try_files` would help here -- requests are always directed at an existing file. –  Jan 16 '18 at 19:06
  • I don't understand. You want to POST to the URL corresponding to a static file, and yet have your web application handle this? – Michael Hampton Jan 16 '18 at 19:10
  • @MichaelHampton It's actually a DELETE method (I'll edit the question to add this). The web application receives the DELETE, removes the file, and does a few database operations. –  Jan 16 '18 at 19:15
  • Hmm. Have you seen [this](https://serverfault.com/a/152764/126632), tried it and confirmed it _does not_ work for you? What happens when you implement this? – Michael Hampton Jan 16 '18 at 20:09
  • @MichaelHampton updated as per your comment, see question. –  Jan 17 '18 at 04:59
  • @user2064000 could you edit the accepted answer with the complete working solution that you have, please? Thanks. – Florin Asăvoaie Jan 17 '18 at 07:43

1 Answers1

1

Try using a series of internal rewrites (not tested, written directly in browser):

location /myapp/files {
  auth_basic "Restricted";
  auth_basic_user_file /etc/nginx/htpasswd;
  rewrite ^(/myapp/files)(.*) $1.$request_method$2 break;
}

location /myapp/files.GET {
  alias /var/www/myapp/files;
  internal;
}

location /myapp/files.DELETE {
  rewrite ^/myapp(/files)(.*) $1$2 break;
  proxy_pass http://127.0.0.1:3000/;
  internal;
}
Florin Asăvoaie
  • 7,057
  • 23
  • 35