Redirect using username to url using .htaccess

I want to do a redirect where the user enters their username 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 have looked around how to do this but still have not been able to get it to work. How can I do this? And where should I place my .htaccess file?

  • root
    • admin
    • includes
    • the public
      • user
        • profile.php
      • index.php
+2


source to share


1 answer


From your directory, it looks like a "public" directory - this is the document root for your site. So put your .htaccess file there.

None of this has been tested. But that should knock you off your feet. I would use mod_rewrite to achieve this goal. Something like this should go into your .htaccess file.

RewriteEngine On
RewriteRule ^user/(.+)$ user/profile.php?username=$1 [R,L]

      

This should fix your problem. The flag [R]

makes Apache HTTPD ask the browser to redirect and visit a new URL. Don't use a flag [R,L]

if you want the redirect to be internal if the user doesn't know anything about it.

Having said that, I will do it this way.



RewriteEngine On

# Canonicalize /user/foo to /user/foo/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^profile/([^/]+)$ /profile/$1/ [R=301,L]

# Map /user/foo/ to foo profile
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^profile/([^/]+)/$ profile/index.php?p=$1 [QSA]

      

RewriteCond %{REQUEST_FILENAME} !-f

and RewriteCond %{REQUEST_FILENAME} !-d

need to be sure that when a user has requested a resource that is a valid file or folder present on the server, just don't worry about all these redirection rules, go ahead and open that file or folder immediately.

The first is RewriteRule

to make sure that if the user forgets the trailing slash, the server asks the browser to redirect the URL with the trailing slash. This is how Apache HTTPD behaves by default (possibly due to mod_dir) and I would try to keep the same behavior here.

The second RewriteRule

ensures that the request http://example.com/user/foo/

is a valid URL, but http://example.com/user/foo/bar/

not. The flag [QSA]

ensures that any parameters added to the URL are preserved.

Without the flag [QSA]

http://example.com/user/foo/?ref=related+articles

will be internally redirected to http://example.com/user/profile.php?user=foo

. With this flag it will be redirected to http://example.com/user/profile.php?user=foo&ref=related+articles

which one I prefer.

+3


source







All Articles