Apache服务器中.htaccess文件的实用配置示例集锦

2019-10-13 22:54:03王旭

2. 防盗链
节省你宝贵的带宽吧!

RewriteEngine On 
#Replace ?mysite.com/ with your blog url 
RewriteCond %{HTTP_REFERER} !^http://(.+.)?mysite.com/ [NC] 
RewriteCond %{HTTP_REFERER} !^$ 
#Replace /images/nohotlink.jpg with your "don't hotlink" image url 
RewriteRule .*.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L] 

3. 重定向移动设备
加入你的网站支持移动设备访问的话,最好还是重定向移动设备的访问到专门定制的页面

RewriteEngine On 
RewriteCond %{REQUEST_URI} !^/m/.*$ 
RewriteCond %{HTTP_ACCEPT} "text/vnd.wap.wml|application/vnd.wap.xhtml+xml" [NC,OR] 
RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR] 
RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR] 
RewriteCond %{HTTP_USER_AGENT} "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR] 
RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR] 
RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR] 
RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR] 
RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR] 
RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR] 
RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC] 
#------------- The line below excludes the iPad 
RewriteCond %{HTTP_USER_AGENT} !^.*iPad.*$ 
#------------- 
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC] #*SEE NOTE BELOW 
RewriteRule ^(.*)$ /m/ [L,R=302] 

4. 强制浏览器下载指定的文件类型
你可以强制浏览器下载某些类型的文件,而不是读取并打开这些文件,例如MP3、XLS。

<Files *.xls> 
 ForceType application/octet-stream 
 Header set Content-Disposition attachment 
</Files> 
<Files *.eps> 
 ForceType application/octet-stream 
 Header set Content-Disposition attachment 
</Files> 

5. 火狐的跨域名字体嵌入
火狐不允许嵌入一个外站的字体,下面的.htaccess片段可以绕过这个限制

<FilesMatch ".(ttf|otf|eot|woff)$"> 
<IfModule mod_headers.c> 
  Header set Access-Control-Allow-Origin "http://yourdomain.com" 
</IfModule> 
</FilesMatch> 

6. 使用.htaccess缓存 给网站提速
恐怕这个是最有用的代码片段了。这段代码能帮你极大的提高网站的速度!

# 1 YEAR 
<FilesMatch ".(ico|pdf|flv)$"> 
Header set Cache-Control "max-age=29030400, public" 
</FilesMatch> 
# 1 WEEK 
<FilesMatch ".(jpg|jpeg|png|gif|swf)$"> 
Header set Cache-Control "max-age=604800, public" 
</FilesMatch> 
# 2 DAYS 
<FilesMatch ".(xml|txt|css|js)$"> 
Header set Cache-Control "max-age=172800, proxy-revalidate" 
</FilesMatch> 
# 1 MIN 
<FilesMatch ".(html|htm|php)$"> 
Header set Cache-Control "max-age=60, private, proxy-revalidate" 
</FilesMatch>