Search code examples
phpmysqlapachemod-rewritevanity-url

Create vanity URLs in a LAMP configuration


What is the best way to create user vanity URLs under a LAMP configuration?

For example, a user profile page could be accessed as follows:

http://www.website.com/profile.php?id=1

Now, if a user enters a "vanity URL" for their profile I would want the the vanity URL to load the page above.

For example, if a user selects "i.am.a.user" as their vanity URL and their user id in the database is 1 then http://www.website.com/profile.php?id=1 would be accessible by that URL and http://www.website.com/i.am.a.user .

I'm aware of mod rewrites in .htaccess but not sure how that would work here.

As I mentioned my site is in PHP, MySQL, Linux and Apache.

Thanks.


Solution

  • Say your other pages had specific URLs that you could check against, the following should help.

    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([a-zA-Z0-9-_]*)$ /profile.php?user=$1 [L]
    

    This helps to maintain current URLs, while allowing for the user shortcut URLs. Also, the RewriteRule will only match URLs that don't contain a /, which will help protect against non-intended redirects. So,

    /i-am-a-user -> MATCHES
    /i_am_a_user -> MATCHES
    /i-!am-a-user -> NOT MATCHED
    /i.am.a.user  -> NOT MATCHED
    /i.am.a.user/ -> NOT MATCHED
    /some/page/ -> NOT MATCHED
    /doesnotexist.php -> NOT MATCHED
    /doesnotexist.html -> NOT MATCHED
    

    Hope that helps.

    EDIT

    I've updated the rules above so that actual files/directories aren't redirected as well as making sure that any .php or .html file is not sent to profile.php either.