htaccess
is not best for performance and is more limited than handling the routing with php. First, you use htaccess
only to direct most requests to a php file:
RewriteCond %{REQUEST_URI} !\.(png|jpe?g|gif|css|js|html)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ index.php [L]
Then, your routing could be as simple as:
$pieces = preg_split('-/-', $_SERVER['REQUEST_URI'], NULL, PREG_SPLIT_NO_EMPTY);
$username = $pieces[0];
include "users/{$username}.php";
but there is a lot more to do in a real application context. There are many php frameworks that have routing features built in that you may be interested in. Any major framework will include this.
Here's a slighly expanded version of this answer on a similar previous post: https://stackoverflow.com/a/20034826/1435655
To expand a bit more, the basic idea most routing systems use is you write out the routes that you accept and what will handle them. When a request comes in, those routes are searched until a match is found. Think of it like this:
$myRoutes = [
'/' => 'home.php',
'/about' => 'about.php'
//etc
];
$route = $_SERVER['REQUEST_URI'];
if (in_array($route, $myRoutes)) {
include $myRoutes[$route];
}
else {
echo "Go to a real page. This one doesn't exist."
}
You could expand that to define url parameters so that /users/someDude
will be sent to users.php
and something like $routeParams['username']
will have a value of someDude
.