网站如何使用url的第一部分作为变量,如twitter.com/Name


How do websites use the first part of the url as a variable, like twitter.com/Name

我知道如何使用$_SERVER["REQUEST_URI"]在类似example.com/page.php/variable的url中使用变量,但我想知道如何使用url的第一部分来完成类似的事情,就像twitter所做的那样:使用php和apache的twitter.com/name

这是因为使用了.htaccess。点击此处了解更多信息。

实际上,我们在.htaccess中指定了url结构的由来。下面是一个简单的例子。

RewriteEngine On
RewriteRule ^([^/]*)'.html$ /?name=$1 [L]

上面的代码实际上是这样做的。您将一个url作为www.example.com/page.html传递,它实际上被转换为www.example.com/?name=page。如果删除.html,则实际上会有www.example.com/page。希望这能帮助你,如果你在谷歌上搜索,你可以找到很多关于它的教程。

也许您可以尝试PHP中的parse_url((函数。此函数创建一个数组,该数组中包含有关您给的URL的信息

http://php.net/manual/en/function.parse-url.php

发件人:php.net:

$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));

如果您使用的是apache,您可以编辑htaccess文件来满足您的需求
htaccess有很多功能,为了改变url行为,您可以使用mod_rewrite功能