自定义URL - 为每个用户提供一个网址 [英] Custom urls - giving each user a url

查看:304
本文介绍了自定义URL - 为每个用户提供一个网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个网站,我想这样他们的个人资料网址分享他们的名字来定制用户的个人资料。例如,该网站域名是www.example.com和用户的URL会www.example.com/username。

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 and the users' url would be www.example.com/username.

我假定这是一个惯例,因为我看到这一切围绕着网络。难道这个工作通过给每个用户自己的目录,以及如何艰苦会是这样?

I am assuming this is a convention because I see this all around the web. Is this done by giving each user their own directory and how painstaking would that be?

推荐答案

我真的不能证明使用htaccess的这样的事情。我只通过一个PHP文件(我的根的index.php )使用htaccess的路由一切,让PHP理清如何处理的URL。例如,你可以这样做:

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

然后做一些与 $用户名

我分析,并用我的URL更为复杂的比这一点,但它不会是适合您的问题的方法。只要确保无论你做什么能够说明任何可能的查询字符串,等等。

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不是伟大的表现,所以我不会滥用它。

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

下面是我原来的code样品仅有轻微扩张:

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]

这就是你可以做什么的index.php一个例子:

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

现在,您可以参观 mysite.com/myUserNameHere ,请求进入的index.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.

这需要路由的照顾,就像你问。我说,我的路由是比较复杂的,但我使用的是一个复杂得多,所以它是不相关的。我只是提醒我code在这里不考虑一个网址附加查询字符串,如mysite.com/someUser/?foo=bar。这是一个简单的过程来解析URL没有查询字符串,你应该能够处理。如果您需要进一步的帮助解析URL,然后进行职位要求有关。

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.

这篇关于自定义URL - 为每个用户提供一个网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆