ubuntu server 8 上建立虚拟主机 和 目录文件夹实现用户验证

关于Apache服务器如何实现用户验证
Apache服务器已经内置用户验证机制,大家只要适当的加以设置,便可以控制网站的某些部分要用户验证。
前期准备,必须已经安装apache,如果还没安装,或者对安装很模糊的话,请查询相应的资料。
设置虚拟主机
我们在/var/www(apache的主页根目录)下建立一个yourdomain.com目录
mkdir /var/www/yourdomain.com
打开 /etc/apache2/sites-available/default 文件
修改这个文件
NameVirtualHost *
<VirtualHost your server IP address>
ServerAdmin webmaster@localhost
ServerName    yourdomain.com
DocumentRoot /var/www/yourdomain.com
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/yourdomain.com>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory “/usr/lib/cgi-bin”>
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>

ErrorLog /var/log/apache2/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog /var/log/apache2/access.log combined
ServerSignature On

#Alias /doc/ “/usr/share/doc/”
Alias /lists/ “/var/www/yourdomain.com/lists”

<Directory “/var/www/yourdomain.com/lists”>
#Options Indexes MultiViews FollowSymLinks
Options Indexes MultiViews
AllowOverride AuthConfig
Order deny,allow
#Deny from all
#Allow from 127.0.0.0/255.0.0.0 ::1/128
Allow from all
</Directory>

</VirtualHost>
这样我就设置好了虚拟主机,同时可以看到上面红字部分,这儿就是需要用户验证的文件夹的设置
AllowOverride AuthConfig #表示进行身份验证
Order allow,deny
Allow from all    #允许所有人访问
#AllowOverride AuthConfig 表示进行身份验证 这是关键的设置

在/var/www/yourdomain.com/lists 下创建.htaccess文件
vi /var/www/yourdomain.com/lists/.htaccess
AuthName “EnterPassword”
AuthType Basic
AuthUserFile /var/www/yourdomain.com/lists/.htpasswd
require valid-user
#AuthName 描述,随便写
#AuthUserFile 用户口令和密码, #require valid-user 或者 require user yourusername 限制是所有合法用户还是指定用户
#密码文件推荐使用.htpasswd,因为apache默认系统对“.ht”开头的文件默认不允许外部读取,安全系数会高一点哦。如果你觉得这儿不安全 的化,可以把他设置到 /ETC/APACHE2 下面 AuthUserFile /etc/apache2/.htpasswd

就是创建apache的验证用户
htpasswd -c /var/www/yourdomain.com/lists/.htpasswd yourusername第一次创建用户要用到-c 参数 第2次添加用户,就不用-c参数
如果想修改密码,可以如下
htpasswd -m .htpasswd yourusername

ok,重启apache服务,
/etc/init.d/apache2 restart
然后访问 http://yourdomain.com/lists
如果顺利的话,应该能看到一个用户验证的弹出窗口,只要填入上面创建的用户名和密码就行
后话,为了服务器的性能,一般不推荐使用AllowOverride AuthConfig或者AllowOverride ALL,因为这会使服务器会不断的去寻找.htaccess,从而影响服务器的效能,一般我们把一些后台管理界面或者其他特殊目录可能需要加验证这个需 求。