URL重写和重定向(包含数据库数据)

时间:2015-05-14 16:56:39

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

我的网址是http://testurl.com/user.php?id=1&name=TestUser

上述链接的默认网址必须与http://testurl.com/user/12345/TestUser

类似

如果用户尝试在自己的浏览器链接中进行更改,如下所示

http://testurl.com/user/12345
http://testurl.com/user/12345/
http://testurl.com/user/12345/TestUsers_bla-bla

然后网址栏会自动更改为http://testurl.com/user/12345/TestUser

修改

<?php
$name = "This-is-a-test-user";
$id = 1;


$fields = array('id' => $id,
                'name' => $name);


$url = "http://localhost/view_user.php?" . http_build_query($fields, '', "&");
?>

<a href = "<?php echo $url; ?>"> View User</a>

3 个答案:

答案 0 :(得分:1)

在root / .htaccess文件中尝试此操作

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^user/([a-zA-Z0-9]+)/?$ /user.php?id=$1 [QSA,L]

RewriteRule ^user/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/?$ /user.php?id=$1&name=$2 [QSA,L]

条件确保您不会重写服务器上的任何现有文件/目录。

答案 1 :(得分:1)

为什么不试着让一个非常基本的规则起作用,然后从那里开始。

首先,您需要确保服务器启用了重写模块,然后在htaccess文件的顶部放置:

public function export_excel($id)
    {
        require_once APPPATH.'Classes/PHPExcel.php';

    $queryResult = $this->get($id);

    $objPHPExcel = new PHPExcel();

    $objPHPExcel->setActiveSheetIndex(0);  


    $result = mysql_query($queryResult[0]['query_sql']) or die (mysql_error());

    //echo "SQL = ",    $queryResult[0]['query_sql'];  // pass query allright

    // Initialise the Excel row number 
    $rowCount = $queryResult[0]['start_line'];
    //start of printing column names as names of MySQL fields  
    $column = $queryResult[0]['title_cell'];

    for ($i = 1; $i < mysql_num_fields($result); $i++)  
    {
        $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
        $column++;
    }
    //end of adding column names  

    //start while loop to get data  
    $rowCount = $rowCount+1;  
    while($row = mysql_fetch_row($result))  
    {  
        $column = 'B';
        for($j=1; $j<mysql_num_fields($result);$j++)  
        {  
            if(!isset($row[$j]))  
                $value = NULL;  
            elseif ($row[$j] != "")  
                $value = strip_tags($row[$j]);  
            else  
                $value = "";  
            $objPHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
            $column++;
        }  
        $rowCount++;
    }

    $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
    //$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');


    // Write the Excel file to filename some_excel_file.xlsx in the current directory
    if($queryResult[0]['template_location'] !=null){
        $objWriter->save($queryResult[0]['template_location']); 
        //echo date('H:i:s') , " Write to Excel2007 format" , EOL;
        return 1;
    }

    else{
        $objWriter->save('php://output');
        //echo date('H:i:s') , " Write to Excel2007 format" , EOL;
        return 1;
    }

    return null;

}

然后你可以使用正则表达式重写规则。例如:

RewriteEngine On

答案 2 :(得分:1)

这里你需要两件事。

1)要处理的htaccess规则

  • http://testurl.com/user/12345
  • http://testurl.com/user/12345/
  • http://testurl.com/user/12345/xxx

相应规则,以避免重复内容(将旧格式/user.php?xxx重定向到新格式/user/ID/NAME

为此,您可以将此代码放在root htaccess

Options -MultiViews

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \s/user\.php\?id=([0-9]+)\s [NC]
RewriteRule ^ user/%1? [R=301,L]

RewriteCond %{THE_REQUEST} \s/user\.php\?id=([0-9]+)&name=([^&\s]+)\s [NC]
RewriteRule ^ user/%1/%2? [R=301,L]

RewriteRule ^user/([0-9]+)/?$ user.php?id=$1 [L]
RewriteRule ^user/([0-9]+)/([^/]+)$ user.php?id=$1&name=$2 [L]

注意:此时,请确保已启用 mod_rewrite 且允许htaccess(在Apache配置文件中)。

一个简单的测试:http://example.com/user/12345/XXXXX应在内部重写为/user.php?id=12345&name=XXXXX

2)现在您需要调整user.php逻辑(这是检查数据<ID, NAME>对存在的位置)

<?php
if (!isset($_GET['id']) || empty($_GET['id']))
{
   // error page not found (since there is no ID)
   header("HTTP/1.1 404 Not Found");
   return;
}

if (!isset($_GET['name']) || empty($_GET['name']))
{
   // no name -> get it by its ID
   $name = getNameByID($_GET['id']); // this function checks in the database

   if ($name === NULL)
   {
      // error: ID is unknown -> page not found
      header("HTTP/1.1 404 Not Found");
      return;
   }

   // ID exists, we now have its name -> redirect to /user/ID/NAME (instead of /user/ID)
   header("HTTP/1.1 301 Moved Permanently");
   header("Location: /user/".$_GET['id']."/".$name);
   return;
}

// if we reach here, we have an ID and a name in the url
// we have to check if NAME corresponds to ID (and if ID exists)

$name = getNameByID($_GET['id']); // this function checks in the database

if ($name === NULL)
{
   // error: ID is unknown -> page not found
   header("HTTP/1.1 404 Not Found");
   return;
}

// now, check if NAME in the url corresponds to the one we got from database

if ($name !== $_GET['name'])
{
   // it doesn't -> redirect to good NAME
   header("HTTP/1.1 301 Moved Permanently");
   header("Location: /user/".$_GET['id']."/".$name);
   return;
}

// finally, here we're fine.
// do what you then have to do...

?>

我故意用&#34;复制&#34;写这段代码。让你理解逻辑的部分 当然,你可以改进它。