GROVER.
GROVER.

Reputation: 4388

.htaccess get variable through url rewrite not working

I have a script inside of my .htaccess file in which I am attempting to change the url from localhost/testing/user/index?username=example to localhost/testing/user/example.

I am doing this just to make my website look "cleaner" and easier to navigate around users.

This is my current htaccess file:

RewriteEngine On
RewriteRule ^user/([A-Za-z0-9-]+)$ user/index?username=$1;
RewriteRule ^user/$ user/index;

For some reason this doesn't want to work for me and ALWAYS throws either a 404 or 500 error.

This is the PHP code in which I am using to get the username passed through the URL.

if(isset($_GET['username']) && empty($_GET['username'])){
        header('location: ./');
    }

    if(empty($_GET['username']) && logged_in() == false){
        header('location: ./');
    } else if(empty($_GET['username']) && logged_in() == true || isset($_GET['username']) && $_GET['username'] === $username){
        $pageDisp = 1;
    } else if(!empty($_GET['username']) && $_GET['username'] !== $username){
        $pageDisp = 2;
}

In the PHP, if $_GET['username'] is empty, it will just set the user to the logged in user, but if they are logged in, it will redirect them to a 404.

This is the layout of my folders and scripts:

.htaccess : /testing/user/

user index.php : /testing/user/

main index.php : /testing/

ALl of these files are located inside of my XAMPP htdocs folder.

All help is appreciated Thanks

Upvotes: 2

Views: 1257

Answers (1)

keziah
keziah

Reputation: 574

This code works for me

Match anything after the /testing/user/*

HTACCESS

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testing/users/([^/]*)$ /testing/users/?username=$1 [L]

index.php inside the /testing/users/ (test)

<?php echo $_GET['username'] ?>

Upvotes: 1

Related Questions