常青树 发表于 2018-12-20 07:02:44

PHP实现url重写和.htaccess

  .htaccess是一个完整的文件名(只有后缀),它是用于Apache服务器下的配置文件,当.htaccess文件放在某一文件夹下,它仅对该文件夹下的文件和文件夹有效。通过.htaccess文件,可以配置服务器实现很多功能,比如错误定位,密码保护,IP拒绝,URL重写等等。
  默认的Apache不支持.htaccess,需要修改Apache的配置文件httpd.conf,才能使得.htaccess有效。
  配置方法:
  配置方面:
  1. 找到apache的安装目录下的conf下的httpd.conf文件,打开文件修改
  LoadModule rewrite_module modules/mod_rewrite.so这行代码,他前面有个#号,把#号删掉
  2.找到
  
      Options FollowSymLinks ExecCGI Indexes
      AllowOverride None
      Order deny,allow
      Deny from all
      Satisfy all
  
  这个节点,把None改为All.节点可能有多个,修改和PHP路径相关的那个。
  3. 重启apache服务
  接下来是创建.htaccess文件,并在里面写配置。Windows中新建文件的时候,不允许文件只有后缀,可以采用notepad等工具新建另存为该文件名。
  如果要实现URL重写,配置文件中采用正则表达式是编写URL,并使之和常规的php文件映射。常用的写法如下:
  RewriteEngine on                     //on为打开,off为关闭
  RewriteRule ({1,})-({1,}).html$ b.php?action=$1&id=$2
  RewriteRule ({1,})/({1,})$ a.php?controller=$1&action=$2
  RewriteRule MyController/$ MyController.php?action=$1
  ErrorDocument 404 /404.txt
  网上找了一篇文件http://roshanbh.com.np/2008/03/url-rewriting-examples-htaccess.html例举了常用的5种映射,也可以参考。
  product.php?id=12 to product-12.html
  RewriteEngine on   
RewriteRule ^product-(+)\.html$ product.php?id=$1
  Rewriting product.php?id=12 to product/ipod-nano/12.html
  RewriteEngine on   
RewriteRule ^product/(+)/(+)\.html$ product.php?id=$2
  Redirecting non www URL to www URL
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^optimaxwebsolutions\.com$   
RewriteRule (.*) http://www.optimaxwebsolutions.com/$1
  Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz
  RewriteEngineOn   
RewriteRule ^(+)$ user.php?username=$1   
RewriteRule ^(+)/$ user.php?username=$1
  Redirecting the domain to a new subfolder of inside public_html.
  RewriteEngineOn   
RewriteCond %{HTTP_HOST} ^test\.com$    
RewriteCond %{HTTP_HOST} ^www\.test\.com$   
RewriteCond %{REQUEST_URI} !^/new/   
RewriteRule (.*) /new/$1
  示例:
  .htaccess文件内容如下
  RewriteEngine on                     //on为打开,off为关闭
  RewriteRule ^({1,})/({1,})$ a.php?controller=$1&action=$2
  RewriteRule ^({1,})/({1,})/$ a.php?controller=$1&action=$2
  说明:
  正则表达式,严格匹配类似Controller/Action或者Controller/Action/,映射到a.php
  a.php内容
  
  输入http://localhost:8080/Controller/Action/
  则被解析到http://localhost:8080/a.php?controller=Controller&action=Action
  这2个url是等价的。
  注意,在映射url后加上查询字符串不影响正常的映射,比如输入http://localhost:8080/Controller/Action/?value=100,也是可以的。
  参考文档:
  http://www.htaccess-guide.com/
  http://corz.org/serv/tricks/htaccess.php
  http://roshanbh.com.np/2008/03/url-rewriting-examples-htaccess.html



页: [1]
查看完整版本: PHP实现url重写和.htaccess