更改许多地址(在.htaccess中)

时间:2014-08-10 20:49:12

标签: php html .htaccess web

我有ids表

id   | Name     
1    | abc  
2    | xyz
3    | qwe
...  | ... 
1000 | zxc

我的地址看起来是:http://example.com/rat.php?id=1我希望http://example.com/abc/rat.php我该怎么做,你有什么想法吗?

P.S当然我没有文件夹abc,我只想在web浏览器中更改URL。我会喜欢Rewrite rules,但我不知道它是否对每条记录都有效

2 个答案:

答案 0 :(得分:2)

RewriteEngine on
RewriteBase /
RewriteRule ^(abc)/rat\.php$    rat.php?name=$1 [NC,L,QSA]

或者(我会这样做)

RewriteEngine on
RewriteBase /
RewriteRule ^(abc)/rat$ rat.php?name=$1 [NC,L,QSA]

您的所有链接都可以像这样重写

RewriteEngine on
RewriteBase /
RewriteRule ^([a-zA-Z0-9-]+)/rat$   rat.php?name=$1 [NC,L,QSA]

              ^ this holds all name variations

因此名称可以包含任何小写,大写字母,数字或标记-

如果rat.php不是唯一的文件,您可以像这样修改上面的

RewriteEngine on
RewriteBase /
RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)$ index.php?name=$1&file=$2 [NC,L,QSA]

在你的PHP中(让我们使用我们有两个变量的最后一个例子

// index.php
//
switch(isset($_GET['file']) ? $_GET['file'] : 'default'){
    case 'rat':
      // load the rat.php for instance
      $something = $_GET['name'];
      break;
    case 'tar':
      // load the tar.php
      // ...
      break;
    default:
      // load index/defautl file 
      break;
}

这是完整的逻辑之后。因此,正如我在下面的评论中所说的那样,您不会像使用.htaccess文件那样在Apache中进行任何重定向。

您可以使用.htaccess中的资源ID而不是它的名称;像这样

http://example.com/article/an-article-title/10

使用此规则

RewriteRule ^(article)/([a-zA-Z0-9-]+)/([0-9]+)$ index.php?modul=$1&title=$2&id=$3 [NC,L,QSA]

你知道你需要的模块,在这种情况下的文章,资源的名称(标题)和它的id。

对于永久移动的重定向,请使用[R=301]

答案 1 :(得分:0)

你可能更好地搜索mvc编程,例如php有使用mvc模型的codeigniter框架,但我认为这样算法 1选择id = 1的表 表中的2提取名称列 3 - 将此列值设置为用于url $ sitename的字符串。“/”。$ row ['name']。“/ rat.php”;

我希望对你有所帮助