【问题标题】:.htaccess url rewriting is working but not the redirection.htaccess url 重写有效,但重定向无效
【发布时间】:2017-05-08 13:48:43
【问题描述】:

我正在使用 html/php 应用程序上的本地服务器,我正在尝试使用 Apache url 重写模块但没​​有成功

应用程序存储在./Compta/index.php。我必须在./Compta/.htaccess 中创建一个.htaccess 文件

我只想使用重写后的网址,例如:http://localhost/Compta/Test/

而不是:http://localhost/Compta/index.php?page=test

如果用户尝试转到旧网址,则重定向用户

.htaccess 文件包含:

Options +FollowSymlinks

RewriteEngine on

RewriteRule ^([[:alnum:]]*)/$   /Compta/index.php?page=$1 [L]

RewriteRule ^([[:alnum:]]*)$   /Compta/index.php?page=$1 [L]

RewriteCond %{REQUEST_URI}  ^/index\.php$
RewriteCond %{QUERY_STRING} ^page=([[:alnum:]]*)$
RewriteRule ^(.*)$ http://localhost/Compta/%1/ [L,R=301]

当我转到 http://localhost/Compta/Test/ 时,以下行正在工作,我的代码在 div 中包含 test.php 的内容:

RewriteRule ^([[:alnum:]]*)/$   /Compta/index.php?page=$1 [L]

当我转到 http://localhost/Compta/Test 时,以下行正在运行,但在 Firefox 中,url 被重写为 http://localhost/Compta/index.php?page=Test,而 http://localhost/Compta/Test2 不会发生这种情况; url 没有被重写。

RewriteRule ^([[:alnum:]]*)$   /Compta/index.php?page=$1 [L]

为了解决这个问题并重定向旧网址,我添加了以下几行:

RewriteCond %{REQUEST_URI}  ^/index\.php$
RewriteCond %{QUERY_STRING} ^page=([[:alnum:]]*)$
RewriteRule ^(.*)$ http://localhost/Compta/%1/ [L,R=301]

但这不起作用,当我转到 http://localhost/Compta/index.php?page=Test 时,网址不会重写为 http://localhost/Compta/Test/

提前谢谢你

【问题讨论】:

    标签: apache .htaccess redirect mod-rewrite mod-alias


    【解决方案1】:

    我没有找到 .htaccess 的解决方案,但我找到了一个 php 的解决方案,所以我在我的 php 文件顶部添加了以下几行:

            if(preg_match("/\/Compta\/index\.php\?page=([[:alnum:]]*)/",@$_SERVER['REQUEST_URI'],$page)&&!empty($page[1]))
            {
                $new_url = "/Compta/";
                switch (strtolower($page[1])) {
                    case "test":
                        $new_url = $new_url."Test/";
                        break;
                    case "test2":
                        $new_url = $new_url."Test2/";
                        break;
                    default:break;
                }
                header("Status: 301 Moved Permanently", false, 301); 
                header("Location: ".$new_url);
                exit;
            }
    

    我测试 url 是否以 "/Compta/index.php?page=" 开头并且是否有 "page" 的参数 然后我初始化包含新网址的变量 切换我的参数内容我修改新的url 然后我重定向到我的新网址:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      相关资源
      最近更新 更多