【问题标题】:How do I rewrite the URL for example.com/index.php#anchor to example.com/anchor?如何将 example.com/index.php#anchor 的 URL 重写为 example.com/anchor?
【发布时间】:2014-11-07 23:46:15
【问题描述】:

我有一个页面 (example.com),在主要部分有锚点 (example.com/index.php#anchorexample.com/index .php#aboutexample.com/index.php#contact 等)以及子页面(example.com/subpage.php)。

这是我的 .htaccess 文件:

RewriteEngine On

DirectoryIndex index.php
ErrorDocument 404 http://example.com/my404page.php

RewriteRule ^anchor/?$ index.php#anchor [R,NE,L]
RewriteRule ^subpage/?$ subpage.php [NE,L]

子页面重写规则效果很好。

对于锚链接,包括“R”(重定向)标志会将 URL 更改为 example.com/index.php#anchor但我希望 URL 为 example.com/anchor

如果我删除 R 标志并在我的浏览器中输入 example.com/anchor,它会转到索引页面并保留干净的 URL(example.com /anchor) 但不会滚动到锚点

那么...有没有办法在 .htaccess 中实现这一点,或者有没有用 JavaScript 实现这一点的好方法?

【问题讨论】:

  • @zackify 为什么“JavaScript”这个问题的标签不好?
  • hashtag 是客户端无法使用 mod_rewrite 进行操作。
  • @Prix 我读过的内容,这显然是为什么只有 [R] 重定向有效......但我还没有在 SO 或其他任何地方找到一个好的解决方案。
  • 这与javascript甚至php无关,这就是我把它拿出来的原因。如果您要使用 javascript 来执行此操作,只需将 '#' 替换为 '/' 然后重定向到该 url 就不会那么难了。
  • @zackify 看起来我正在寻找使用 JavaScript 来实现这一点。我包含 .htaccess 代码的原因是因为我想展示我尝试过的内容。您能否详细说明“只需将 '#' 替换为 '/',然后重定向到该 url”?

标签: php .htaccess rewrite


【解决方案1】:

无法通过 URL 重写来做到这一点。因为当# 是 URL 的一部分时浏览器向下滚动...而不是在服务器端。

【讨论】:

    【解决方案2】:

    .htaccess 无法做到这一点。但是您可以使用以下 JavaScript 代码来实现:

    window.location = String.prototype.replace(window.location, /index\.php#(.*)/, function(match, g1){return g1;});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 2011-12-13
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2011-04-15
      • 2012-10-13
      相关资源
      最近更新 更多