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->


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

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

is a valid URL, but

not. The flag [QSA]

ensures that any parameters added to the URL are preserved.

Without the flag [QSA]

will be internally redirected to

. With this flag it will be redirected to

which one I prefer.



All Articles