我正尝试将HTTPauthentication应用到我的大部分网站,除了首页,path/welcome
和separate / admin /,/ services /和/ stats / sections。
我似乎没有做到这一点, 这是我目前的configuration:
location ~ ^/(admin|services|stats)/ { # L1 # don't need http auth at this path as there is separate auth proxy_pass http://myapp-admin-cluster; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { #L2 location ~ /(?!welcome).+ { #L3 auth_basic "MyApp"; auth_basic_user_file /var/www/myapp/htpasswd; } proxy_pass http://myapp-web-cluster; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; }
问题是如果我导航到/admin/
我得到HTTP 404,而不是我的请求被转发到myapp-admin-cluster代理(也不会转发到myapp-web-cluster代理)。
Q1:为什么在L2主体中定义的代理设置不适用于匹配L3的path?
Q2:为什么嵌套位置L3覆盖L1? 他们都是正则匹配,所以肯定它应该匹配第一个? 引用自nginx doc:“然后按照正则expression式在configuration文件中出现的顺序检查正则expression式,正则expression式的search在第一个匹配时终止”
因为基本上位置/将匹配任何url模式,所以当你不能匹配pipe理string时,你将匹配/ block下的规则。
从规则L3中,您匹配除匹配/欢迎之外的所有页面,因此您将redirect到执行基本身份validation。
更新:
由于作者已经更新了他的问题,位置块应该被更新,我也怀疑Nginx在redirect的时候找不到应该显示哪个文件,我build议也放一个索引部分 :
location ~* ^/(admin|services|stats)/ { index index.html; ...
由于您正在使用url进行代理,因此您需要在http:// myapp-admin-cluster下有相应的文件
例如,我们有以下url:
http://<your_webserver_IP or DNS>/admin/1.html
您将被redirect到:
http://myapp-admin-cluster/admin/1.html
但不是:
http://myapp-admin-cluster/
希望它会给你一些提示来解决你的问题。