Nginx 下为网站添加 auth_basic 认证

作者:admin | 时间:January 14, 2015 | 分类:host,web | 评论:0 ℃

Nginx 下 auth_basic 认证至少可以分两种,目录认证和整站认证。实现代码分别为:

1、整站认证,在 Server 段添加以下代码:

auth_basic “input you user name and  password”;
auth_basic_user_file /usr/local/nginx/conf/vhost/nginx_passwd;

完成之后就是这个样子:

server {
        listen 80;
        root /home/www/;
        index index.php;
        server_name domain.com;
         #密码认证
        auth_basic “input you user name and  password”;
        auth_basic_user_file /usr/local/nginx/conf/vhost/nginx_passwd;
        location / {
        }
}

2、目录认证,在 location 段添加以下代码:

auth_basic “input you user name and  password”;
auth_basic_user_file /usr/local/nginx/conf/vhost/nginx_passwd;

完成之后就是这个样子:

location ^~ /目录/.* {
location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
}
auth_basic “input you user name and  password”;
auth_basic_user_file /usr/local/nginx/conf/vhost/nginx_passwd;
}

目录认证后就丧失了继承的 PHP 解析能力,所以要重新添加 PHP 解析语法:

location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
}

密码认证文件可以通过 http://tool.oschina.net/htpasswd 在线生成!

参考:http://blog.rekfan.com/articles/288.html