URL重写和GET参数

时间:2018-01-07 06:04:59

标签: php html .htaccess url-rewriting

我只使用htaccess url重写index.php并使用PHP捕获GET参数。当尝试不同的参数时,我的网站在某些参数上给出404错误,我觉得很奇怪。但以下是详细信息:

htaccess的

RewriteRule ^([^/index.php]*)$ /index.php?company=$1 [L]

的index.php

<?php
$name = 'specialpromo';

if(isset($_GET['company'])) {
    include 'include/dbconfig.php';  

    // Create connection
    $conn = mysqli_connect($servername, $username, $password);

    // Check connection
    if (!$conn) {
        $errmsg = "Connection error";
    } else {
        if(!(mysqli_select_db($conn,$dbname))){
            $errmsg = "Database error";
        } else {
            $sql_comp = $conn->prepare("select a.* 
            from company a
            where a.code = ?");
            $sql_comp->bind_param('s', $_GET['company']);
            $sql_comp->execute();
            $rs_comp =  $sql_comp->get_result() or die('Error, query failed<br />');

            $numrow_comp = mysqli_num_rows($rs_comp);

            if ($numrow_comp==1){
                if($row_comp = mysqli_fetch_assoc($rs_comp)){
                    $name = $row_comp['name'];
                }
            }

            mysqli_free_result($rs_comp);
        }
        mysqli_close ($conn);
    }
}
?>

请尝试下面的网址,因为这两个值都不在我的数据库中,它们会产生奇怪的结果。

  1. https://shop.specialpromo.asia/ddd将返回错误404
  2. https://shop.specialpromo.asia/aaa会很好地加载,但没有找到结果

1 个答案:

答案 0 :(得分:0)

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*) index.php?company=$1 [L]

第1行:如果请求uri与任何现有目录不匹配

第2行:如果请求uri与任何现有文件不匹配

第3行:然后对于每个请求uri,重写为index.php?company=$1$1是对正则表达式(.*)

的反向引用