I want to do a redirection where a user enters their user name in the URL and redirects to their profile, like this-> example.com/user/joe redirects example.com/user/profile.php?username=joe and obviously shows their profile.
I’ve looked around on how to do this but still haven’t managed to get it working.
How will I be able to do this? And where am I supposed to place my .htaccess file?
- root
- admin
- includes
- public
- user
- profile.php
- index.php
- user
From your directory it looks like ‘public’ directory is the document root for your website. So, place the .htaccess file there.
None of this is tested. But this should get you off the ground. I would use mod_rewrite to achieve this. Something like this should go into your .htaccess file.
This should solve your problem. The
[R]flag would cause Apache HTTPD to ask the browser to redirect and visit the new URL. Don’t use the[R,L]flag if you want the redirect to be internal without the user coming to know anything about it.Having said that, this is how I would really do it.
RewriteCond %{REQUEST_FILENAME} !-fandRewriteCond %{REQUEST_FILENAME} !-dwould be to make sure that when a user has requested for a resource that is a valid file or folder present in the server, just don’t bother about all these redirect rules, go ahead and serve that file or folder right away.The first
RewriteRuleis to make sure that if the user forgets the trailing slash, the server asks the browser to redirect to the URL with a trailing slash. This is how Apache HTTPD behaves by default (perhaps because of mod_dir) and I would try to preserve the same behaviour here as well.The second
RewriteRulemakes sure that a request tohttp://example.com/user/foo/is a valid URL buthttp://example.com/user/foo/bar/is not. The[QSA]flag ensures that any parameters added to the URL are preserved.Without the
[QSA]flag,http://example.com/user/foo/?ref=related+articleswould internally redirect tohttp://example.com/user/profile.php?user=foo. With that flag, it would redirect tohttp://example.com/user/profile.php?user=foo&ref=related+articleswhich is what I prefer.