使用.htaccess重写平面URL

时间:2015-01-29 08:23:25

标签: php regex .htaccess mod-rewrite url-rewriting

我正在尝试缩短以下网址

 www.domain.com/index_1.php?var=value
 www.domain.com/index_2.php?name=value

 www.domain.com/value
 www.domain.com/name/value

我到底是什么,

 www.domian.com                    // This should reach index_1.php
 www.domain.com/value              // This should reach index_1.php
 www.domain.com/name               // This should reach index_2.php
 www.domain.com/name/value         // This should reach index_2.php
 www.domain.com/name/              // The last slash should be omitted and redirect to "www.domain.com/name"

“值”范围可能包含[0-9] [A-Z] [a-z] [ - ] [_]

我尝试过以下.htaccess代码,

 Options +FollowSymlinks
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule (^name?$)|(^name/([^/]+)/?$) /index_2.php?name=$1 [L]
 RewriteRule ^([^/][^(name)]+)/?$ /index_1.php?var=$1 [L]

当我输入

 www.domian.com                    // It Works.
 www.domain.com/value              // It shows "404 Page Not Found".
 www.domain.com/name               // It works.
 www.domain.com/name/value         // It works.
 www.domain.com/name/              // It shows "404 Page Not Found".

如果可以使用PHP完成,请回答。

2 个答案:

答案 0 :(得分:1)

您必须区分 www.domain.com/name www.domain.com/value

否则,您可以使用PHP完成此操作。

Options +FollowSymlinks
RewriteEngine On
RewriteBase /

# For www.domain.com/value
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ index.php?var=$1 [L,QSA]

# For www.domain.com/name/value
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^([\w-]+)/([\w-]+)/?$ index_2.php?$1=$2 [L,QSA]

在index.php中:

if(isset($_GET["var"])) {
  $value = $_GET["var"];
  if($value == "name"){
    include"index_2.php";  
  }else{
    include"index_1.php";
  }
}else{
  include"index_1.php";
}

答案 1 :(得分:0)

您可以使用:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /

# For www.domain.com/value
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ index_1.php?var=$1 [L,QSA]

# For www.domain.com/name/value
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/([\w-]+)/?$ index_2.php?$1=$2 [L,QSA]