How to use .htaccess rewrite

Patrick S.

Seasoned Veteran
Joined
Apr 1, 2011
Messages
3,378
Reaction score
0
FP$
6
Here is something cool for every one out there.
My tutorial on How to use .htaccess rewrite.

What it does is you have a file say test.php?user=glock you want it to say /my-profile-glock with out having to create a directory for every profile.

First create a test file.
test.php
Put this in it
Code:
<?php
$user = $_GET['user'];
if (isset($_GET['user'])) {
echo "Hello $user";
}else{
echo "Get out of here";
};
?>

Now open .htaccess file(it's a hidden file) if you can't see it even if you can see hidden files you need to create on.
Put this in it:
Code:
RewriteEngine On
RewriteRule ^my-profile-([^/]*)$ /test.php?user=$1 [L]

You probably know what the PHP does so I will only explain the htaccess

First RewriteEngine On
Means .htaccess knows it can rewrite the url

second RewriteRule
Put that so it knows to rewrite only that file
^ starts the rewrite and $ ends it
([^/]*) this is for the profile name is it does what ever profile you want.
you can add more like this:
my-date-([^/]*)-([^/]*)-([^/]*)

now for this:
/test.php?user=$1
first off the $1 is the profile name in the PHP to add more just do
/test.php?user=$1&something=$2&something=$3

Basically like that

any questions? Just ask me in the tread 😉 Good luck
 
Forgive me if I'm wrong but you don't seem to know what your talking about when you explain what is happening in the .htaccess file with those characters.

I don't mean to be rude, it's just your post read that way.

Also you don't need to put $ in the URL, that signals a variable in the PHP code which has already been defined in there. You should just have user=1 and the varible work.

Also with just that simple bit of code, without any back-end code to it, the code won't work as it's going to need to search for a reason to either deny or accept the variable being processed.

*Edit:
I read your post again and it seems that it will work providing that you enter in the URL with the ID of 1 at the end, but what I said above still applies; there is no bacl-end code supporting it so anyone can enter in the ID of one and it will show the "Hello $user" which is the variable for the id so it will actually show "Hello 1".
 
Here let me try to explain
Code:
<?php
$user = $_GET['user'];
if (isset($_GET['user'])) {
echo "Hello $user";
}else{
echo "Get out of here";
};
?>
That echo's hello (name) but you have to enter this as a URL
test.php?user=glock
So that it would output the right code (in this case hello glock)
Now if you add this you your .htaccess file
Code:
RewriteEngine On
RewriteRule ^my-profile-([^/]*)$ /test.php?user=$1 [L]
You could go to
/my-profile-glock
and it would output same as above
hello glock.
in Htaccess $1 stands for anything like * in php
([^/]*) this is telling the server that $1 = glock.
Does that help?
 
Back
Top Bottom