apache下使用.htaccess文件重写url、伪静态,常用的一些方法


今天研究了下apache的重写问题,伪静态等,之前只做过少许的iis+.net的重写和伪静态。


方法:

1.使apache支持url重写。打开apache的配置文件httpd.conf,记得先备份一下,找到#LoadModule rewrite_module modules/mod_rewrite.so,将前面的#去掉;搜索AllowOverride None,把None改成All,可能有多个,都改吧。


2.改完配置要重启下apache,启动不了的话说明配置被改错了。


3.在网站根目录下建立一test文件夹作为测试。文件夹中包括用于测试的index.php,new.php,h.html文件。


4.建一个.htaccess文件,放到test中。修改.htaccess中的规则会即时生效,不需要重启apache。


“#”为注释



 
#打开重写
RewriteEngine on
          
#1."http://localhost/test/index.php?id=数字" 
#重写为"http://localhost/test/index-数字.html"
 
#注:采用了正则([0-9]*),所以id只能为数字,否则会出错
RewriteRule ^index-([0-9]*).html$ index.php?id=$1
          
           
#2.http://localhost/test/index.php?id=1&name=nic 
重写为 http://localhost/test/domain
        
RewriteRule ^domain$ index.php?id=$1&name=$2
          
          
#3.http://localhost/test/index.php?id=$1&name=nic 
#重写为 http://localhost/test/domain/x/y
#正则([0-9|a-z]*)说明id和nmae支持数字0~9和英文字母a~z
RewriteRule ^domain/([0-9|a-z]*)/([0-9|a-z]*)$ index.php?id=$1&name=$2
           
          
#4.http://localhost/test/index.php?id=110 直接重写为 http://localhost/test/domainq
RewriteRule ^domainq$ index.php?id=110
           
          
#5.http://localhost/test/index.php?id=110 
#重写为 http://localhost/domainx
#这里把test给目录重写掉了(少了一层目录注意到没),此时要在上级目录放一个.htaccess使用下面规则
          
RewriteRule ^domainx$ test/index.php?id=110
           
          
#6.把扩展名重写掉
#http://localhost/test/index.php 
#重写为 http://localhost/test/index
RewriteRule ^([0-9|a-z]*)$ $1.php
           
          
           
#7.把*.html
#重写为*/
#http://localhost/test/h/
#与下一条规则顺序不能变
RewriteRule ^([0-9|a-z]*)/$ $1.html
           
          
#8.把*.html重写为*.a,*.b,*.c ...
#http://localhost/test/h.a
#http://localhost/test/h.b
RewriteRule ^([0-9|a-z]*)..$ $1.html
           
          
#9.把*.html重写为*.apple
#http://localhost/test/h.apple
RewriteRule ^([0-9|a-z]*).apple$ $1.html
          
           
#10.把*.html重写为*.任意类型,其它文件也可以重写不局限于html。
#这个厉害了,可以随意在浏览器中填写扩展名皆可访问,so easy,妈妈再也不用担心我的扩展名了。
#http://localhost/test/h.asp
#http://localhost/test/h.aspx
#http://localhost/test/h.jsp
#http://localhost/test/h.mmzybydxwdkzml
#http://localhost/test/h.gddcsdcddshynh 随意扩展名
     
RewriteRule ^([0-9|a-z]*).*$ $1.html



本文的示例在windows+apache中测试通过,还未测试linux+apache及linux+nginx。我原以为.htaccess是apache专用的,但有人说在nginx下include .htaccess也可以,有空的时候会测下linux+nginx。


记录用于备忘,顺便分享,大家应该可以举多反多。

百度编辑器真不好用啊,还是我用的版本太低了?

类别:OperationMaintenance   阅读(0)   评论(0)    发表时间:2014-10-10 21:42  星期五

评论区

发表评论

        姓名:
邮箱|网站:
        内容:

  (可按Ctrl+Enter提交)