2012-10-10 81 views
0

我做了一个简单的网址缩写。我试图让.htaccess重写一个看起来像这样的http://chrismepham.com/q4IT612这个http://chrismepham.com/index.php?code=q4IT612的url,以便它可以用在一个函数中,该函数将重定向到一个外部url。.htaccess不重写我的网址

这里是我使用的.htaccess代码:

SetEnv TZ Europe/London 
RewriteEngine on 
RewriteRule ^([a-zA-Z0-9]+)$ index.php?code=$1 

在我的索引页面的顶部,我有以下:

if(isset($_GET['code']) && !empty($_GET['code'])){ 
     $code = $_GET['code']; 
     redirect($code); 
     die(); 
    } 

继承人的重定向功能:

function redirect($code){ 
//test the connection 
    try{ 
     //connect to the database 
     $dbh = new PDO("host;dbname=dbname","user", "pass"); 

    //if there is an error catch it here 
    } catch(PDOException $e) { 
     //display the error 
     echo $e->getMessage(); 
    } 

    if(code_exists($code)){ 
     $stmt = $dbh->prepare("SELECT url FROM url_shortener WHERE code=?"); 
     $stmt->bindParam(1, $code); 
     $stmt->execute(); 

     while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 

       $url = $row['url']; 
     } 
     header('Location: ' .$url); 
    } 
} 

为什么不重写网址?

感谢

+0

是否要:通过'http://chrismepham.com/index.php码= q4IT612'工作?你确定它不是PHP的问题吗? –

+0

什么版本的Apache? .htaccess文件是否启用? apache日志中的任何错误? – ernie

+0

@Jon奇怪的是,不,但这些做http://chrismepham.com/index.php?code=YntJL4和http://chrismepham.com/index.php?code=YHcpaO – crm

回答

0

我觉得您的规则必须是:

RewriteRule ^/?([a-zA-Z0-9]+)$ index.php?code=$1 

这使得斜线可选;不同版本的Apache处理这种不同

+0

谢谢,但没有做到这一点 – crm

0

你需要重写规则中的index.php前面的斜线:

RewriteRule ^([a-zA-Z0-9]+)$ /index.php?code=$1