让nginx列目录及对目录进行密码保护

1、如何让nginx列目录

在对应的网站配置段中,加入:

location /_files

{

    root /home/blog.creke.net;

    autoindex on;

    autoindex_exact_size off;

    autoindex_localtime on;

}

解释一下:

root是指当前的网站根文件夹,例子中列出的根目录其实是/home/blog.creke.net/_files目录,如果不填则沿用上层的root配置;

autoindex是是否对该location匹配的目录在找不到索引文件(index.html、index.php等)时,列出目录,默认为off;

autoindex_exact_size是是否输出准确的大小,如果on则输出byte单位的大小,off则用GB、MB、KB来近似表示,默认为on;

autoindex_localtime是否以服务器时间输出文件时间,off则用GMT时间输出,默认为off。

参考:http://wiki.nginx.org/HttpAutoindexModule

2、对目录进行密码保护:

在对应目录的location中加入:

auth_basic "Creke Server Auth";

auth_basic_user_file /usr/local/nginx/conf/htpasswd;

其中auth_basic是验证时显示的标题,auth_basic_user_file是对应的用户名密码,一行一个,与apache的“.htpasswd”一样。

参考:http://wiki.nginx.org/HttpAuthBasicModule

最后,给出一个使用perl生成htpasswd中认证用户名密码的脚本,方便生成:

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo "====================================="
echo "# A tool like htpasswd for Nginx    #"
echo "#-----------------------------------#"
echo "# MOD BY Creke                      #"
echo "====================================="

#set UserName

	username=""
	read -p "Please input UserName:" username
	if [ "$username" = "" ]; then
		echo "Error:UserName can't be NULL!"
		exit 1
	fi
	echo "==========================="
	echo "UserName was: $username"
	echo "==========================="

#set password

	unpassword=""
	read -p "Please input the Password:" unpassword
	if [ "$unpassword" = "" ]; then
		echo "Error:Password can't be NULL!"
		exit 1
	fi
	echo "==========================="
	echo "Password was: $unpassword"
	echo "==========================="
password=$(perl -e 'print crypt($ARGV[0], "pwdsalt")' $unpassword)

echo "$username:$password"

Leave a comment