Custom urls - giving each user a url

前端 未结 3 1724
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 02:27

I am building a website and I would like to customize the users\' profile so their profile url shares their name. For example, the website domain would be www.example.com an

3条回答
  •  甜味超标
    2020-12-12 02:50

    I really can't justify using htaccess for something like this. I only use htaccess to route everything through one php file (my root index.php) and let php sort out how to handle the url. For example, you could do this:

    $uri = trim($_SERVER['REQUEST_URI'], '/');
    $pieces = explode('/', $uri);
    $username = $pieces[0];
    

    Then do something with $username.

    The way I parse and use my url's is a bit more complicated than this, but it wouldn't be relevant to your question. Just make sure whatever you do is able to account for any possible query strings, etc.

    mod-rewrite is not great for performance, so I wouldn't abuse it.

    Updated based on your comments.

    Here's just a slight expansion on my original code sample:

    //.htaccess - route all requests through index.php
    RewriteCond %{REQUEST_URI} !\.(png|jpe?g|gif|css|js|html)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ index.php [L]
    

    and this is an example of what you could do in index.php:

    $pieces = preg_split('-/-', $_SERVER['REQUEST_URI'], NULL, PREG_SPLIT_NO_EMPTY);
    $username = $pieces[0];
    
    include "users/{$username}.php";
    

    Now you could visit mysite.com/myUserNameHere, the request goes to index.php which parses out the username and includes a file for that user.

    That takes care of the routing just like you asked. I said that my routing is more complicated, but my use is a lot more complicated, so it isn't relevant. I only warned that my code here doesn't account for a url with a query string attached, like "mysite.com/someUser/?foo=bar". It's a simple process to parse the url without the query string and you should be able to handle that. If you need further assistance parsing the url, then make a post asking about that.

提交回复
热议问题