环境:
系统 Windows8.1
Apache 2.2
加载Rewrite模块:
在conf目录下httpd.conf中找到
LoadModule rewrite_module modules/mod_rewrite.so
这句,去掉前边的注释符号“#”,或添加这句。
允许在任何目录中使用“.htaccess”文件,将“AllowOverride”改成“All”(默认为“None”):
1 | # AllowOverride controls what directives may be placed in .htaccess files. |
2 | # It can be “All”, “None”, or any combination of the keywords: |
3 | # Options FileInfo AuthConfig Limit |
在Windows系统下不能直接建立“.htaccess”文件,可以在命令行下使用“echo a> .htaccess”建立,然后使用记事本编辑。
Apache Rewrite模块的简单应用:
Rewrite的所有判断规则均基于Perl风格的正则表达式,通过以下基础示例能写出符合自己跳转需求的代码。
1、请求跳转
目的是如果请求为.jsp文件,则跳转至其它域名访问。
例如:访问www.clin003.com/a.php跳转至b.clin003.com/b.php网页,访问www.clin003.com/news/index.php跳转至b.clin003.com/news/index.php网页
注意:不是使用HTML技术中的meta或者javascript方式,因为www.clin003.com/a.php这个文件并不存在,用的是Apache2.2服务器中的Rewrite模块。
修改 .htaccess或apche的配置文件httpd.conf文件,添加以下内容
3 | RewriteRule (.*)\.php$ http: |
2、域名跳转
如果请求为old.clin003.com下的所有URL,跳转至b.clin003.com
3 | RewriteCond %{REMOTE_HOST} ^old.studenthome.cn$ [NC] |
4 | #针对host为old.clin003.com的主机做处理,^为开始字符,$为结尾字符 |
3、防盗链
如果本网站的图片不想让其它网站调用,可以在 .htaccess或者apche的配置文件httpd.conf文件中添加以下内容
03 | RewriteCond %{HTTP_REFERER} !^$ |
05 | RewriteCond %{HTTP_REFERER} !img.clin003.com$ [NC] |
06 | #且如果不是img.clin003.com所有子域名调用的 |
07 | RewriteCond %{HTTP_REFERER} !img.clin003.com/(.*)$ [NC] |
08 | RewriteCond %{HTTP_REFERER} !zhuaxia.com [NC] |
09 | RewriteCond %{HTTP_REFERER} !google.com [NC] |
10 | RewriteCond %{HTTP_REFERER} !google.cn [NC] |
11 | RewriteCond %{HTTP_REFERER} !baidu.com [NC] |
12 | RewriteCond %{HTTP_REFERER} !feedsky.com [NC] |
13 | RewriteRule (.*)\.(jpg|jpeg|jpe|gif|bmp|png|wma|mp3|wav|avi|mp4|flv|swf)$ http: |
14 | #截获所有.jpg或.jpeg……请求,跳转到http: |
4、不需要定义.htaccess文件
在Apache2\conf\httpd.conf 最后一行添加
RewriteEngine On
RewriteRule ^(.*)-htm-(.*)$ $1.php?$2
5.重启Apache即可