I need to create a vanity URL redirect using htaccess and PHP.

My requirements are:

If a user writes example.com/users/foobar The client will be redirected to for example: profile.php?user=foobar in either the /users/ directory or the root directory. Possibly in an /inc/ folder in the root directory.

A example.com to www.example.com redirect is also necessary. The URL needs to stay same visually. I would like all of this in a single .htaccess file.


I would also like (although not a requirement) the redirect to also be applied on example.com/foobar

I have not found any answers that does this.

  • Why would you want to convent /users/username/ into profile.php?user=username the first example looks better and will help your committed members remember their URL easier, just saying... Commented Aug 20, 2015 at 9:52
  • 2
    @SimonHayter I assume the OP really means an "internal rewrite", as otherwise I agree, "The client will be redirected" doesn't appear to make a whole lot of sense.
    – MrWhite
    Commented Aug 20, 2015 at 10:42
  • "Possibly in an /inc/ folder in the root" - "possibly"? Yes or no?
    – MrWhite
    Commented Aug 20, 2015 at 10:45

1 Answer 1


First off the easiest one for www is this.

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^yourwebsite\.com$ [NC]
RewriteRule ^(.*)$ http://www.yourwebsite.com/$1 [R=301,L]

Now for some actual rewriting you should be able to use something like this.

RewriteCond $1 !^(users)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ profile.php?user=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)$ profile.php?user=$2 [L]

But to be honest, in my experience your best bet is just to try for yourself and create for your specific needs. If you don't create it for yourself and just go copy pasting, any minor change you will need and you will get in trouble. There is enough of examples and explanations just through google or checking other questions here on stackexchange.

  • Shouldn't the last RewriteRule be more specific? eg. RewriteRule ^users/([^/]+)$ profile.php?user=$1 [L]
    – MrWhite
    Commented Aug 20, 2015 at 10:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.