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> ...
随机推荐
- 【Git】CentOS7 通过源码安装Git
yum源仓库里的Git版本更新不及时,最新版的Git是1.8.3,但是官方的最新版早已经更新到2.9.5.想要安装最新版本Git,只能下载源码进行安装 建议最好更新git为较新版本,便于使用 1.查看 ...
- 笔记12 注入AspectJ切面
虽然Spring AOP能够满足许多应用的切面需求,但是与AspectJ相比, Spring AOP 是一个功能比较弱的AOP解决方案.AspectJ提供了Spring AOP所不能支持的许多类型的切 ...
- Maven的pom.xml文件结构之基本配置packaging和多模块聚合结构(微服务)
1. packaging packaging给出了项目的打包类型,即作为项目的发布形式,其可能的类型.在Maven 3中,其可用的打包类型如下: jar,默认类型 war ejb ear rar pa ...
- 用JavaScript按一定格式解析出URL 串中所有的参数
1.先看看location对象 2.其中的search属性就获取当前URL的查询部分(问号?之后的部分) 3.改造location.search 比如当前URL为:https://www.hao123 ...
- 77. Combinations(medium, backtrack, 重要, 弄了1小时)
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For exampl ...
- python学习之路前端-jQuery
jQuery简介 JQuery是继prototype之后又一个优秀的Javascript库.它是轻量级的js库 ,它兼容CSS3,还兼容各种浏览器(IE 6.0+, FF1.5+, Safa ...
- 利用Python进行数据分析——Ipython
利用Python进行数据分析--Ipython 一.Ipython一些常用命令 1.TAB自动补全 2.变量+? 显示相关信息 3.函数名+??可以获取函数的代码 4.使用通配符* np.load? ...
- page1
1.1 常用的客户端技术:HTML. CSS. 客户端脚本技术 1.2 常用的服务器端技术:CGI .ASP .PHP (一种开发动态网页技术).ASP.NET(是一种建立动态web应用程序的技术,是 ...
- webpack4.1.1的使用详细教程
安装全局webpack cnpm install -g webpack 安装全局webpack-cli npm install -g webpack-cli 初始化:生成package.json文件 ...
- 实验与作业(Python)-03 Python程序实例解析
截止日期: 要求: 下周实验课前上交,做好后在实验课上检查可获取平时分. 做出进阶或选做的的请用清晰的标致标识出来,方便老师批改 本次作业:可提交也可不提交.作业算平时成绩. 本次作业内容量较大,请组 ...