What is the difference between hash mode and history mode in routing?
/ 2 min read /
#ai
Let me explain the differences between hash mode and history mode in routing in detail:
- URL Format Differences:
- Hash mode: Uses the
#symbol, e.g.:www.example.com/#/home2 - History mode: More like a traditional URL, e.g.:
www.example.com/home2
- Working Principle Differences:
-
Hash mode:
- Uses the hash (
#) portion of the URL to simulate a full URL - The hash part is not sent to the server
- Based on the browser’s
hashchangeevent 2
- Uses the hash (
-
History mode:
- Based on the HTML5 History API
- Uses
pushStateandreplaceStatemethods to manage history - URLs are cleaner and more like traditional server-side routing 2
- Server Configuration Requirements:
-
Hash mode:
- No special server configuration needed
- Because the hash part is not sent to the server
- Less SEO-friendly 2
-
History mode:
- Requires server configuration support
- Needs to be configured so all routes return
index.html - Otherwise, you’ll get 404 errors 2
- Server Configuration Examples (History mode):
Apache configuration:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]</IfModule>Nginx configuration:
location / { try_files $uri $uri/ /index.html;}- How to Choose:
-
Choose Hash mode if:
- You don’t want to configure the server
- The project doesn’t need clean URLs
- SEO requirements are low
-
Choose History mode if:
- You need better-looking URLs
- The project needs better SEO
- You have control over the server configuration
- Compatibility Considerations:
- Hash mode: Better compatibility, supports more browsers
- History mode: Requires HTML5 History API support; all modern browsers support it
- Migration Advice: If migrating from Hash mode to History mode:
- Make sure the server is properly configured
- Update the router configuration
- Test that all routes work correctly
- Check that direct URL access works 2
In real-world development, if you’re using a modern frontend framework (like Next.js, Umi, etc.), they usually default to History mode and handle the server configuration automatically, letting developers focus on business logic.
Source: Claude 3.5 Sonnet