Hugh's Blog

Nginx 用户认证

一般的 Web 服务器都提供了用户认证登录系统,用于限制用户访问某些路径,需要登录认证之后才能继续访问网站 (比如后台管理),开启也很简单,以 Nginx 为例,做个记录。

创建用户密码文件

通过 OpenSSL 创建

# Add user
sudo echo -n 'admin:' >> /etc/nginx/.htpasswd
# Add an encrypted password
sudo openssl passwd -apr1 >> /etc/nginx/.htpasswd
# Password: (your password)
# Verifying - Password: (repeat your password)
# Check if added
cat /etc/nginx/.htpasswd
# Output admin(admin)
admin:$apr1$xpcwUTed$IOI18VsDIv3rmzIIJhXbk1

通过 htpasswd 命令创建

需要安装 apache2-utils

sudo apt-get update
sudo apt-get install apache2-utils
# Add user
sudo htpasswd -c /etc/nginx/.htpasswd admin
# Will be asked to supply and confirm a password for the user.
# Check if added
cat /etc/nginx/.htpasswd

Nginx 开启用户认证

sudo vim /etc/nginx/sites-available/default

修改配置:

server {
    # ...
    location / {
        try_files $uri $uri/ =404;

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

重启 Nginx:

sudo nginx -t
sudo service nginx restart

Nginx 用户认证只是提供了简单的验证功能,最好还是跟 SSL 加密一起使用。

2017-08-07

Apache 下可以通过修改 .htaccess 来添加认证,密码文件格式与 Nginx 一样。

AuthType Basic
AuthName "Password Required"
#AuthBasicProvider file
AuthUserFile "/path/to/.htpasswd"
Require valid-user

2018-03-20

今天在一个伪静态网站下为子目录添加认证时遇到问题,比如 WordPress,下面是根目录的 .htaccess 内容:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

子目录下的 .htaccess 内容,比如 sub:

AuthType Basic
AuthName "Password Required"
AuthUserFile "/path/sub/.htpasswd"
Require valid-user

但是打开网站 http://example.com/sub/ 却显示 404 错误,原因是当打开子目录链接时,此时并未进行认证,抛出 401,而且并未发送到浏览器,又返回到伪静态的配置中去匹配,所以返回 404,解决方法是在 .htaccess 指定 401 的返回信息给浏览器,只需在根目录的 .htaccess 添加:

// Added
ErrorDocument 401 default

参考

How To Set Up Password Authentication with Nginx on Ubuntu 14.04

Authentication and Authorization

Password Protect a WordPress Subdirectory with .htaccess