js如何实现伪静态
使用 URL 重写实现伪静态
在 JavaScript 中实现伪静态通常需要结合服务器端配置(如 Apache 或 Nginx)和前端路由库(如 Vue Router 或 React Router)。以下是常见方法:
配置服务器重写规则(以 Apache 为例)
在 .htaccess 文件中添加规则,将动态 URL 重写为静态形式:
RewriteEngine On
RewriteRule ^article/([0-9]+)/?$ article.php?id=$1 [L]
前端路由库处理(以 React Router 为例)
使用 react-router-dom 定义路由规则:

import { BrowserRouter as Router, Route } from 'react-router-dom';
<Router>
<Route path="/article/:id" component={ArticlePage} />
</Router>
使用 History API 实现无刷新跳转
通过 history.pushState() 修改浏览器地址栏而不刷新页面:
window.history.pushState({}, '', '/article/123');
动态路由参数解析
在单页应用(SPA)中获取伪静态 URL 的参数:
// React Router 获取参数
const { id } = useParams();
// 原生 JavaScript 获取路径参数
const pathParams = window.location.pathname.split('/')[2];
服务端渲染(SSR)方案
使用 Next.js 等框架实现服务端伪静态路由:

// pages/article/[id].js
export async function getServerSideProps(context) {
const { id } = context.params;
return { props: { id } };
}
Nginx 服务器配置示例
在 Nginx 配置中添加重写规则:
location /article/ {
rewrite ^/article/(\d+)$ /article.php?id=$1 last;
}
注意事项
确保服务器已启用 URL 重写模块(如 Apache 的 mod_rewrite)
伪静态 URL 应保持语义化,如 /article/123 比 ?id=123 更友好
对于 SEO 敏感场景,建议配合服务端渲染或静态站点生成(SSG)方案






