regex - .htaccess 如果 URL 错误,请执行某些操作

标签 regex apache .htaccess mod-rewrite redirect

我正在制作我的个人 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

最佳答案

如果您需要具有与 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
?>

关于regex - .htaccess 如果 URL 错误,请执行某些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14816625/

相关文章:

php - 使用 htaccess 格式化个人资料网址

c# - 在无序日志文件中搜索

java - 正则表达式匹配超出应有的范围

.htaccess - 301 重定向到带有 HSTS 预加载 header 的 WWW

php - 警告 : mysqli_connect(): php_network_getaddresses: getaddrinfo failed: No such host is known. 但我显然必须在那里主持

java - 使用 Apache Poi 从 Excel 工作簿中删除工作表后,还剩下一个工作表吗?

.htaccess - AllowOverride 安全问题

Java字符串分割返回空结果

Python 正则表达式\W : with vs without parenthesis

node.js - 如何设置 Apache ProxyPass 以保留 Express 路由