nginx可以为网站或目录甚至特定的文件设置密码认证。

密码必须是crypt加密的。可以用htpasswd来创建密码。

1.安装htpasswd工具

yum -y install httpd

 

2.生成密码文件

$ htpasswd
Usage:
        htpasswd [-cmdpsD] passwordfile username
        htpasswd -b[cmdpsD] passwordfile username password

        htpasswd -n[mdps] username
        htpasswd -nb[mdps] username password
 -c  Create a new file.
 -n  Don’t update file; display results on stdout.
 -m  Force MD5 encryption of the password.
 -d  Force CRYPT encryption of the password (default).
 -p  Do not encrypt the password (plaintext).
 -s  Force SHA encryption of the password.
 -b  Use the password from the command line rather than prompting for it.
 -D  Delete the specified user.
On Windows, NetWare and TPF systems the '-m' flag is used by default.
On all other systems, the '-p' flag will probably not work.

 

htpasswd的说明已经很清楚了,我们使用以下命令生成密码文件:

#生成含用户test密码test1名为passwd的文件
htpasswd -bc passwd test test1

 

3.修改nginx配置文件

如果是为了给网站加上认证,可以直接将认证语句写在nginx的配置server段中。

如果是为了给目录加上认证,就需要写成目录形式了。同时,还要在目录中加上php的执行解释,否则php就会被下载而不执行了。

基于整个网站的认证, auth_basic 在 php 解释之前。

其他帖子是这样的
server  
location ~ ^/wp-login\.php {
	auth_basic "kn007's Auth System";
	auth_basic_user_file /usr/local/nginx/passwd_kn007.db;
	location ~ .*\.php?$ {
		try_files $uri =404;
		fastcgi_pass  unix:/tmp/php-cgi.sock;
		fastcgi_index index.php;
		include fastcgi.conf;
	}
}

 

实际上用lnmp安装的nginx配置是这样的:

server  
{  
  listen 80;  
  server_name ailitonia.com www.ailitonia.com;  
  root /www/ailitonia.com;  
  index index.html index.htm index.php;  
  #新增以下几行
  auth_basic "Server Auth";  
  auth_basic_user_file nginx_passwd;  
}

  #实际上的php解释
  include enable-php.conf;

 

针对目录的认证

在一个单独的location中,并且在该location中嵌套一个解释php的location,否则php文件不会执行并且会被下载。auth_basic在嵌套的location之后。

  location ^~ /admin/ {
    include enable-php.conf;
    auth_basic "Server Auth";
    auth_basic_user_file nginx_passwd;
}

 

location ^~ /admin/ {…} 意为匹配/admin/目录下的所有文件,这条规则应尽量往前面放,匹配目录涉及nginx的匹配规则,详见这篇文章


本文被阅读了:3,980次

作者头像
关于  Ailitonia

正因站在了巨人的肩膀上,才越发觉得自己渺小。不求成为巨人,但求与其同行。 把自己所见所闻,记录下来。

→查看所有由Ailitonia发布的文章