.htaccess rewrite with GET variables

Tags: ,



am trying to create a url like this using htaccess… www.example.com/user/david

what i have now is this www.example.com/user?username=david

It works well when i do something like

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*/([a-zA-Z0-9_-]+)|([a-zA-Z0-9_-]+))$ ./user.php?username=$1 [L]

But i am wrong at my php code.

if(isset($_GET["username"]))
{
    $stmt = $mysqli->prepare("SELECT * FROM campus_users WHERE campus_name = ?");
    $stmt->bind_param("s", $campus_name );
    $campus_name = trim($_GET["username"]);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows == 1) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        //displaying users rows
    } else {
        header("location: blank-page");
      exit();
    }
} else {
  header("location: home.php");
  exit();
}

But when i enter the url like this www.example.com/user?username=david it works well…

The problem is i want a smart looking url which isnt working due to my php i guess.

Please help me. Thanks in advance.

Answer

If your URL with query string is working fine then it most probably it means your .htaccess rules are not working, usually we give user friendly URLs to users in your case it should be www.example.com/user/david and internally it should route to www.example.com/user.php?username=david. Please try following Rules in your .htaccess file.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/user/(.*)$
RewriteRule ^.*$ /user.php?username=%1 [QSA,NC,NE,L]

NOTE: if possible and you are not on prod systems then you could try to restart your Apache service too, though it’s not necessary but sometimes it may be required. Also use user friendly URL as mentioned above in browser make sure you clear the browser cache before hitting it.



Source: stackoverflow