【问题标题】:mod_rewriting with name from databasemod_rewriting 使用数据库中的名称
【发布时间】:2014-01-24 16:03:17
【问题描述】:

我有一个 URL 格式的页面:

www.site.com/events/event.php?id=1&cat_id=4

我想改写成对 SEO 更友好的东西,即

www.site.com/events/name-of-event

(我的 URL 中不需要类别名称,仅用于页面创建动态面包屑链接)。

我的 MySQL 数据库中有事件名称,我想在 URL 中使用它。我试图调整this answer 中的代码,但没有成功。有人可以帮忙吗?

编辑:

RewriteRule ^events/([^/]+)$ event.php?event_name=$1 [L,QSA] 这是我最初尝试的(cat_id 对于 URL 不是必需的,因为页面会检查并检索默认值,如果没有通过)。

【问题讨论】:

  • 你是如何适应它的?什么不起作用?
  • @IgnacioVazquez-Abrams 是吗?考虑到这个问题显然没有很好的答案,也许有人可能会对这个新问题有一个答案......
  • @FDL 更新问题
  • 这家伙在做什么? moz.com/ugc/… 还是这个人? stackoverflow.com/a/21218043/3181236
  • 什么不起作用?你的规则看起来不错。您有 event.php 使用事件名称从数据库中提取正确的事件吗?你打开了 mod_rewrite 吗?

标签: php apache .htaccess mod-rewrite


【解决方案1】:

为了向后兼容,您可能希望将events/event.php?id=123 重定向到新的events/event_name url。问题是,正如您在链接答案中所说的那样,没有真正的方法可以通过 Apache 连接到数据库,因此您必须在文件本身中处理重定向/翻译。

规则本身必须如下所示:

RewriteRule ^events/([^/]+)/?$ /events/event.php?event_name=$1 [L,QSA]

然后,在您的 event.php 中,您将执行以下操作:

#This is the top line of your file.
if( isset( $_GET['id'] ) ) {
  $id = intval( $_GET['id'], 10 );
  $event_name = do_database_query_NOAW( $id );
  header( 'HTTP/1.1 301 Moved Permanently' );
  header( 'Location: /events/' . $event_name );
  exit();
}

#code that now uses (the sanitized) event name instead of the sanitized id
if( !isset( $_GET['event_name'] ) || !preg_match( '/[A-Za-z0-9-]+/', $_GET['event_name'] ) ) {
  header( 'HTTP/1.1 400 Bad Request' );
  exit();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-07
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2020-03-14
    • 2018-10-24
    相关资源
    最近更新 更多