当我们使用 Nginx 时,碰巧我们想要限制对某些 URL 和/或端点的访问。因此,为此,我们需要在 Nginx 中设置身份验证,这就是我们今天将要看到的。

密码文件
为了让用户能够登录,Nginx 必须有一个名为的文件,htpasswd该文件将包含每个用户的名称及其密码,格式如下:

user1:password1
user2:password2
...

用户名是明文形式,但密码是用BCrypt加密的。

生成此文件的最简单方法是使用工具htpasswd.

安装 htpasswd
这个工具可以在包中找到apache2-utils,你可以使用以下命令安装它:

sudo apt-get update
sudo apt-get install apache2-utils

使用 htpasswd
该命令具有以下格式:

htpasswd [options] [file path] [user name to add]

要知道的选项-c将帮助我们创建文件。

然后,你只需要使用命令添加每个想要的用户!

例子

# Create the file & add the user toto
htpasswd -c /etc/nginx/htpasswd toto

# Add another user to an existing file
htpasswd /etc/nginx/htpasswd titi

配置 Nginx
最后一步是配置 Nginx 实例。所以在你的配置文件中,像下面的例子一样添加auth_basic&参数,它应该是好的!auth_basic_user_file

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.html index.htm;

    server_name localhost;

    location / {
        try_files $uri $uri/ =404;
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

我希望它能帮助你!🍺当我们使用 Nginx 时,碰巧我们想要限制对某些 URL 和/或端点的访问。因此,为此,我们需要在 Nginx 中设置身份验证,这就是我们今天将要看到的。

密码文件
为了让用户能够登录,Nginx 必须有一个名为的文件,htpasswd该文件将包含每个用户的名称及其密码,格式如下:

user1:password1
user2:password2
...

用户名是明文形式,但密码是用BCrypt加密的。

生成此文件的最简单方法是使用工具htpasswd.

安装 htpasswd
这个工具可以在包中找到apache2-utils,你可以使用以下命令安装它:

sudo apt-get update
sudo apt-get install apache2-utils

使用 htpasswd
该命令具有以下格式:

htpasswd [options] [file path] [user name to add]

要知道的选项-c将帮助我们创建文件。

然后,你只需要使用命令添加每个想要的用户!

例子

# Create the file & add the user toto
htpasswd -c /etc/nginx/htpasswd toto

# Add another user to an existing file
htpasswd /etc/nginx/htpasswd titi

配置 Nginx
最后一步是配置 Nginx 实例。所以在你的配置文件中,像下面的例子一样添加auth_basic&参数,它应该是好的!auth_basic_user_file

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.html index.htm;

    server_name localhost;

    location / {
        try_files $uri $uri/ =404;
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

我希望它能帮助你!🍺

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐