使用nginx保护单个文件的密码

时间:2014-08-29 09:35:57

标签: authentication nginx

我尝试使用密码保护文件的位置阻止说admin.php无效.Below是我的nginx配置

location = /admin.php {
             root /var/www/site.com/public_html/www;
             index index.php index.html index.htm;
             auth_basic            "Restricted Area";
             auth_basic_user_file  /var/www/site.com/public_html/htpasswd;
        }

location ~* \.php$ { 
    root /var/www/site.com/public_html/www;
    try_files $uri =404;
    fastcgi_pass   unix:/tmp/php5-fpm.sock;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
    fastcgi_read_timeout 300;
}

我尝试将location = /admin.php {更改为location ~/admin\.php$ {location /admin.php {,但没有一项工作

admin.php的网址是:https://mysite.com/admin.php

是的,我在每次尝试后都重新加载了nginx

亲切的问候

1 个答案:

答案 0 :(得分:5)

我有点晚了,但这是你正在寻找的规则:

location ~ /admin\.php$ {
    auth_basic "Restricted Area";
    auth_basic_user_file /path/to/.htpasswd;
    root /var/www/site.com/public_html/www;
    try_files $uri =404;
    fastcgi_pass   unix:/tmp/php5-fpm.sock;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
    fastcgi_read_timeout 300;
}

您需要在PHP文件的位置块中包含fastcgi处理。希望这有助于某人!