大网数据广告活动
网站运营与故障问答

Handling # uri fragments as regular requests

· 52CE 我爱测

So I have a one-page website with multiple sections and IDs. Right now, in the nav, I have it going to #about to jump them down to a section with ID=about But I want the user to be able to go to mysite.com/#about but without the …

问题原文

原帖链接 · Josh Holly · CC BY-SA 4.0

So I have a one-page website with multiple sections and IDs. Right now, in the nav, I have it going to #about to jump them down to a section with ID=about

But I want the user to be able to go to mysite.com/#about but without the #. So if the user goes to mysite.com/about, it will jump them down to the about section on the same domain.

How can I accomplish this? I imagine it's a dot htaccess modification with some javascript?

I've Googled all over for a solution but to no avail.

社区高分解答

原帖链接 · MrWhite · CC BY-SA 4.0

Assuming the file that renders your "one-page" site is index.html and your "pages" are /about, /contact and /help that correspond to elements with ids of the same name (less the slash prefix).

Your root .htaccess code would be something like the following, using mod_rewrite:

RewriteEngine On

RewriteRule ^(about|contact|help)$ index.html [L]

The above rewrites requests for the 3 URLs stated to index.html. So, those 3 URLs get the same HTTP response.

Then, JavaScript on the page would be something like:

// Get the URL-path, less the slash prefix
const id = location.pathname.substring(1);

// Get the HTML "page" element whose ID is passed in the URL.
const element = document.getElementById(id);
if (element) {
    element.scrollIntoView();
}

Note that the id could be empty or index.html. (Aside: You could redirect from /index.html to / in .htaccess.)

Although, as mentioned in comments, this might have accessibility issues over using the standard fragment identifier. And /#about and /about will return the same response - the first being handled by the browser and the second by JavaScript.

Reference:

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2022-11-27)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。