我如何在.htaccess中使用?

时间:2010-08-09 11:15:36

标签: php

我想改变这个地址:

www.domain.com/game.php?id=1

这样的事情:

www.domain.com/game/1/THE-NAME-OF-THE-GAME-IN-DB

我该怎么做?

还有一个问题:

我希望当用户转到不存在的地址时,例如,如果它不存在:

www.domain.com/game.php?id=9123912 - this ID doesnt exists

服务器会将他传递给404错误。我该怎么办?

非常感谢。

修改

game.php:

if (isset($_GET['id'])) {

    $row = mysql_num_rows(mysql_query("SELECT * FROM games WHERE id = '{$_GET['id']}'"));

    if ($row) {
        $game = mysql_fetch_array(mysql_query("SELECT * FROM games WHERE id = '{$_GET['id']}'"));
        Header( "HTTP/1.1 301 Moved Permanently" ); 
        Header( "Location: /game/".$game['id']."/".seo_title($game['name'])); 
    } 

    else {
        Header( "HTTP/1.1 404 Not found" ); 
    }

    exit;
}

htaccess的:

LIKE YOU SAID. I JUST COPIED.

3 个答案:

答案 0 :(得分:4)

的.htaccess

RewriteEngine On
RewriteRule ^game/([0-9]+)/ /game.php?newid=$1

game.php

if (isset($_GET['id'])) {
  $row = dbgetrow("SELECT * FROM games WHERE id = %s",$_GET['id']);
  if ($row) {
    Header( "HTTP/1.1 301 Moved Permanently" ); 
    Header( "Location: /game/".$row['id']."/".seo_title($row['name'])); 
  } else {
    Header( "HTTP/1.1 404 Not found" ); 
  }
  exit;
}

if (isset($_GET['newid'])) $_GET['id'] = $_GET['newid'];

这是一个代码,对我有用,但被认为是一个伪代码,可以给你一个想法 dbgetrow()函数从数据库中获取一行
和seo_title()函数可能就像这个

function seo_title($s) {
    $s = strtolower(trim($s));
    $s = str_replace(" ","-",$s);
    $s = preg_replace('![^a-z0-9-]!',"",$s);
    $s = preg_replace('!\-+!',"-",$s);
    return $s;
}

整个概念都是从SO :)中捏出来的 唯一的games/1/部分非常重要,其余部分可以是任何东西,游戏标题仅用于seo目的。以这个问题标题为例:
How can I use in .htaccess?
:)

答案 1 :(得分:0)

.htaccess并不意味着像你提到的那样执行url重写。如果您的服务器正在运行apache,请尝试this。如果您的服务器正在运行IIS,请尝试this

至于第二个问题,如果id不存在,请让game.php执行重定向到您知道不存在的页面名称(如9123912.html)。应将服务器配置为本机传送404。

答案 2 :(得分:0)

可能最好的方法是将网页重定向到正确的网址,如下面的代码:(为我工作)

RewriteBase

并在.htaccess文件中,您还可以将RewriteBase /设置为RewriteBase /YOUR_SCRIPT_PATH_WITHOUT_HOST_NAME/ <TextView android:id="@+id/mywidget" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:singleLine="true" android:textColor="#2086CA" android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." android:textAppearance="?android:attr/textAppearanceSmall" />

等事情

另见Apache Doc