I'm programming a website which has a lot of users stored in a mysql_database where each user has an ID and profilename (like jim.button.1) among other fields. I want an url (which get's the profile through e.g a mysql_select on the userID) that has this structure: www.mysite.com/jim.button.1
Now I know that I could do that with a mod_rewrite_rule, but with thousands of users I'll get a very large .htaccess file. I'm not by far an expert in mod rewrite by the way, but I understand how it works.
Is there a way to do this, say in one or two mod_rewrite_rules or is there another smart way to accomplish this?
All help is welcome.
You could rewrite all URLs that don't map to an existing file, using:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</IfModule>
Then grab the actual URL via $_SERVER['REQUEST_URI']
. Here's an example:
$parts = parse_url($_SERVER['REQUEST_URI']);
$user = $parts['path'];
See https://github.com/zendframework/ZendSkeletonApplication/blob/master/public/.htaccess for an example.
You can use something like this:
RewriteEngine On
RewriteRule ^(.+)$ users.php?user=$1 [QSA,L]
In your users.php you can get the user like this:
$user = $_GET['user'];
// do your stuff with the user
You have to fine tune this to get it integrated with the rest of your site, but you get the idea.
I would combine both Ross Smith's and JvdBerg's so you'd end up with something like:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*)$ profile.php?user=$1 [NC,L]
</IfModule>
which would make it easier to process in your script rather than having to parse the entire URL. The beginning 4 lines after turning on the RewriteEngine
are needed so the rest of the site can continue to operate (checks directory, file, links) and if the url is one will use the first rule and not process any more. And then the second rule is if it isn't one of the previous and redirects as a get to your 'profile.php' page.
Then in your 'profile.php' page, you can get your values as:
list($fname, $lname, $id) = explode('.', $_REQUEST['user']);
And go from there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With