3

我正在制作我的个人CMS。我想在其中使用酷(友好)的 URL。这是我的 .htaccess 文件代码:

RewriteEngine on
RewriteBase /
DirectoryIndex index.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([a-zA-Z-_0-9_/]+)/?$ index.php?args=$1 [L]

我看到在 Stack Overflow 上也使用了友好的 URL。今天我试图在 Stack Overflow 上出错。到(例如)这个 URL http://stackoverflow.com/questions/5469955/htaccess-url-rewrite-if-file-not-exists。我补充说.php。但我没有看到 404 错误。我们的论坛以一种神奇的方式删除了我的后记,并将我重定向回正确的站点 URL。我怎样才能在我的 CMS 中做同样的事情

我试图将此 ( RewriteRule ^([a-zA-Z-_0-9_/]+)/?$ index.php?args=$1 [L]) 行更改为 ( RewriteRule ^([a-zA-Z-_0-9_/]+)/([a-zA-Z-_0-9)$ index.php?args=$1 [L]),但这没有帮助,然后我看到了500 Internal Server Error

4

1 回答 1

3

如果您需要与 Stack Overflow 相同的行为,那么您还必须有一些服务器端支持(例如 PHP、ASP 等)。考虑以下代码片段:

.ht 访问:

RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?id=$1&title=$2 [L,NC,QSA]

索引.php:

<?php
   $id    = $_GET['id'];
   $title = $_GET['title'];

   $dbTitle = // Get title from Database query using $id
   ...
   if ($title != $dbTitle) {
      // Redirect with 301 to correct /<id>/<title> page
      header ('HTTP/1.1 301 Moved Permanently');
      header('Location: /' . $id . '/' . $dbTitle);
      exit;
   }
   // The rest of your script
?>
于 2013-02-11T16:53:23.957 回答