如何将example.com/index.php#anchor的URL重写为example.com/anchor?
我有一个页面(example.com),主要部分(example.com/index.php#anchor,example.com/index.php#about,example.com/index.php#contact)以及子页面(example.com/subpage.php) 这是我的.htaccess文件:如何将example.com/index.php#anchor的URL重写为example.com/anchor?,php,.htaccess,rewrite,Php,.htaccess,Rewrite,我有一个页面(example.com),主要部分(example.com/index.php#anchor,example.com/index.php#about,example.com/index.php#contact)以及子页面(example.com/subpage.php) 这是我的.htaccess文件: RewriteEngine On DirectoryIndex index.php ErrorDocument 404 http://example.com/my404page.
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有没有一个好方法来实现这一点?用URL重写是不可能做到的。因为当
#
是URL的一部分时,浏览器会向下滚动。。。不在服务器端。您不能使用.htaccess
执行此操作。但您可以使用以下JavaScript代码来实现:
window.location = String.prototype.replace(window.location, /index\.php#(.*)/, function(match, g1){return g1;});
@zackify为什么“JavaScript”是这个问题的坏标签?标签是客户端不能用mod_rewrite操作的。@请相信我所读的,这显然是为什么只有[R]重定向有效。。。但我还没有找到一个很好的解决方案,这与javascript甚至php无关,这就是我为什么选择它的原因。如果你用javascript来做这件事,那么简单地用“/”替换“#”,然后重定向到那个url就不会那么难了。@zackify看起来我想用javascript来实现这一点。我之所以包含.htaccess代码,是因为我想展示我所做的尝试。你能详细说明一下“简单地用“/”替换“#”,然后重定向到那个url”吗?