.htaccess如果URL不好做某事

时间:2013-02-11 16:41:08

标签: regex apache .htaccess mod-rewrite redirect

我正在制作我的个人CMS。我想在其中使用酷(友好)网址。这是我的.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上犯一个错误。至(例如)此网址http://stackoverflow.com/questions/5469955/htaccess-url-rewrite-if-file-not-exists。我添加了.php。但我没有看到404错误。我们的魔术方法论坛删除了我的后记并将我重定向回正确的网站网址。 如何在我的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

1 个答案:

答案 0 :(得分:3)

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

htaccess的:

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

的index.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
?>