How can I use in .htaccess?

前端 未结 3 953
闹比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?
    :)

    0 讨论(0)
  • 2021-01-17 04:15

    .htaccess isn't meant to perform url rewriting like you mention. If your server is running apache try this. If your server is running IIS try this.

    As for the second question, if the id doesn't exist, have game.php perform a redirect to a pagename you know does not exist (like 9123912.html). The server should be configured to deliver the 404 natively then.

    0 讨论(0)
  • 2021-01-17 04:16

    Probably the best way is to redirect page to correct url like code below:(work for me)

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

    and in .htaccess file you can also set RewriteBase to somethings like RewriteBase / or RewriteBase /YOUR_SCRIPT_PATH_WITHOUT_HOST_NAME/

    also see Apache Doc

    0 讨论(0)
提交回复
热议问题