1. 程式人生 > >Nginx下配置Http Basic Auth保護目錄

Nginx下配置Http Basic Auth保護目錄

Nginx下的配置也挺方便的,我們可以沿用由Apache的htpasswd模組生成的.htpasswd檔案作為密碼檔案。注意,nginx 的 http auth basic 的密碼是用 crypt(3) 加密的,而apache是md5加密。所以生成時:

/usr/local/apache2/bin/htpasswd -c -d pass_file user_name
#回車輸入密碼,-c 表示生成檔案,-d 是以 crypt 加密。
對於lnmp使用者,一般不安裝apache,說下怎麼在nginx下生成htpasswd

執行示例

chmod 777 htpasswd.py
./htpasswd.py -c -b htpasswd username password
#-c為生成檔案 htpasswd為檔名

我們將這個htpasswd檔案放到nginx/conf下,記得chmod 400 htpasswd來保護一下。

然後修改nginx.conf:

server {
    server_name d8.neolee.com;
    root /var/www/d8.neolee.com;
    include /etc/nginx/fastcgi_php;
    location / {
	auth_basic            "Password please";
	auth_basic_user_file  /usr/local/nginx/conf/htpasswd;
        index index.php;
        if (!-e $request_filename) {
            rewrite ^(.*)$  /index.php last;
        }
    }
}

加入了

	auth_basic            "Password please";
	auth_basic_user_file  /usr/local/nginx/conf/htpasswd;

重啟nginx即可。

來源:http://neolee.com/web/nginx-http-basic-auth/