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. Codeforces Round #430 D. Vitya and Strange Lesson

    Today at the lesson Vitya learned a very interesting function - mex. Mex of a sequence of numbers is ...

  2. 实现PC视频播放最强画质教程( Potplayer播放器+MADVR插件)【转】

    转自:http://www.hangge.com/blog/cache/detail_1461.html 一.MADVR介绍 MADVR 是一款超强的视频插件,其配合高清播放软件,可以做到目前 PC  ...

  3. django rest-framework 1.序列化 二

    在上一节说了Serializers的使用类似Django的From,在Django中有From也有ModelFrom,Serializers也是有个ModelSerializers,下面在讲讲rest ...

  4. Android智能手机中各种音频场景下的audio data path

    上一篇文章(Android智能手机上的音频浅析)说本篇将详细讲解Android智能手机中各种音频场景下的音频数据流向,现在我们就开始.智能手机中音频的主要场景有音频播放.音频录制.语音通信等.不同场景 ...

  5. python 程序中调用go

    虽然python优点很多,但是有一个致命的缺点就是运行速度太慢,那么python程序需要一些计算量比较大的模块时一般会调用c或者c++的代码来重写,但是c/c++编写代码代价太高,耗费太多的人力.那么 ...

  6. 记录一次widora sdk编译ipk 实战编译redis

      因为业务需求,需要用到redis存储一点简单的数据,因为redis有良好的哈希机制,可以完美实现我的某些需求,但openwrt官方提供memcached的ipk并没有提供redis,没办法,只能自 ...

  7. IScroll.js 学习笔记

    一.css部分1.transform 旋转div { transform:rotate(7deg); -ms-transform:rotate(7deg); /* IE 9 */ -moz-trans ...

  8. sublime text3中设置Emmet输入标签自动闭合

    项目后端前一段时间从C#转成了JAVA,在开发的过程中,由于HTML对标签的语法很宽松,比如这样:<img src="" alt="">在标签的结尾 ...

  9. 一口一口吃掉Hibernate(七)——继承映射

    前几篇博文中讲到了常用的几种关联映射.其实hibernate中还有一种"省劲儿"的映射,那就是--"继承映射". 学了这么多的关系映射了,继承映射,从字面上也能 ...

  10. leetcode刷题笔记326 3的幂

    题目描述: 给出一个整数,写一个函数来确定这个数是不是3的一个幂. 后续挑战:你能不使用循环或者递归完成本题吗? 题目分析: 既然不使用循环或者递归,那我可要抖机灵了 如果某个数n为3的幂 ,则k=l ...