14

i thought this would work but for some reason it skips the auth_basic and always returns 200. Same happens if i swap 200 for a 301 redirect.

If i comment out the return statement it works ok. Ideally i want just an /auth endpoint that once authenticated it will 301 redirect to another path.

 location /auth {
     auth_basic_user_file /etc/nginx/.htpasswd;
     auth_basic "Secret";

     return 200 'hello';
  }

Am i missing something ?

many thanks

fLo

Flo Woo
  • 949
  • 1
  • 12
  • 26

1 Answers1

17

return-directives are executed before most other directives. To solve your problem you need to split this into two locations:

location /auth {
  auth_basic_user_file /etc/nginx/.htpasswd;
  auth_basic "Secret";
  try_files DUMMY @return200;
}

location @return200 {
  return 200 'hello';
}

The try_files-directive is evaluated after auth_basic. The second location is evaluated only as a result of try_files.

Digitalkapitaen
  • 2,353
  • 13
  • 17
  • OK thanks, confirmed working. I tried to find some documentation that confirms this but wasn't able to find it on nginx site or else where. If anyone has some where that confirm this is expected behaviour or maybe a bug ? thanks. – Flo Woo Nov 07 '16 at 12:00
  • I have never found official documentation about this. The source code confirms this behavior and there this presentation: http://de.slideshare.net/joshzhu/nginx-internals , see slide 37 and following. The `return`-directive belongs to the rewrite module. Also this article: http://www.nginxguts.com/2011/01/phases/ – Digitalkapitaen Nov 08 '16 at 09:52
  • This doesn't work when you also want to set a cookie. add_header Set-Cookie "foo=bar" before try_files does nothing. – Rihad Aug 07 '18 at 18:33
  • @Rihad The add_header directive needs to come in the named location (before the return), then the cookie is written. This is because the request is actually handled in this location, i.e. the content and headers are created there. – Digitalkapitaen Aug 08 '18 at 12:29