17

我已按照说明进行操作,但仍然无法使用密码保护我的网站。这就是我的 app-nginx.config 的样子:

server {
    listen       80;
    server_name  Server_Test;
    auth_basic            "Restricted";
    auth_basic_user_file  /usr/local/nginx/conf/htpasswd;

...

}

我哪里错了?我从一个教程网站复制并粘贴了这个。

4

2 回答 2

18

确保 Nginx 可以访问密码文件。auth_basic_user_file 的路径是相对于nginx.conf. 因此,如果您nginx.conf位于,/usr/local/nginx您可以将指令更改为:

auth_basic_user_file  conf/htpasswd;

并且文件必须是可读的。

这个文件应该可以被工作人员读取,从非特权用户运行。例如。当 nginx 从 www 运行时,您可以将权限设置为:

chown root:nobody htpasswd_file
chmod 640 htpasswd_file

-- 来自http://wiki.nginx.org/HttpAuthBasicModule

于 2012-09-17T22:43:59.500 回答
9

刚刚让我的 nginx 服务器工作,甚至配置它来保护我的根文件夹访问。我想与您分享我的发现,并在此过程中对本页中的问题给出一个很好且有效的答案。

作为 nginx 的新用户(版本 1.10.0 - Ubuntu)。我遇到的第一个问题是知道文件位置,所以这里是关键位置:

了解您的位置:

主文件夹位置: /etc/nginx

默认站点位置:/var/www/甚至/ver/www/html/html文件夹内将是index.html文件 - 希望您知道从那里做什么。)

配置文件:

主要配置文件:/etc/nginx/nginx.conf

当前站点服务器配置:(/etc/nginx/sites-enabled在第一次安装时,那里有一个名为 的文件default,您需要使用sudo它才能更改它(例如 sudo vi default:)

添加密码:

所以,既然 e 知道播放器(无论如何都是静态的开箱即用网站),让我们将一些文件放在“html”文件夹中,并为其添加密码保护。

要设置密码,我们需要做 2 件事: 1. 创建一个密码文件(有尽可能多的用户,但我会选择 1)。2. 配置当前服务器('default')来限制这个页面,并使用1中的文件来启用密码保护。

1.让我们创建一个密码:

我想为此使用的行是:( sudo htpasswd -c /etc/nginx/.htpasswd john您将收到输入并重新输入密码的提示)您可以在此处的一行中执行此操作: sudo htpasswd -c /etc/nginx/.htpasswd john [your password]

我将解释命令的每个部分:

  • sudo htpasswd- 使用更高的权限进行操作。
  • -c - for:创建文件(将另一个用户添加到现有用户跳过此参数)
  • /etc/nginx/.htpasswd- 创建的文件的名称(文件夹 /etc/nginx 中的“.htpsswd”)
  • john是用户名(在提示的“用户”字段中输入)
  • password是此特定用户名所需的密码。(提示时..)

通常该htpasswd命令对您不起作用,因此您必须安装它的包:

使用:(sudo apt-get install apache2-utils如果失败请尝试使用并重sudo apt-get update试)

2.让我们配置服务器使用这个文件进行身份验证

让我们使用这一行来编辑当前(默认)服务器 conf 文件:

sudo vi /etc/nginx/sites-enabled/default(你不必使用'vi',但我喜欢它..)

删除大部分注释后文件看起来像这样 (#)

# Default server configuration
#
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

}

我们需要在块中添加两行位置('/' 指向站点的根文件夹),所以它看起来像这样:

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;

        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
     }

我将解释这些新行:

  • auth_basic "Restricted Content";- 定义访问管理的类型
  • auth_basic_user_file /etc/nginx/.htpasswd;- 将我们创建的文件 (/etc/nginx/.htppasswd) 定义为此身份验证的密码文件。

让我们重新启动服务并享受受密码保护的网站:

sudo service nginx restart

中提琴- 享受...

这里有一些更棒的教程:

很好的解释

另一个goo教程

于 2017-05-25T13:45:18.490 回答