如何通过JS和PHP实现SEO友好的博客文章链接?
解决URL路由问题:实现
website.com/blog/title-name格式链接 你的核心问题是现有路由架构通过index.php统一处理所有请求,之前添加的RewriteRule直接指向blog.php与该架构冲突,导致规则未生效。以下是完整修复步骤:
1. 修正.htaccess规则
将新增规则调整为转发到index.php,并放在原有规则之前,确保优先匹配博客文章路径:
RewriteEngine On RewriteBase / # 匹配/blog/xxx格式请求,转发到index.php并传递title参数 RewriteRule ^blog/([^/]+)$ index.php?post_title=$1 [L,QSA] # 原有规则:处理非文件/目录的其他请求 RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+)$ index.php [QSA,L]
2. 更新index.php路由逻辑
在switch语句外添加正则匹配,处理/blog/xxx格式的请求,提取文章标题并加载post.php内容:
<?php $request = $_SERVER['REQUEST_URI']; // 处理单篇博客文章请求 if (preg_match('/^\/blog\/([^\/]+)$/', $request, $matches)) { $postTitle = urldecode($matches[1]); $title = "Blog Post: " . $postTitle; // 通过include传递变量给post.php,替代file_get_contents ob_start(); include __DIR__ . '/views/post.php'; $content = ob_get_clean(); $active_page = 'blog'; } else { switch ($request) { case "/" : case "" : $title = "Home Page"; $content = file_get_contents(__DIR__ . '/views/index.php'); $active_page ='home'; break; case "/blog" : $title = "Blog Page"; $content = file_get_contents(__DIR__ . '/views/blog.php'); $active_page ='blog'; break; case "/contact" : $title = "Contact Page"; $content = file_get_contents(__DIR__ . '/views/contact.php'); $active_page ='contact'; break; default: $title = "404 - Not found"; http_response_code(404); $content = file_get_contents(__DIR__ . '/views/404.php'); break; } } ?>
3. 修正blog.js的链接(确保编码特殊字符)
对文章标题进行URL编码,避免特殊字符破坏路径:
// linking blog container const titleLink = document.createElement("a"); titleLink.href = `/blog/${encodeURIComponent(blogPost.title)}`;
4. 更新post.php的参数获取
推荐直接使用服务器端传递的变量,替代前端解析URL参数:
<?php // 直接使用index.php传递的$postTitle变量 echo "<h1>" . htmlspecialchars($postTitle) . "</h1>"; ?>
如果仍需前端获取标题,可解析URL路径:
const pathParts = window.location.pathname.split('/'); const postTitle = decodeURIComponent(pathParts[2]);
失效原因说明
你之前添加的RewriteRule直接转发到blog.php,但现有架构要求所有请求通过index.php路由,该规则被后续的RewriteRule ^(.+)$ index.php覆盖;同时blog.php未纳入现有布局加载流程,导致页面无法正常渲染。
内容的提问来源于stack exchange,提问作者Kirilas
相关产品推荐
相关产品推荐

