21个常用的apache .htaccess文件配置技巧分享
ApacheWeb服务器可以通过.htaccess文件来操作各种信息,这是一个目录级配置文件的默认名称,允许去中央化的Web服务器配置管理。可用来重写服务器的全局配置。该文件的目的就是为了允许单独目录的访问控制配置,例如密码和内容访问。
1.定制目录的Index文件
DirectoryIndexindex.htmlindex.phpindex.htm
你可以使用上面的配置来更改目录的默认页面,例如你将这个脚本放在foo目录,则用户请求/foo/时候就会访问/foo/index.html。
2.自定义错误页
ErrorDocument404errors/404.html
当用户访问页面报错时,例如页面找不到你希望显示自定义的错误页面,你可以通过这种方法来实现。或者是动态的页面:
ErrorDocument404/psych/cgi-bin/error/error?404
3.控制访问文件和目录的级别
.htaccess经常用来限制和拒绝访问某个文件和目录,例如我们有一个includes文件夹,这里存放一些脚本,我们不希望用户直接访问这个文件夹,那么通过下面的脚本可以实现:
#noonegetsinhere! denyfromall 上述脚本是拒绝所有的访问,你也可以根据IP段来拒绝: #nonastycrackersinhere! orderdeny,allow denyfromall allowfrom192.168.0.0/24 #thiswoulddothesamething.. #allowfrom192.168.0
一般这些方法是通过防火墙来处理,但在一个生产环境中的服务器来说,这样的调整非常方便。
有时候你只是想禁止某个ip访问:
#someoneelsegivingtheruskiesabadname.. orderallow,deny denyfrom83.222.23.219 allowfromall
4.修改环境变量
环境变量包含了服务器端CGI的一些扩展信息,可使用SetEnv和UnSetEnv进行设置以及取消设置.
SetEnvSITE_WEBMASTER"JackSprat" SetEnvSITE_WEBMASTER_URImailto:Jack.Sprat@characterology.com UnSetEnvREMOTE_ADDR
5.301重定向
如果你希望某个页面跳转到新的页面:
Redirect301/old/file.htmlhttp://yourdomain.com/new/file.html
下面可以实现对整个路径的重定向:
RedirectMatch301/blog(.*)http://yourdomain.com/$1
6.通过.htaccess实现缓存策略
通过设置在浏览器上缓存静态文件可以提升网站的性能:
#year <FilesMatch"\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4)$"> HeadersetCache-Control"public" HeadersetExpires"Thu,15Apr201020:00:00GMT" HeaderunsetLast-Modified </FilesMatch> #2hours <FilesMatch"\.(html|htm|xml|txt|xsl)$"> HeadersetCache-Control"max-age=7200,must-revalidate" </FilesMatch> <FilesMatch"\.(js|css)$"> SetOutputFilterDEFLATE HeadersetExpires"Thu,15Apr201020:00:00GMT" </FilesMatch>
7.使用GZIP对输出进行压缩
在.htaccess中添加下面的代码可以将所有的css、js和html使用GZIP算法压缩:
<IfModulemod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_includefile \.(html?|txt|css|js|php|pl)$ mod_gzip_item_includehandler ^cgi-script$ mod_gzip_item_includemime ^text/.* mod_gzip_item_includemime ^application/x-javascript.* mod_gzip_item_excludemime ^image/.* mod_gzip_item_excluderspheader^Content-Encoding:.*gzip.* </IfModule>
使用上面代码的前提是启用mod_gzip模块,你可以使用下面脚本来判断Web服务器是否提供mod_deflate支持:
<Location> SetOutputFilterDEFLATE SetEnvIfNoCaseRequest_URI \ \.(?:gif|jpe?g|png)$no-gzipdont-vary SetEnvIfNoCaseRequest_URI \ \.(?:exe|t?gz|zip|gz2|sit|rar)$no-gzipdont-vary </Location>
如果Web服务器不支持mod_deflate,那么可使用下面方法:
<FilesMatch"\.(txt|html|htm|php)"> php_valueoutput_handlerob_gzhandler </FilesMatch>
8.强制要求使用HTTPS访问
通过以下脚本可以强制整个网站必须使用https方式访问:
RewriteEngineOn RewriteCond%{HTTPS}!on RewriteRule(.*)https://%{HTTP_HOST}%{REQUEST_URI}
9.URL重写
例如要将product.php?id=12重写为product-12.html
RewriteEngineon RewriteRule^product-([0-9]+)\.html$product.php?id=$1
将product.php?id=12重写为product/ipod-nano/12.html
RewriteEngineon RewriteRule^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$product.php?id=$2
重定向没有www到有www的URL地址:
RewriteEngineOn RewriteCond%{HTTP_HOST}^viralpatel\.net$ RewriteRule(.*)http://www.viralpatel.net/$1[R=301,L]
重写yoursite.com/user.php?username=xyz到yoursite.com/xyz
RewriteEngineOn RewriteRule^([a-zA-Z0-9_-]+)$user.php?username=$1 RewriteRule^([a-zA-Z0-9_-]+)/$user.php?username=$1
重定向某个域名到一个public_html里新的子文件夹:
RewriteEngineOn RewriteCond%{HTTP_HOST}^test\.com$[OR] RewriteCond%{HTTP_HOST}^www\.test\.com$ RewriteCond%{REQUEST_URI}!^/new/ RewriteRule(.*)/new/$1
10.阻止列出目录文件
使用下面代码可以防止列表目录里的所有文件:
Options-Indexes
或者
IndexIgnore*
11.添加新的MIME-Types
MIME-types依赖于文件的扩展名,未能被识别的文件扩展名会当成文本数据传输
AddTypeapplication/x-endnote-connectionenz AddTypeapplication/x-endnote-filterenf AddTypeapplication/x-spss-savefilesav
12.防盗链
你不希望别人网站引用你站内的图片、css等静态文件,也就是传说中的防盗链,可以使用如下脚本:
RewriteCond%{HTTP_REFERER}!^$ RewriteCond%{REQUEST_URI}!^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).*[NC] RewriteCond%{HTTP_REFERER}!^http://www.askapache.com.*$[NC] RewriteRule\.(ico|pdf|flv|jpg|jpeg|mp3|mpg|mp4|mov|wav|wmv|png|gif|swf|css|js)$-[F,NS,L]
13.指定上传文件的大小限制,适用于PHP
php_valueupload_max_filesize20M php_valuepost_max_size20M php_valuemax_execution_time200 php_valuemax_input_time200
上述脚本中,通过四个参数来设置上传文件的限制,第一个参数是文件的大小,第二个是POST数据的大小,第三个是传输的时间(单位秒),最后一个是解析上传数据最多花费的时间(单位秒)
14.禁止脚本执行
Options-ExecCGI AddHandlercgi-script.php.pl.py.jsp.asp.htm.shtml.sh.cgi
15.修改字符集和语言头
AddDefaultCharsetUTF-8 DefaultLanguageen-US
16.设置服务器时区(GMT)
SetEnvTZAmerica/Indianapolis
17.强制“FileSaveAs”提示
AddTypeapplication/octet-stream.avi.mpg.mov.pdf.xls.mp4
18.保护单个文件
正常情况下.htaccess可用于限制整个目录的访问,但也可以只限制某个文件:
<Filesquiz.html> orderdeny,allow denyfromall AuthTypeBasic AuthName"CharacterologyStudentAuthcate" AuthLDAPon AuthLDAPServerldap://directory.characterology.com/ AuthLDAPBase"ou=Student,o=CharacterologyUniversity,c=au" requirevalid-user satisfyany </Files>
19.设置Cookie
通过环境变量来设置Cookie
HeadersetSet-Cookie"language=%{lang}e;path=/;"env=lang
基于请求设置Cookie,该代码发送Set-Cookie头用于设置Cookie值为第二个括号里的匹配项
RewriteEngineOn RewriteBase/ RewriteRule^(.*)(de|es|fr|it|ja|ru|en)/$-[co=lang:$2:.yourserver.com:7200:/]
20.设置自定义的响应Headers
HeadersetP3P"policyref=\"http://www.askapache.com/w3c/p3p.xml\"" HeadersetX-Pingback"http://www.askapache.com/xmlrpc.php" HeadersetContent-Language"en-US" HeadersetVary"Accept-Encoding"
21.根据User-Agent来阻止请求
SetEnvIfNoCase^User-Agent$.*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures)HTTP_SAFE_BADBOT SetEnvIfNoCase^User-Agent$.*(libwww-perl|aesop_com_spiderman)HTTP_SAFE_BADBOT Denyfromenv=HTTP_SAFE_BADBOT