How can I use in .htaccess?

前端 未结 3 954
闹比i
闹比i 2021-01-17 03:23

I want to change from this address:

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

to somthing like that:

www.domain.com/game/1/THE-NAME-OF-T         


        
3条回答
  •  一生所求
    2021-01-17 04:10

    .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'];
    

    this is a code, that works for me but considered to be a pseudo-code to give you an idea.
    dbgetrow() function to get a row from the database
    and seo_title() function could be like this one

    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;
    }
    

    The whole concept has been pinched from SO :)
    the only games/1/ part is really important while the rest can be anything, game title is just for seo purpose. Take this question title for example:
    How can I use in .htaccess?
    :)

提交回复
热议问题