I have a URL http://localhost/index.php?user=1. When I add this .htaccess file

Options +FollowSymLinks
RewriteEngine On

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

I will be now allowed to use http://localhost/user/1 link. But how about http://localhost/index.php?user=1&action=update how can I make it into http://localhost/user/1/update ?

Also how can I make this url http://localhost/user/add ? Thanks. Sorry I am relatively new to .htaccess.


Solution 1:

If you want to turn

http://www.yourwebsite.com/index.php?user=1&action=update

into

http://www.yourwebsite.com/user/1/update

You could use

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^user/([0-9]*)/([a-z]*)$ ./index.php?user=$1&action=$2

To see the parameters in PHP:

<?php 
echo "user id:" . $_GET['user'];
echo "<br>action:" . $_GET['action'];
?>
  • The parenthesis in the .htaccess are groups that you can call later. with $1, $2, etc.
  • The first group I added ([0-9]*) means that it will get any numbers (1, 34, etc.).
  • The second group means any characters (a, abc, update, etc.).

This is, in my opinion, a little bit more clean and secure than (.*) which basically mean almost anything is accepted.

Solution 2:

you can write something like this:

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