Nginx创建密码保护目录
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创建密码保护目录的更多相关文章
- nginx中给目录增加密码保护实现程序
一款nginx中给目录增加密码保护实现程序,可以有效的保护一些目录不被访问,有需要的朋友可参考一下. 了防止一些可能出现存在漏洞的后台脚本暴露,使用验证的方式保护这些文件所在的目录 使用apache的 ...
- 把 Nginx 创建为 Windows 的一个服务
译序:Nginx 不是为 Windows 而写.Nginx 是用在软件的工作环境中的.但软件开发环境一般都是 Windows,有时调试的需要也要装 Nginx,但 Nginx 并没给 Windows ...
- MFC 创建多层目录
创建多层目录 BOOL CTestToolCtr::CreateFolder(CString strNewFolder) { /************************************ ...
- php使用递归创建多级目录
<?php header('Content-type:text/html;charset=utf8'); echo "Loading time:".date('Y-m-d H ...
- PHP判断文件夹是否存在和创建文件夹的方法(递归创建多级目录)
在开始之前,我先说明一下,可能许多朋友与我一样认为只要给一个路径,mkdir就可以创建文件夹,其实不是那样,单个的MKDIR只能创建一级目录,对于多级的就不行了,那如何用mkdir来创建呢?先我抄一段 ...
- PHP 检查并创建多级目录
<?php //检查并创建多级目录 function checkDir($path){ $pathArray = explode('/',$path); $no ...
- 如何让nginx显示文件夹目录
1. 如何让nginx显示文件夹目录 vi /etc/nginx/conf.d/default.conf 添加如下内容: location / { root /data/www/f ...
- 修改nginx的访问目录以及遇到的403错误修改总结
对于这个问题困扰了我好几天,前篇文章介绍了图片服务器的使用,但是两个服务器如何进行通话访问呢,即如何通过nginx来访问ftp服务器上的资源文件呢,这里面需要修改nginx的配置文件(vi /usr/ ...
- VS 创建虚拟目录失败,映射到其他文件夹!
今天,改一哥们项目!立马,问了一下原因.支支吾吾的气死LZ! 算了,就不信自己琢磨不出来!哼 找了半天,坑爹的是在Web.csproj文件中! 用txt打开,发现这个东东! <UseIIS> ...
随机推荐
- C语言第二次作业 ,
一:修改错题 1输出带框文字:在屏幕上输出以下3行信息. 将源代码输入编译器 运行程序发现错误 错误信息1: 错误原因:将stido.h拼写错误 改正方法:将stido.h改为stdio.h 错误信息 ...
- MySQL使用判断
1.case语法 在第一个方案的返回结果中, value=compare-value.而第二个方案的返回结果是第一种情况的真实结果.如果没有匹配的结果值,则返回结果为ELSE后的结果,如果没有ELSE ...
- 关于thymeleaf th:replace th:include th:insert 的区别
关于thymeleaf th:replace th:include th:insert 的区别 th:insert :保留自己的主标签,保留th:fragment的主标签. th:re ...
- rabbitMQ权限相关命令
权限相关命令为: (1) 设置用户权限 rabbitmqctl set_permissions -p VHostPath User ConfP WriteP ReadP (2) 查看(指 ...
- js页面(页面上无服务端控件,且页面不刷新)实现请求一般处理程序下载文件方法
对于js页面来说,未使用服务端控件,点击下载按钮时不会触发服务端事件,且不会提交数据到服务端页面后台进行数据处理,所以要下载文件比较困难.且使用jQ的post来请求一般处理程序也不能实现文件的下载,根 ...
- ubuntu 英文系统下安装中文输入法
环境:ubuntu15.10 64位 英文版 软件:fcitx输入法框架,及多种拼音输入法 linux的英文系统会比中文少很多麻烦,特别是在命令行输入路径的时候,如果路径是中文将是一件很头疼的问题.但 ...
- scratch写的图灵机
大多数人对于scratch不感冒,因为觉得这是孩子玩的.的确,积木的方式不适合专业程序员写代码,然而别小看scratch,怎么说,它也是图灵完备的.而且,过程支持递归,虽然带不了返回值. 虽然计算速度 ...
- git使用之错误分析及解决(持续更新)
错误一: 使用 $ git push -u origin master 出现如下错误: error: src refspec master does not match any. error: fai ...
- blog写作心得体会
虽然写blog也挺久了,写出来的东西自己回顾的时候也会怀疑读者是否能看的明白,还是有种流水账的感觉,以后希望多从读者的角度出发.下面记录一些以后写博客的注意点. 具体关于某种技术点的小知识还有碰到的各 ...
- Lucene总结
数据的分类 结构化数据:有固定类型或者有固定长度的数据 例如:数据库中的数据(mysql,oracle等), 元数据(就是windows中的数据) 结构化数据搜索方法: 数据库中数据通过sql语句可以 ...