RewriteRule工作但丑陋的URL显示而不是漂亮的

时间:2012-04-29 12:38:34

标签: php apache .htaccess mod-rewrite

这是我的.htaccess文件:

RewriteEngine on

RewriteBase /admin

RewriteRule menu/([0-9]+)/([0-9]+)/([a-z0-9]+) http://www.mysite.com/admin/index.php?m=$1&o=$2&token=$3 [R,L]

我必须包含完整的网址,因为没有它,它会一直重定向到http://www.mysite.com/menu/1/1/login.php而不是mysite.com/admin/login.php

所以我重写了我的链接,所以它们看起来像这样:

<a href="/admin/menu/1/1/bl4h1234">Some link</a>

这样可行,但URL在地址栏中显示为丑陋的URL,但整个目的是将URL显示为漂亮的URL:/

我该如何解决?

3 个答案:

答案 0 :(得分:1)

您正通过[R]重定向到新网址。相反,从重写中删除协议和域并丢失[R]。这将执行内部重写。

RewriteRule menu/([0-9]+)/([0-9]+)/([a-z0-9]+) index.php?m=$1&o=$2&token=$3 [L]

答案 1 :(得分:1)

另一种(&amp; standard [MVC / Front controller Patterns])处理mod_rewrite规则和重写的方法是将整个url传递给index.php,然后在那里处理它。

从长远来看,它实际上使它变得更简单,否则只有在添加更多功能时,问题的复杂性才会增加。

由于您似乎在每个文件夹(menu|admin)中都使用 index.php ,因此您没有任何路由器脚本。 因此,您需要处理.htaccess中的基本路线。你基本上只需要为每个文件夹重写一次。

.htaccess在你的根目录中。否则,您需要为每个文件夹重写并且不需要RewriteBase / path

目录结构(.htaccess放在root中的位置):

ROOT>/
     /index.php
     /.htaccess
     /admin/
           /index.php
     /menu/
          /index.php
     /someOtherFolder/
                     /index.php
                     /somefile.php

.htaccess重写

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^admin/menu/(.*)$ admin/index.php?route=$1 [L,QSA]
RewriteRule ^menu/(.*)$ index.php?route=$1 [L,QSA]

然后在index.php文件中,通过$_GET['route']

爆炸/参数来处理路径
<?php 
if(isset($_GET['route'])){
    $url = explode('/',$_GET['route']);
    //Assign your variables, or whatever you name them
    $m     = $url[0];
    $o     = $url[1];
    $token = $url[2];
}else{
    $m     = null;
    $o     = null;
    $token = null;
}
?>

希望它有所帮助。

答案 2 :(得分:0)

  1. 不要将重写创建为绝对URL。删除协议 以及重写URL的主机名。
  2. 如果您不想重定向,请不要使用R标志。
相关问题