1

I was wondering if I'm supposed to use .htaccess to change a get variable to a value from the database (username).

so if there is

http://www.url.com/user.php?u=1

how do you conver it to

http://www.url.com/andrewliu

Thanks!

3 Answers 3

3

You need to change your user.php to take a username instead of a userid. Then you can use something like:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?([a-z0-9_-]+)/?$ /user.php?u=$1 [L]

This passes the username through the u query string parameter, essentially: /user.php?u=andrewliu

Otherwise there's no way htaccess and mod_rewrite can know what the mapping is between user_id and username. Alternatively, you can write a database script and use RewriteMap to create a mapping for you:

RewriteMap usermap prg:/path/to/userscript

and in your htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?([a-z0-9_-]+)/?$ /user.php?u=${usermap:$1} [L]

The last option, if you've only got, say, 5 users (or some small amount), you can make explicit rewrites:

RewriteEngine On
RewriteRule ^/?andrewliu$ /user.php?u=1 [L]
RewriteRule ^/?anotheruser$ /user.php?u=2 [L]
RewriteRule ^/?foousername$ /user.php?u=3 [L]
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! I just set my get variable to my username and applied your rewriterule for the user.php. works like a charm! Thank yoU!
3

You need to use Mod-ReWrite. You can use this in your htaccess files but if you have access to your httpd.conf file it will prove to be quicker there.

You would ideally use the ?u=1 in your htaccess file and use that to find the the name and append the name onto the end. Otherwise you will have to search for the username and could be succesiptable to spelling mistakes etc etc.

RewriteRule ^/([0-9]+)/.*$ /user.php?u=$1 [L]

This is how Stackoverflow does it, try accessing this page without the number in the url and you will get a 404 page not found. Get the number right and what ever else you type after the forward slash will be exchanged for the correct words! This is much more convienent!

1 Comment

+1 for mentioning to use httpd.conf and not htaccess. To explain properly this is because htaccess is read on single request using up the servers resources whereas the conf page is read only when the service is started!
0

Use $GET in php to get the value of 'u'

Then use your logic to convert it to name.

Now just use redirect function to go to to that URL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.