.htaccess重定向exression以匹配usename添加密码

时间:2018-01-27 17:33:26

标签: php apache .htaccess redirect mod-rewrite

我正在写.htaccess文件来重定向我的网址,如

 "localhost/authenticate/username/password" to
 "localhost/myfile.php?fn=authenticate&uname=username&passwd=password"

我的.htaccess文件包含

RewriteRule ^authenticate/*/*/ myfile.php?fn=authenticate&uname=$1&passwd=$2

有人可以告诉我正确的表达方式。 我也试过跟随,但没有任何作用。 RewriteRule ^authenticate/.*/.*/ myfile.php?fn=authenticate&uname=$1&passwd=$2

myfile.php:
<?php
    if (isset($_REQUEST['fn']) && "authenticate"==$_REQUEST['fn']) {
      $user = isset($_REQUEST['uname']) ? $_REQUEST['uname'] : "";
      $pass = isset($_REQUEST['passwd']) ? $_REQUEST['passwd'] : "";

      if ($user != "" && $pass != ""){
        #validate here
        echo "user = ".$user."  passwd = ".$pass;
      }
      else{
        echo "user/pass empty";
      }
    }else {
      echo "Ivalid url";
    }
 ?>

.htaccess:

# Turn rewrite engine on
Options +FollowSymlinks
RewriteEngine on
RewriteBase /

#RewriteRule ^authenticate/([^/]+)/([^/]+)/? /myfile.php?fn=authenticate&uname=$1&passwd=$2 [QSA,L]
#RewriteRule ^authenticate/(.*)/(.*)/? /myfile.php?fn=authenticate&uname=$1&passwd=$2 [QSA,L]

RewriteRule ^/?authenticate/([^/]+)/([^/]+)/? /myfile.php?fn=authenticate&uname=$1&passwd=$2


#url: http://localhost/test/authenticate/john/1234

1 个答案:

答案 0 :(得分:0)

您需要使用括号来启用正则表达式反向引用。

RewriteRule ^/?authenticate/([^/]+)/([^/]+)/? /myfile.php?fn=authenticate&uname=$1&passwd=$2

$1是对第一个([^/]+)的正则表达式反向引用,它匹配除/个字符以外的所有字符,而$2是正则表达式反向引用第二个([^/]+) 1}}。

因此,如果用户请求localhost/authenticate/username/password,则apache处理程序会在内部将URL重写为/myfile.php?fn=authenticate&uname=username&passwd=password