即使唯一提供的参数是 id,如何使用 mod_rewrite 自动获取 slug

发布于 2025-01-07 23:26:26 字数 287 浏览 4 评论 0原文

即使只提供了 id,我也想获得 slug。例如,我输入:

http://stackoverflow.com/questions/6421212/

站点加载后,URL 变为:

http://stackoverflow.com/questions/6421212/how-to-rewrite-url-with-post-title-slug

我的意思是,即使我只输入了 Id,我也想拉出 slug。

提前致谢!

I want to get the slug even if only the id is supplied. For example I enter this:

http://stackoverflow.com/questions/6421212/

After the site has been loaded, the URL becomes:

http://stackoverflow.com/questions/6421212/how-to-rewrite-url-with-post-title-slug

What I mean is that that I want to pull up the slug even if I only entered the Id.

Thanks in advance!

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

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

发布评论

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

评论(2

打小就很酷 2025-01-14 23:26:26

mod_rewrite 不知道给定 ID 的正确 slug。您的应用程序会生成 slug。因此,您可以使用 ID 从数据库中获取 slug,并将其与浏览器发送的 slug 进行比较。如果不匹配,则发出 301 重定向到完整(如果 slug 为空)或正确(如果 slug 不匹配)URL。这就是SO的工作原理。打开这些 URL 并查看网络检查器以了解我的意思:

  • http://stackoverflow.com/questions/9393455/
  • http://stackoverflow.com/questions/9393455/foo -bar-blah-baz

在 PHP 中,检查 $_SERVER 超级全局,您应该能够在重写之前找到包含实际 URL 的变量。您可以像这样发送 301 标头:

header("Location: /1234/correct-slug", true, 301);

mod_rewrite does not know the right slug for the given ID. Your application that generates the slug does. So you grab the slug from the database using the ID and compare it with the one sent by the browser. If it does not match, issue a 301 redirect to the full (if slug was empty) or correct (if the slug did not match) URL. That's how SO works. Open these URLs and look at the net inspector to see what I mean:

  • http://stackoverflow.com/questions/9393455/
  • http://stackoverflow.com/questions/9393455/foo-bar-blah-baz

In PHP, inspect the $_SERVER super global, you should be able to find the variables that contain the actual URL before re-writing. And you can send 301 header like so:

header("Location: /1234/correct-slug", true, 301);
再浓的妆也掩不了殇 2025-01-14 23:26:26

在加载的页面中,几乎立即检查 slug。如果它不存在,请将其从数据库中拉出(您有 ID)并重定向到新的完整链接。

如果您在渲染任何 HTML 等之前执行此操作,那么看起来就像是在没有重定向的情况下完成的。

如果您发布当前的 htaccess,我可以修改您必须允许提供的 slug 和不提供的 slug。

In the page that loads, check for the slug almost immediately. If it doesn't exist, pull it out of the database (You have the ID) and redirect to the new full link.

If you do that before rendering any HTML etc, it'll look like it's been done without a redirect.

If you post your current htaccess, I can modify what you have to allow for both slug provided, and no slug provided.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文