【问题标题】:URL rewrite using mod_rewrite in .htaccess在 .htaccess 中使用 mod_rewrite 重写 URL
【发布时间】:2009-05-20 08:02:10
【问题描述】:

我正在尝试使用 mod_rewrite apache 模块重写 URL。 我正在尝试如下使用它:

Options +FollowSymlinks
RewriteEngine on
RewriteBase /
RewriteRule ^wants/testing.htm wants.php?wantid=$1 [L]

我在访问文件的目录中创建了一个 .htaccess 文件。

mod_rewrite 也已启用。 完成所有这些后,我仍然无法使其正常工作。

有人可以帮我解决这个问题吗?如果我遗漏了什么,请告诉我

提前致谢, 格纳什

【问题讨论】:

  • 究竟是什么不适合你?您希望如何重写 URL,您希望从哪里提取 wantid 参数?
  • URL 显示 mydomain.com/wants.php?wantid=123。我需要让它看起来像 mydomain.com/wants/123
  • $1 是对 $_GET 参数的引用,希望在 URL 中。如果我不够清楚,请告诉我。我是 URL 重写的新手

标签: .htaccess mod-rewrite url-rewriting


【解决方案1】:

根据 OP 的评论:

网址显示 mydomain.com/wants.php?wantid=123。一世 需要让它看起来像 mydomain.com/wants/123

这应该适用于您的情况:

RewriteEngine on
RewriteBase /
RewriteRule ^wants/([0-9]+)$ /wants.php?wantid=$1 [L]

它将允许您使用 http://yoursite.com/wants/123 并将其默默地重写为 wants.php?wantid=123

【讨论】:

    【解决方案2】:

    我认为前导斜线(或者更确切地说是缺少斜线)可能是你的问题:

    Options +FollowSymlinks
    RewriteEngine on
    RewriteBase /
    RewriteRule ^wants/testing.htm /wants.php?wantid=$1 [L]
    

    否则 Apache 可能会在 /wants/wants.php 中查找 PHP 文件,因为它会将其视为相对 URL。

    【讨论】:

    • ^/wants/testing.htm /wants.php?wantid=$1 [L]
    • @SpliFF 不,这是针对 .conf 文件而不是 .htaccess
    【解决方案3】:

    嗯,所以我想了一下,我想你可以做这样的事情(如果我理解正确,只根据你的评论更改正则表达式):

    Options +FollowSymlinks
    RewriteEngine on
    RewriteBase /
    RewriteRule ^wants/\d+$ /wants.php?wantid=$1 [L]
    

    但我想您也可以省略 $1 引用,并且仍然可以访问您的 wants.php 中的 id。所以

    RewriteRule ^wants/\d+$ /wants.php [L]
    

    应该也可以,然后你可以使用类似的东西

    <?php 
        $request = split('/', $_SERVER["REQUEST_URI"])[1];
    ?>
    

    在您的 wants.php 中,数组的最后一个元素将是您的 id(或您决定重写并发送到脚本的任何其他内容)。

    【讨论】:

      【解决方案4】:

      如果您想在 wants 目录中的 .htaccess 文件中使用规则,则必须从模式的开头剥离上下文 wants/。所以只是:

      RewriteEngine on
      RewriteRule ^([0-9]+)$ /wants.php?wantid=$1 [L]
      

      否则,如果你想使用根目录下.htaccess文件中的规则:

      RewriteEngine on
      RewriteRule ^wants/([0-9]+)$ wants.php?wantid=$1 [L]
      

      【讨论】:

        猜你喜欢
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-14
        • 2013-03-29
        • 2021-04-27
        • 1970-01-01
        • 2015-02-14
        相关资源
        最近更新 更多