.htaccess文件常用功能总结
Write By CS逍遥剑仙
我的主页: csxiaoyao.com
GitHub: github.com/csxiaoyaojianxian
Email: sunjianfeng@csxiaoyao.com
QQ: 1724338257
1. apache中启用.htaccess
修改 /private/etc/apache2/httpd.conf
Options FollowSymLinks # AllowOverride None AllowOverride All # 去掉注释 LoadModule rewrite_module libexec/apache2/mod_rewrite.so # 可以选择修改使用.htaccess以外的文件名,如.config AccessFileName .config
2. 时区设置
SetEnv TZ Asia/Shanghai
3. 显示/隐藏目录列表
# 允许显示,两种方式 Options Indexes FollowSymLinks Options All +Indexes # 隐藏目录,三种方式 Options FollowSymLinks Options All -Indexes Options -Indexes
4. 访问控制
使用Order命令限制用户访问一些关键目录
# 保护 htaccess 文件 <Files .htaccess> order allow,deny deny from all </Files> # 阻止查看所有文件 <Files *> order allow,deny deny from all </Files> # 阻止查看指定的文件 <Files logo.png> order allow,deny deny from all </Files> # 多种文件类型 <FilesMatch ".(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$"> order allow,deny deny from all </FilesMatch>
5. 重定向
Redirect permanent / http://www.csxiaoyao.com Redirect temp /old.html http://www.csxiaoyao.com/index.html order deny,allow
6. URL重写
# 开启URL重写 RewriteEngine On # 重写规则 RewriteRule ^demo/getnew/([0-9]+)$ index.php/demo/getnew?id=$1 RewriteRule ^demo/(\S+)$ index.php/demo/$1
7. 阻止/允许特定IP
Order allow,deny Deny from 123.123.123.123 Deny from 123.123.1 Allow from all
8. 自定义错误页
# 基于网站根目录 ErrorDocument 404 /pages/404.html ErrorDocument 500 /pages/500.html
9. 缺省页
DirectoryIndex index.html index.htm index.php
10. 使用/禁用缓存文件
<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$"> Header set Cache-Control "max-age=2592000" </FilesMatch> <FilesMatch ".(pl|php|cgi|spl|scgi|fcgi)$"> Header unset Cache-Control </FilesMatch>
11. 压缩文件
压缩 text, html, javascript, css, xml
AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript
12. 防盗链
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http://(www\.)?csxiaoyao.com(/)?.*$ [NC] RewriteRule .*\.(gif|jpg|jpeg|bmp|png)$ http://www.csxiaoyao.cn/src/logo.png [R,NC,L]
13. 安全相关
RewriteEngine On # 阻止脚本企图通过URL修改mosConfig值 RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [OR] # 阻止脚本通过URL传递的base64_encode垃圾信息 RewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR] # 阻止在URL含有<script>标记的脚本 RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR] # 阻止企图通过URL设置PHP的GLOBALS变量的脚本 RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR] # 阻止企图通过URL设置PHP的_REQUEST变量的脚本 RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2}) # 把所有被阻止的请求转向到403禁止提示页面 RewriteRule ^(.*)$ index.php [F,L] # 禁止某些目录里的脚本执行权限 AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi Options -ExecCGI