vue实现伪静态
Vue 实现伪静态的方法
Vue 项目通常采用前端路由(如 vue-router),但默认情况下路由模式是哈希模式(如 #/home)。要实现伪静态(无 # 的 URL),可以使用 history 模式,并结合服务器配置实现。
启用 history 模式
在 vue-router 配置中,将 mode 设置为 'history':
const router = new VueRouter({
mode: 'history',
routes: [...]
})
这样 URL 会变为 example.com/home 的形式,但需服务器支持。
服务器配置
伪静态需服务器将所有请求重定向到 index.html,由前端路由处理。以下是常见服务器的配置示例:
Nginx 配置
location / {
try_files $uri $uri/ /index.html;
}
Apache 配置
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Node.js (Express) 配置
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
静态资源路径处理
在 vue.config.js 中设置 publicPath 为相对路径(避免静态资源加载问题):
module.exports = {
publicPath: './'
}
注意事项
- SEO 优化:伪静态 URL 对 SEO 更友好,但需配合服务端渲染(SSR)或预渲染(如
prerender-spa-plugin)解决爬虫抓取问题。 - 404 处理:需在 Vue 中自定义 404 页面,因为服务器会将所有路径指向
index.html。 - 后端协作:若接口与前端路由冲突,需后端配合调整接口路径。







