0
votes

I'm using htaccess url rewrite only for index.php and using PHP to capture the GET parameter. When trying different parameter my website is giving 404 error on certain parameter which I found very strange. However below are the details:

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);
    }
}
?>

Please try the URL below as both values are not in my database, they are giving weird result.

  1. https://shop.specialpromo.asia/ddd will return error 404
  2. https://shop.specialpromo.asia/aaa will load just fine although no result found
1
[^/index.php] is a character class, not an exclusion. It's reqivalent to [^dehinpx./] and covers d… obviously. - mario
i see. How to make htaccess only allow rule for index.php then rewrite it? - Isaac
Use a negative lookahead, or a RewriteCond to exclude index.php. The common RewriteCond !-f approach might suffice even. - mario
I only want the rewriterule to happen when the page is index.php, can you show me the code? Thanks a lot - Isaac

1 Answers

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

Line 1: if request uri does not match any existing directory

Line 2: if request uri does not match any existing file

Line 3: then for every request uri, rewrite to index.php?company=$1, $1 is the backreference to the regex (.*)