锚点URL显示异常问题求助:点击导航栏锚点后URL格式不符且页面重载
Problem Recap
I’m using navigation links with href="./#anchor" for on-page anchors. When clicked, the page reloads (even after removing all JavaScript including the preloader), and the URL gets mangled to website/#/anchor/2 instead of the expected website/#anchor. There’s no <base> tag in my HTML, and this happens consistently on both local and live servers. Looking for help to fix this!
Troubleshooting & Fixes
1. Simplify the Anchor Link Syntax
The ./ prefix in your link is unnecessary and likely causing path parsing confusion. Anchor links are inherently tied to the current page, so:
- Replace
href="./#anchor"with the standard, clean syntax:href="#anchor" - If your page lives in a subdirectory (e.g.,
website/subpage/index.html),href="#anchor"will still work for anchors on the same page. For anchors on the root site’s homepage, use the absolute pathhref="/#anchor"instead.
This change should eliminate unnecessary page reloads and keep the URL intact as website/#anchor.
2. Audit Server Routing/Rewrite Rules
Since the issue persists across local and live servers, server configuration is the most likely culprit. Here’s what to check:
- Apache: Look into your
.htaccessfile formod_rewriterules that might be treating the#fragment as part of the URL path. Ensure rules don’t redirect or rewrite paths containing#. - Nginx: Verify your
try_filesor location block settings. Some SPA-focused configs redirect all paths to the homepage, which can corrupt anchor URL structure. - Static Hosting Platforms: If using services like Netlify or Vercel, check if "SPA Redirects" are enabled. This feature can override anchor behavior by treating all paths as dynamic routes.
Test this by manually typing website/#anchor into your browser’s address bar:
- If the URL stays correct and the anchor works, the issue was simply your link syntax.
- If the URL still morphs to
website/#/anchor/2, your server is modifying the path—adjust routing rules to ignore the#fragment (browsers don’t send this part to servers by default, so proper configs won’t parse it as a path).
3. Rule Out Directory/File Name Conflicts
Double-check if there’s a folder or file named anchor in your site’s directory structure. If ./anchor/ exists, the browser might misinterpret ./#anchor as a path to that directory plus an anchor, leading to the distorted URL.
内容的提问来源于stack exchange,提问作者Jeremy Marschfahrt

