nginx:auth_basic和php

时间:2011-01-14 23:25:44

标签: php authentication nginx

我想使用auth_basic使用密码保护我网站的文件夹。该文件夹包含php脚本,如果请求它们应该执行。

我尝试了以下内容:

location /admin {
  auth_basic    "Admin-Section";
  auth_basic_user_file /myfolder/.htpasswd;
 }

 location ~ ^/admin/.*\.php$ {
  auth_basic    "Admin-Section";
  auth_basic_user_file /myfolder/.htpasswd;
  fastcgi_pass 127.0.0.1:9000;
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
  include   fastcgi_params;
 }

在请求该admin文件夹中的php脚本时,我会被要求输入用户名/密码,但是php脚本将永远被下载而不是通过fastcgi执行。

我做错了什么?

编辑:在我的本地计算机上,一切正常,这种配置。 O0
编辑:顺便说一句,PHP正在admin-folder外面使用相同的fastcgi-options 编辑:天啊!该站点的配置存储在/ etc / nginx / sites-available / mysite和/ etc / nginx / sites-enabled /包含mysite文件的符号链接。因为有些时候改变mysite文件没有效果。例如。将所有位置更改为“拒绝所有”都没有效果。这些文件没有问题 所以我删除了符号链接并重新启动了服务器。然后我再次创建了符号链接,重新启动了服务器,一切都按预期工作。有人可以解释这种奇怪的行为吗?

Gest问候,
大不了

4 个答案:

答案 0 :(得分:12)

使用此配置,nginx将仅匹配两个块中的一个 - 具有最高优先级的块。

解决方案是将PHP块组合到 AUTH块中。这是nginx作者自己推荐的方法,Igor Sysoev。

location /admin/ {
  auth_basic    "Admin-Section";
  auth_basic_user_file /myfolder/.htpasswd;
  location ~ \.php$ {
   fastcgi_pass  127.0.0.1:9000;
   fastcgi_index index.php;
   fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
   include       fastcgi_params;
  }
}

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

答案 1 :(得分:1)

这是一个老问题,但我遇到了同样的问题,所以这里是解释。

Nginx使用the rules described in the docs来匹配位置块。对于常规块,最长匹配将是将要应用的块,但对于正则表达式,始终是将应用的第一个匹配块。

在您的生产服务器中,您很可能在管理块上方有一个location ~ \.php$块,因此您发布的监听块从未应用过。

长短篇小说:当处理nginx中的正则表达式侦听块时,顺序很重要。将更具体的匹配放在一般匹配之前。

答案 2 :(得分:-1)

您需要删除以下行:

fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;

答案 3 :(得分:-1)

也许你忘了添加root:

location ~ .\php$ {
    #Lines of code...
    root /your/document/root;
    #Lines of code...
}

location /admin/ {
    #Lines of code...
    root /your/document/root;
    #Lines of code...
}