【问题标题】:How to use .htaccess for beautiful links [duplicate]如何使用 .htaccess 获得漂亮的链接 [重复]
【发布时间】:2013-01-10 21:17:19
【问题描述】:

可能重复:
.htacces to create friendly URLs. Help needed

我正在使用 ids 来显示成员的记录(个人资料)。

所以/profile.php?id=1显示id为1的成员的数据。

但是这些网址很丑陋,而且对 SEO 也不友好。

我想将网址更改为profiles/membername 格式(成员名是已存储在数据库中的每个成员的唯一别名)。

如何通过.htaccess实现这个链接结构?

【问题讨论】:

  • 我也想要漂亮的链接 :D
  • 你应该在你的应用程序中解决这个问题,而不是.htaccess

标签: php mysql apache .htaccess


【解决方案1】:

这需要安装 apache 的 mod_rewrite 模块。你想要的可以通过下面这段代码来实现:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^profiles/(.*)?$ profile.php?id=$1
</IfModule>

示例: www.yourwebsite.com/profiles/1234 -> www.yourwebsitename.com/profile.php?id=1234 如果您想要更多变量,只需修改上面的行,如下所示:

RewriteRule ^profiles/(.*)/(.*)?$ profile.php?id=$1&var2=$2

只需编辑您的 .htaccess 文件并添加以上行,确保在进行任何修改之前创建 .htaccess 的备份。

【讨论】:

  • 感谢 Sathiya,但是如果有成千上万个潜在的 id,我必须为每个人创建规则吗?
  • 并非如此,上面的单个规则充当通配符条目: RewriteRule ^profiles/(.*)?$ profile.php?id=$1 这意味着它对所有形式为 / 的 URL 都有效profile/1234 或 /profiles/1235 等,其中“1234”和“1235”是 ID 变量的值。我发布的第二条规则只是一个示例,向您展示如何重写 URL,以防您想发送多个参数,即 ?id=1234&name=John
【解决方案2】:

先看一些关于问题的文章 http://httpd.apache.org/docs/2.2/howto/htaccess.html

RewriteEngine On

RewriteRule ^profiles/(a-z0-9]+)$ /profile.php?username=$1 [L,QSA]

所以例如/profiles/membername ---> /profile.php?username=membername

【讨论】:

  • 谢谢,但如果有数千个潜在的 id,我必须为每个人创建规则吗?
  • 不,它的通用性.../profiles/anything --> /profile.php?username=anything
  • 非常感谢,今天就试试这个。让你知道
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-06
  • 2011-03-22
  • 2012-11-01
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
相关资源
最近更新 更多