Apache Utils
我們需要htpassword來創(chuàng)建和生成加密的用戶用于基礎(chǔ)認(rèn)證(Basic Authentication)。通過以下命令安裝apache2-utils。
sudo apt-get install apache2-utils
創(chuàng)建用戶名和密碼
在Nginx托管的網(wǎng)站目錄下生成一個(gè).htpasswd文件。如下的命令可以創(chuàng)建文件同步增加用戶和加密的密碼到文件中
sudo htpasswd -c /etc/nginx/.htpasswd exampleuser
命令行為提示你輸入密碼
New password:
Re-type new password:
Adding password for user exampleuser
htpaswd的文件格式如下:
login:password
注意:htpasswd需要對(duì)nginx運(yùn)行用戶可訪問
更新Nginx配置
在你的網(wǎng)站的Nginx配置文件增加如下兩行:
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
第二行是你的htpasswd文件位置。
舉個(gè)例子,假如你的文件是/etc/nginx/sites-available/website_nginx.conf,通過vi或者其它編輯器打開該文件
sudo vi /etc/nginx/sites-available/website_nginx.conf
增加代碼:
server {
listen portnumber;
server_name ip_address;
location / {
root /var/www/mywebsite.com;
index index.html index.htm;
auth_basic "Restricted"; #For Basic Auth
auth_basic_user_file /etc/nginx/.htpasswd; #For Basic Auth
}
}
刷新Nginx
為了使配置生效,需要刷新nginx配置,然后再訪問
$ sudo /etc/init.d/nginx reload
* Reloading nginx configuration...