认识.htaccess文件
.htaccess文件(或者"分布式配置文件")提供了针对目录改变配置的方法, 即,在一个特定的文档目录中放置一个包含一个或多个指令的文件, 以作用于此目录及其所有子目录.作为用户,所能使用的命令受到限制.管理员可以通过Apache的AllowOverride指令来设置.
如何启用.htaccess文件
打开apache配置文件httpd.conf,然后查找AllowOverride属性,并设置为AllowOverride All,即可启用htaccess
htaccess 301跳转
301的跳转我在详解301永久重定向代码和永久链接优化中详细的提到过,大家可以看看。
案例1 从一个页面跳转到另一个页面(简单写法)
Redirect 301 ^old.html$ http://www.xiezewen.com/new.html
实现old.html向new.html的永久跳转,但是后面的路径必须是完整的路径
案例2 URL重写
RewriteEngine on RewriteRule ^old.html$ http://www.xiezewen.com/new.html [r=301] RewriteRule ^products/([^/]+)/([^/]+)/([^/]+) product.php?cat=$1&brand=$2&prod=$3
第一行 打开URL重写的引擎,必须有;
第二行 一个案例,实现old.html向new.html的永久跳转,并且在浏览器中直接显示新地址
第三方 一个案例,匹配表达式,能够将product.php?cat=turntables&brand=technics&prod=a2251的链接伪静态成url products/turntables/technics/a2251
htaccess 404设置
<Files ~ "^.(htaccess|htpasswd)$"> deny from all </Files> ErrorDocument 404 /404.html order deny,allow
htaccess 503设置
<Files ~ "^.(htaccess|htpasswd)$"> deny from all </Files> ErrorDocument 503 /503.html order deny,allow
注:上述错误友好页面,需要在网站根目录建立404.html等静态文件。
htaccess 阻止部分ip访问
order allow,deny deny from 202.114.44.1 allow from allOrde
htaccess apache服务器缓存(可节约服务器资源)
ExpiresActive on ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month"
htaccess 开启服务器Gzip压缩
<ifmodule mod_deflate.c> AddOutputFilter DEFLATE html xml php js css </ifmodule>
htaccess 在html页面运行php程序
AddHandler x-mapp-php6 .html .htm
htaccess 设置php脚本执行时间
php_value max_execution_time 500