Nginx创建password保护文件夹
Posted jzdwajue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nginx创建password保护文件夹相关的知识,希望对你有一定的参考价值。
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创建password保护文件夹的主要内容,如果未能解决你的问题,请参考以下文章
Nginx——Nginx启动报错Job for nginx.service failed because the control process exited with error code(代码片段
连接MySQL出现错误:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)(代码片段
修改MySQL密码报错“ERROR 1819 (HY000): Your password does not satisfy the current policy requirements“(代码片段