关于.htaccess文件的几个常用技巧
by 冬瓜 on Apr 17 , 2010 , under 学术, 知识管理 , 620 views , 5 Comments
说起.htaccess规则文件,很多朋友都不会陌生,特别是使用wordpress、discuz等php类开源产品的朋友,该文件的作用与windows主机下的httpd.ini文件稍有雷同之处,但.htaccess的作用要大得多,我的几个站点也都使用了.htaccess文件,今天就分享几个常用的技巧。
可别小看.htaccess规则文件,短短的几行规则代码可以做很多事情呢:(本站的http://wjd.name/xxx 的URL格式就是用.htaccess实现的)
防止图片、文件盗链
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$ [NC]
RewriteCond %{HTTP_REFERER} !cn.wjd.im [NC] //允许本站访问
RewriteRule .*\.(gif|jpg|png)$ http://wjd.name/logo.jpg [R,NC,L] //让所有盗链的gif|jpg|png文件显示为http://wjd.name/logo.jpg
自定义的出错页面
ErrorDocument 401 /error/401.html //401错误转向到error/401.html 页面
ErrorDocument 403 /error/403.html
ErrorDocument 404 /error/404.html
ErrorDocument 500 /error/500.html
屏蔽搜索引擎
SetEnvIfNoCase User-Agent “^Baidu” bad_bot //屏蔽百度
Deny from env=bad_botSetEnvIf User-Agent “^Googlebot” google //屏蔽google
Deny from env=google
屏蔽IP段
order allow,deny
deny from 58.135.0.0/15
allow from all
根据IP重定向
ErrorDocument 403 http://l.wjd.name //以下ip访问时重定向到http://l.wjd.name
Order deny,allow
Deny from all
Allow from 218.193.144.141
Allow from 218.193.144.159
帮助用户直接打开文件而不是下载
AddType application/octet-stream .pdf //直接打开pdf文件
AddType application/octet-stream .zip
AddType application/octet-stream .mov
修改默认主页
# serve alternate default index page
DirectoryIndex index111.html //设置index111.html为默认主页
隐藏目录列表
Options -Indexes
.htaccess的规则实在是太多了,今个儿就列出了几个来,其实现在使用.htaccess最多的还是URL伪静态化,也就是rewrite,但是针对每个产品的rewrite规则都不一样,所以今天就不一一展示了,未来有时间的话把我正在使用的几款产品的.htaccess文件贴出来。
扫盲:.htaccess是什么
子目录中的指令会覆盖更高级目录或者主服务器配置文件中的指令。Unix、Linux系统或者是任何版本的Apache Web服务器都是支持.htaccess的。笼统地说,.htaccess可以帮我们实现包括:文件夹密码保护、用户自动重定向、自定义错误页面、改变你的文件扩展名、封禁特定IP地址的用户、只允许特定IP地址的用户、禁止目录列表,以及使用其他文件作为index文件等一些功能。
April 17th, 2010 on 13:51
[…] This post was mentioned on Twitter by 王佳冬. 王佳冬 said: 关于.htaccess文件的几个常用技巧 http://wjd.name/htaccess/ […]
April 17th, 2010 on 14:54
您自己发明的?
April 17th, 2010 on 15:59
怎么可能
May 18th, 2010 on 10:24
您自己发明的?
October 24th, 2011 on 19:40
[…] 例如,重定向wjd.name到cn.wjd.im,打开wjd.name的网站文件夹根目录,找到或者新建.htaccess,文件内容: RewriteEngine on RewriteCond %{HTTP_HOST} cn.wjd.im RewriteRule ^(.*) http://cn.wjd.im/$1 [R] […]