.htaccess文件使用教程总结

2019-10-15 22:33:31王冬梅

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 / //www.jb51.net
Redirect temp /old.html //www.jb51.net/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