sidlack
sidlack

Reputation: 51

How can I rewrite this url?

This is my login script. I am redirecting the user to /sws/index.php?user=$user but I want to use .htaccess to redirect them to /sws/index/user/$user.

The $user variable represents the users username!

I have tried lots of different tutorials to try and rewrite the URL but they didn't work! Can anyone suggest a .htaccess script that would work here? Also, when the user logs in I want the URL to be rewritten automatically.

<?php

if (isset($_POST['login'])) {

    include "functions/password.php";

    $email = $_POST['email'];
    $password = $_POST['password'];

    $result = mysqli_query($connect, "SELECT * FROM users0 WHERE email='$email'");
    $row = mysqli_fetch_array($result, MYSQLI_BOTH);

    if (password_verify($password, $row['password'])) {
        session_start();

        $_SESSION["id"] = $row['id'];
        $_SESSION["first_name"] = $row['first_name'];
        $_SESSION["last_name"] = $row['last_name'];
        $_SESSION["email"] = $row['email'];
        $_SESSION["company"] = $row['company'];
        $user = $_SESSION['first_name'] . $_SESSION['last_name'];

        header('Location: index.php?user=' . $user);
    } else {
        header('Location: index.php?error');
    }
}

?>

Upvotes: 0

Views: 66

Answers (3)

MrWhite
MrWhite

Reputation: 45829

I am redirecting the user to /sws/index.php?user=$user but I want to use .htaccess to redirect them to /sws/index/user/$user.

This isn't something you should be doing in .htaccess. Your application should redirect them to /sws/index/user/$user and you then use .htaccess (mod_rewrite) to internally rewrite the request to /sws/index.php?user=$user (the real URL). (If you do it in .htaccess then the user will experience multiple/unnecessary redirects.)

The only time you would need to do this in .htaccess is if the URL had previously been indexed by search engines or linked to. But since this is part of your login script then it's probably not necessary. (?)

So, change your script redirect to:

header('Location: /sws/index/user/'.$user);

Then, in the .htaccess in the document root, rewrite the request back to the full URL (similar to what devpro has already posted):

RewriteEngine On
RewriteRule ^sws/index/user/(.*)$ sws/index.php?user=$1 [L]

Upvotes: 0

Thanga
Thanga

Reputation: 8101

The below Apache redirect will do this (Even the URL has some more arguments also e-g: index.php?user=thanga&arg1=test).

RewriteRule ^index.php\?user\=([A-Za-z_0-9]*)(.*)$ index/user/$1$2 [R]

Upvotes: 0

devpro
devpro

Reputation: 16117

Try This:

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

Upvotes: 1

Related Questions