【问题标题】:NGINX - auth basic if $arg contains 'admin'NGINX - 如果 $arg 包含 'admin' 则基本身份验证
【发布时间】:2015-02-06 12:05:04
【问题描述】:

我试图让我的管理员控制器通过 auth_basic 身份验证。这就是我的 nginx 配置的样子:

location /index.php {
   if ($arg_r ~ admin) {
        auth_basic                          "Restricted";
        auth_basic_user_file                /etc/nginx/mywebsite/.htpasswd;
   }
}

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_script_name;
    fastcgi_pass php;
 }

当请求在 arg r 中包含“admin”时,我需要提示身份验证,例如:

  • /index.php?r=admin -> 授权
  • /index.php?r=admin/anythinghere -> 验证
  • /index.php?r=site/index -> 无授权

但不工作,我做错了什么?

【问题讨论】:

    标签: nginx basic-authentication


    【解决方案1】:

    根据文档,auth_* 在“if”中是不允许的。也许这可以解决问题:

    location = /index.php {
       if ($arg_r ~ admin) {
          rewrite ^ /_admin/index.php$is_args$args last;
       }
       include fastcgi_params;
       fastcgi_index index.php;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_param PATH_INFO $fastcgi_script_name;
       fastcgi_pass php;
    }
    
    location /_admin/index.php {
       internal;
       auth_basic                          "Restricted";
       auth_basic_user_file                /etc/nginx/mywebsite/.htpasswd;
       include fastcgi_params;
       fastcgi_index index.php;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_param PATH_INFO $fastcgi_script_name;
       fastcgi_pass php;
    }
    location ~ \.php$ {
       include fastcgi_params;
       fastcgi_index index.php;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_param PATH_INFO $fastcgi_script_name;
       fastcgi_pass php;
    }
    

    只是复制了启用身份验证的位置。 “内部”指令将直接请求限制在此位置。 请注意,我在第一个位置添加了“=”,它可以避免将 /index.phpadasdasdsdfadsf 重写为 /_auth/index.php

    【讨论】:

    • 嗯,如果我按照你所说的那样更正了我的配置,转到 /index.php 会下载名为“Download”的 index.php,但在 index.php?r=admin 询问我要认证。什么鬼?
    • 您需要包含用于处理 php 的任何机制(例如 fastcgi 或代理)来代替他的 cmets,没有它“.php”文件只是文件。
    • 我有位置 ~ \.php 在配置的末尾
    • 确切位置 = /index.php 优先于正则表达式
    • 那么,我应该将 \.php 位置内容放入 /index.php 和 /_admin/index.php 吗?
    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 2016-01-11
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多