创建用户/搜索引擎友好的 URL

发布于 2024-08-31 11:22:08 字数 117 浏览 2 评论 0原文

我想创建一个像 www.facebook.com/username 这样的 url,就像 Facebook 所做的那样。我们可以使用 mod_rewrite 来做到这一点吗?用户名是表中用户的名称。它不是子目录。请指教。

I want to create a url like www.facebook.com/username just like Facebook does it. Can we use mod_rewrite to do it. Username is name of the user in a table. It is not a sub directory. Please advise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

缺⑴份安定 2024-09-07 11:22:08

当然,mod_rewrite 可以做到这一点。这是一个关于它的教程

Sure, mod_rewrite can do that. Here is a tutorial on it.

从﹋此江山别 2024-09-07 11:22:08

是的,您可以做到这一点,但要使其正确进行,您可能会遇到一些初始障碍。

首先,您必须使用正则表达式来匹配它。如果您不了解正则表达式,那么一开始可能会感到困惑。

第二个是,您需要考虑到您要重写域上的顶级路径,您必须有某种机制,仅在文件不存在时才进行重写。

我想如果 mod_rewrite 支持测试 url 是否指向真实文件,那会很容易。如果没有,您可能必须使用它不会重写的单词黑名单,因为您需要一些保留字。

这至少包括包含您的图像、css、js 等的文件夹和您的网站运行的 index.php,以及您使用的任何其他 php 文件。

我想提供更多帮助,但我是一个 .net 人员,我通常会使用 UrlRewriter.net 等库来帮助解决 asp.net url 重写问题,这些库的配置与 mod_rewrite 不同。

为了匹配用户名,我将使用这样的正则表达式:

^/(\w*)/?$

然后将括号中的位放入一个变量中,您可以在重写中使用,例如

/index.php?profileName={0}

我提供的正则表达式的意思是:

  • ^在此之前没有任何内容
  • /正斜杠
  • (\w*)任何字母或数字的数量
  • /?可选的正斜杠
  • $ 此后没有任何内容

Yes you can do this but you might have a couple of initial hurdles to get it going correctly.

The first is that you will have to use a regular expression to match it. If you don't know regex then this can be confusing at first.

The second is that you will need to take into account that of you are going to rewrite the top path on the domain you will have to have some mechanism for only rewriting if the file doesn't exist.

I guess if mod_rewrite supports testing if the url points at a real file that will be easy. If not you might have to use a blacklist of words that it wont rewrite as you will need to have some reserved words.

This would include at the least the folder that contains your images, css, js, etc and the index.php your site runs off, plus any other php files you have kicking around.

I would like to be more help but I am a .net guy and I usually help out in asp.net url rewriting issues with libraries such as UrlRewriter.net which have different configurations than mod_rewrite.

To match the username I would use a regex like this:

^/(\w*)/?$

this would then put the bit in the brackets into a variable you can use in the rewrite like

/index.php?profileName={0}

The regex I provided means:

  • ^ nothing before this
  • / forward slash
  • (\w*) any number of letters or numbers
  • /? optional forward slash
  • $ nothing after this
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文