nginx 的根目录 为:/home/undoner/nginx-www
nginx 访问地址 为:http://127.0.0.1
本文实现对nginx根目录文件访问的权限控制

(1)nginx指定密码文件格式为:“username:password”,但是password不能为明文,必须经过crypt加密,所以需要用工具产生密码字符串

以下有三种方法:

第一种.

在线直接生成加密字符串:http://tool.oschina.net/htpasswd

第二种

python脚本:“htpasswd.py”,也可以下载。

#!/usr/bin/python
"""Replacement for htpasswd"""
# Original author: Eli Carter import os
import sys
import random
from optparse import OptionParser # We need a crypt module, but Windows doesn't have one by default. Try to find
# one, and tell the user if we can't.
try:
import crypt
except ImportError:
try:
import fcrypt as crypt
except ImportError:
sys.stderr.write("Cannot find a crypt module. "
"Possibly http://carey.geek.nz/code/python-fcrypt/\n")
sys.exit(1) def salt():
"""Returns a string of 2 randome letters"""
letters = 'abcdefghijklmnopqrstuvwxyz' \
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
'0123456789/.'
return random.choice(letters) + random.choice(letters) class HtpasswdFile:
"""A class for manipulating htpasswd files.""" def __init__(self, filename, create=False):
self.entries = []
self.filename = filename
if not create:
if os.path.exists(self.filename):
self.load()
else:
raise Exception("%s does not exist" % self.filename) def load(self):
"""Read the htpasswd file into memory."""
lines = open(self.filename, 'r').readlines()
self.entries = []
for line in lines:
username, pwhash = line.split(':')
entry = [username, pwhash.rstrip()]
self.entries.append(entry) def save(self):
"""Write the htpasswd file to disk"""
open(self.filename, 'w').writelines(["%s:%s\n" % (entry[0], entry[1])
for entry in self.entries]) def update(self, username, password):
"""Replace the entry for the given user, or add it if new."""
pwhash = crypt.crypt(password, salt())
matching_entries = [entry for entry in self.entries
if entry[0] == username]
if matching_entries:
matching_entries[0][1] = pwhash
else:
self.entries.append([username, pwhash]) def delete(self, username):
"""Remove the entry for the given user."""
self.entries = [entry for entry in self.entries
if entry[0] != username] def main():
"""%prog [-c] -b filename username password
Create or update an htpasswd file"""
# For now, we only care about the use cases that affect tests/functional.py
parser = OptionParser(usage=main.__doc__)
parser.add_option('-b', action='store_true', dest='batch', default=False,
help='Batch mode; password is passed on the command line IN THE CLEAR.'
)
parser.add_option('-c', action='store_true', dest='create', default=False,
help='Create a new htpasswd file, overwriting any existing file.')
parser.add_option('-D', action='store_true', dest='delete_user',
default=False, help='Remove the given user from the password file.') options, args = parser.parse_args() def syntax_error(msg):
"""Utility function for displaying fatal error messages with usage
help.
"""
sys.stderr.write("Syntax error: " + msg)
sys.stderr.write(parser.get_usage())
sys.exit(1) if not options.batch:
syntax_error("Only batch mode is supported\n") # Non-option arguments
if len(args) < 2:
syntax_error("Insufficient number of arguments.\n")
filename, username = args[:2]
if options.delete_user:
if len(args) != 2:
syntax_error("Incorrect number of arguments.\n")
password = None
else:
if len(args) != 3:
syntax_error("Incorrect number of arguments.\n")
password = args[2] passwdfile = HtpasswdFile(filename, create=options.create) if options.delete_user:
passwdfile.delete(username)
else:
passwdfile.update(username, password) passwdfile.save() if __name__ == '__main__':
main()

第三种

perl脚本:“htpasswd2.pl”  ,内容如下:

#!/usr/bin/perl
use strict;
my $pw=$ARGV[0];
print crypt($pw,$pw)."\n";

(2)若是第一种方法,直接新建文本复制进去就行;若是第二种或第三种,下载或新建文件后,注意添加可执行权限,再执行脚本生成用户名密码。

第一种:

将网页上面的结果(“2eN4uuMHGaLQQ”即“test1”加密后的字符串)直接复制进 htpasswd 文件中

htpasswd内容:test1:2eN4uuMHGaLQQ

第二种:

chmod 777 htpasswd.py
./htpasswd.py -c -b htpasswd username password

比如:./htpasswd.py -c -b htpasswd undoner undoner    ,得到文件:htpasswd ,内容如下(“dFYOP1Zvmqyfo”即“undoner”加密后的字符串):

htpasswd内容:undoner:dFYOP1Zvmqyfo

第三种:

chmod 777 htpasswd2.pl
./htpasswd2.pl password

比如:./htpasswd2.pl test        ,得到密码字符串:N1tQbOFcM5fpg

可将 ”N1tQbOFcM5fpg“ 复制进 /etc/nginx/htpasswd 文件中,用户名是明文的,所以设什么都行,格式如下:

htpasswd内容:test:N1tQbOFcM5fpg

(3)最后将该密码文件htpasswd复制到nginx的配置文件目录(也可放其他位置,注意改路径+改权限),最后nginx里面添加配置即可。

chmod 777 htpasswd

在sites-available/default添加下面两行内容:

auth_basic "Password";

auth_basic_user_file /etc/nginx/htpasswd;

location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
auth_basic "Password";
auth_basic_user_file /etc/nginx/htpasswd;
charset utf-8;
root /home/undoner/nginx-www;
index index.html index.htm;
autoindex on;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
}

(4)重启nginx

sudo /etc/init.d/nginx restart

Nginx创建密码保护目录的更多相关文章

  1. nginx中给目录增加密码保护实现程序

    一款nginx中给目录增加密码保护实现程序,可以有效的保护一些目录不被访问,有需要的朋友可参考一下. 了防止一些可能出现存在漏洞的后台脚本暴露,使用验证的方式保护这些文件所在的目录 使用apache的 ...

  2. 把 Nginx 创建为 Windows 的一个服务

    译序:Nginx 不是为 Windows 而写.Nginx 是用在软件的工作环境中的.但软件开发环境一般都是 Windows,有时调试的需要也要装 Nginx,但 Nginx 并没给 Windows ...

  3. MFC 创建多层目录

    创建多层目录 BOOL CTestToolCtr::CreateFolder(CString strNewFolder) { /************************************ ...

  4. php使用递归创建多级目录

    <?php header('Content-type:text/html;charset=utf8'); echo "Loading time:".date('Y-m-d H ...

  5. PHP判断文件夹是否存在和创建文件夹的方法(递归创建多级目录)

    在开始之前,我先说明一下,可能许多朋友与我一样认为只要给一个路径,mkdir就可以创建文件夹,其实不是那样,单个的MKDIR只能创建一级目录,对于多级的就不行了,那如何用mkdir来创建呢?先我抄一段 ...

  6. PHP 检查并创建多级目录

    <?php //检查并创建多级目录    function checkDir($path){        $pathArray = explode('/',$path);        $no ...

  7. 如何让nginx显示文件夹目录

    1. 如何让nginx显示文件夹目录 vi /etc/nginx/conf.d/default.conf 添加如下内容: location / {           root /data/www/f ...

  8. 修改nginx的访问目录以及遇到的403错误修改总结

    对于这个问题困扰了我好几天,前篇文章介绍了图片服务器的使用,但是两个服务器如何进行通话访问呢,即如何通过nginx来访问ftp服务器上的资源文件呢,这里面需要修改nginx的配置文件(vi /usr/ ...

  9. VS 创建虚拟目录失败,映射到其他文件夹!

    今天,改一哥们项目!立马,问了一下原因.支支吾吾的气死LZ! 算了,就不信自己琢磨不出来!哼 找了半天,坑爹的是在Web.csproj文件中! 用txt打开,发现这个东东! <UseIIS> ...

随机推荐

  1. SpringCloud学习之SpringCloudStream&集成kafka

    一.关于Spring-Cloud-Stream Spring Cloud Stream本质上就是整合了Spring Boot和Spring Integration,实现了一套轻量级的消息驱动的微服务框 ...

  2. 安装MySQL后出现发生系统错误2或者系统找不到指定的文件

    就是出现如下图所示的情况: 上图中画横线的地方可以看出,sql服务确实安装了.出现这种情况的原因就是服务的默认目录与sql文件的安装目录不一致.这里我个人的MySQL安装路径为D:\mysql-5.7 ...

  3. js删除数组中的元素delete和splice的区别

    例如有一个数组是 :var textArr = ['a','b','c','d']; 这时我想删除这个数组中的b元素: 方法一:delete 删除数组 delete textArr[1]  结果为:  ...

  4. Spring利用反射调用接口

    首先在项目中使用java反射调用 //根据实例及参数名获得方法A Method method = event.getObj().getClass() .getMethod(event.getMetho ...

  5. 了解ASCII、gb系列、Unicode、UTF-8的区别

    转自:http://www.douban.com/note/334994123/?type=rec ● 为什么有这么多编码? ● UTF-8和GB2312有什么区别? ● 我们在国内做网站是用UTF- ...

  6. Kinect SDK2.0 + OpenCV 3.0 抠人,换背景

    使用Kinect2.0的MultiSourceFrameReader,同时获取DepthFrameSource, ColorFrameSource, BodyIndexFrameSource,然后获取 ...

  7. ACM Primes

    Write a program to read in a list of integers and determine whether or not each number is prime. A n ...

  8. Go 语言变量作用域

    作用域为已声明标识符所表示的常量.类型.变量.函数或包在源代码中的作用范围. Go 语言中变量可以在三个地方声明: 函数内定义的变量称为局部变量 函数外定义的变量称为全局变量 函数定义中的变量称为形式 ...

  9. MySQL EXTRACT() 函数

    定义和用法 EXTRACT() 函数用于返回日期/时间的单独部分,比如年.月.日.小时.分钟等等. 语法 EXTRACT(unit FROM date) date 参数是合法的日期表达式.unit 参 ...

  10. Docker创建 tomcat/weblogic 集群

    安装 tomcat 镜像 准备好需要的 jdk.tomcat 等软件放到 home 目录下面,启动一个容器 docker run -t -i -v /home:/opt/data --name mk_ ...