Search code examples
phpdnswildcardhyperlinkwildcard-subdomain

How to create sub-links for user on sign up?


I am looking to create vanity url for my users. How can i do it?

I want something like username.domain.com

My second question is, can i also customize this upon client requests? Like let's say, Client says add a feature to my account, will I be able to do it since it's almost like a separate site within my site?


Solution

  • You could use URL rewriting e.g. via Apache's mod_rewrite to solve this.

    For security and practical reasons however, I do not recommend using something like username.domain.com unless you carefully filter out user names like www. Better use username.u.domain.com or something similar.

    Here an example for rewrite rules using HTTP redirection.

    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\.domain\.com$
    RewriteCond %{HTTP_HOST} ^([^.]+)\.u\.domain\.com$
    RewriteRule .* http://domain.com/user/%1 [R,L]
    

    Alternatively, you could also use a DNS wildcard / catch-all entry and extract the user name part before your domain using a regular expression, e.g.

    function getUserNameFromHost() {
        if ( !preg_match('`^(\w+)\.u\.domain\.com$`', $_SERVER['HTTP_HOST'], $matches) )
            return false;
        else
            return $matches[1];
    }