【问题标题】:.htaccess if URL is bad do something.htaccess 如果 URL 不好做某事
【发布时间】:2013-01-26 19:39:55
【问题描述】:

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

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite redirect


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2014-11-19
    • 2015-09-28
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多