.htaccess 文件是 Apache 等网页服务器使用的基于目录的配置文件。要使用它,首先需要修改httpd.conf,启用 AllowOverride 选项。设置完成后我们就可以在某个目录里新建一个 .htaccess 文件,利用它设置该目录及其子目录的一些选项。这里列举一些常见的设置方式。
一、设置目录的 index 文件
DirectoryIndex index.php index.html index.htm
这个设置将使得服务器按照上面的顺序查找文件作为 index 文件。
二、设置错误页面
ErrorDocument 404 /error.html
这个设置将使得用户访问不存在的页面是返回 /error.html 文件
三、禁止列出目录内容
Options -Indexes
这个设置使得用户访问没有 index 文件的目录时不再列出该目录的所有文件。
四、禁止列出某些文件
IndexIgnore .htaccess *~ README*
这个设置使得列出该目录的所有文件时忽略 .htacces 文件,以 ~ 结尾的文件以及以 README 开头的文件。
五、禁止某些地址的访问
Order Allow, Deny Deny from 111.22.33.44 Deny from 222.33.44. Allow from all
这个设置将禁止 IP 地址为 111.22.33.44 以及在 222.33.44.0~222.33.44.255 中的用户的访问。
这种设置方式在 Apache 2.4 中已经被废弃,而改为用下面这种方式:
<RequireAll> Require all granted Require not ip 111.22.33.44 Require not ip 222.33.44. </RequireAll>
六、设置目录的访问密码
AuthName "Protected Directory" AuthType Basic AuthUserFile /full/path/to/.htpasswd Require valid-user
此时访问此目录时将需要从 /full/path/to/.htpasswd 文件中验证用户名和密码。
当然也可以设置特定文件的访问密码,例如:
<Files secret.txt> AuthName "Protected File" AuthUserFile /full/path/to/.htpasswd AuthType Basic Require valid-user </Files>
七、设置页面跳转
Redirect page1.html page2.html
这样设置i后,当访问 page1.html 文件时,服务器将发送 HTTP 状态码 302 将浏览器导向 page2.html。
八、设置路径改写
RewriteEngine On RewriteBase / RewriteRule ^forum-([0-9]+)-([0-9]+)\.html$ forum.php?fid=$1&page=$2
这样用户访问 forum-123-45.html 服务器将把它改写为 forum.php?fid=123&page=45。
参考资料:
[1] Apache HTTP Server - .htaccess files
[2] Apache HTTP Server - access Control
[3] Apache HTTP Server - Authentication and Authorization
[4] Apache HTTP Server - Apache Core Features
[5] Apache HTTP Server - Apache mod_rewrite
[6] Apache HTTP Server - mod_access_compat
[7] Apache HTTP Server - mod_autoindex
[8] Apache HTTP Server - mod_auth_basic
[9] .htaccess - 维基百科,自由的百科全书
[A] Comprehensive guide to .htaccess- intro
[B] .htaccess使用指南 - Just 平生一笑