文章目录
1. Hash 模式
Hash 模式是 Vue Router 的默认模式,它使用 URL 的 hash 部分(即 #
后面的部分)来实现路由。
特点
-
URL 示例:
复制
http://example.com/#/home http://example.com/#/about
-
原理:
- 使用
window.location.hash
来模拟路由。 #
后面的部分不会被发送到服务器,因此不需要服务器额外配置。
- 使用
-
优点:
- 兼容性好,支持所有浏览器(包括低版本浏览器)。
- 不需要服务器额外配置,适合静态部署。
-
缺点:
- URL 中带有
#
,不够美观。 - 对 SEO 不友好,因为搜索引擎通常不会解析
#
后面的内容。
- URL 中带有
2. History 模式
History 模式使用 HTML5 History API(pushState
和 replaceState
)来实现路由,URL 中不再包含 #
。
特点
-
URL 示例:
复制
http://example.com/home http://example.com/about
-
原理:
- 使用
history.pushState
和history.replaceState
来操作浏览器的历史记录。 - URL 看起来更自然,类似于传统的多页应用。
- 使用
-
优点:
- URL 更美观,没有
#
。 - 对 SEO 更友好,因为搜索引擎可以正确解析 URL。
- URL 更美观,没有
-
缺点:
- 需要服务器额外配置,确保在直接访问或刷新页面时返回
index.html
。 - 兼容性较差,不支持 IE9 及以下浏览器。
- 需要服务器额外配置,确保在直接访问或刷新页面时返回
3. 核心区别对比
特性 | Hash 模式 | History 模式 |
---|---|---|
URL 表现形式 | 带有 # ,如 http://example.com/#/home | 无 # ,如 http://example.com/home |
服务器配置 | 不需要额外配置 | 需要配置支持,确保返回 index.html |
兼容性 | 支持所有浏览器 | 不支持 IE9 及以下浏览器 |
SEO 友好性 | 不友好,搜索引擎不解析 # 后的内容 | 友好,搜索引擎可以解析完整 URL |
实现原理 | 使用 window.location.hash | 使用 HTML5 History API |
4、部署时 Hash 模式与 History 模式的配置与区别
History 模式需要额外的服务器配置,因此比 Hash 模式稍复杂一些,但它能提供更美观的 URL 和更好的 SEO 支持。
Hash 模式部署
请看文章Vue项目通过Nginx部署到云服务器-Docker版的前端部分。
History 模式部署
History 模式相比 Hash 模式,多了一步配置 nginx.conf 文件的步骤。
以下是具体的nginx.conf
配置。创建配置文件将下面的内容粘贴进去,无需任何的修改。
# 全局配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
# 事件模块配置
events {
worker_connections 1024;
}
# HTTP 模块配置
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
# 定义一个 server 块
server {
listen 80;
server_name localhost;
# 根目录,指向 Vue 打包后的 dist 目录
root /usr/share/nginx/html;
index index.html;
location / {
# 尝试查找文件,如果不存在则重定向到 index.html
try_files $uri $uri/ /index.html;
}
# 可选:配置静态资源缓存
location /assets {
expires 1y;
add_header Cache-Control "public";
}
# 可选:配置 404 页面
error_page 404 /404.html;
location = /404.html {
internal;
}
# 可选:配置 50x 错误页面
error_page 500 502 503 504 /50x.html;
location = /50x.html {
internal;
}
}
}
挂载 nginx.conf 配置文件并启动 Nginx 容器。(注意修改配置文件和dist的路径
)
docker run -d --name nginx-container \
-p 8080:80 \
-v /path/to/your/nginx.conf:/etc/nginx/nginx.conf \
-v /path/to/your/dist:/usr/share/nginx/html \
nginx
5、总结
- Hash 模式:
- 使用 URL 的
#
部分实现路由,兼容性好,无需服务器额外配置,适合静态部署。 - 缺点是 URL 不够美观,且对 SEO 不友好。
- 使用 URL 的
- History 模式:
- 使用 HTML5 History API 实现路由,URL 更美观,对 SEO 更友好。
- 需要服务器额外配置(如 Nginx 的
try_files
指令),以确保直接访问或刷新页面时返回index.html
。
- 核心区别对比:
- Hash 模式简单易用,适合兼容性要求高的场景;History 模式 URL 更自然,适合对 SEO 和用户体验要求高的项目。
- 部署配置:
- Hash 模式:直接部署,无需额外配置。
- History 模式:需配置服务器(如 Nginx),确保所有路由请求返回
index.html
。
本文为开发者提供了两种模式的选择依据和具体部署指南,帮助优化 Vue 项目的路由设计与服务器配置。