How can I use in .htaccess?

I want to change this address:

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

for something like this:

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

How can i do this?

And one more question:

I want when a user is sent to an address that does not exist, for example, if it does not exist:

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

The server will give it a 404 error. How can I do this?

Thank you very much.

EDIT:

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. 
0
source share
3 answers

.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 code that works for me but is considered pseudo code to give you an idea.
Dbgetrow () function to get a row from a database
and the seo_title () function might look like this

 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 was sandwiched from SO :)
the only part of games/1/ really important, and the rest can be anything, the name of the game is for seo purposes only. Take this question title, for example:
How can I use in .htaccess? :)

+4
source

.htaccess is not intended to rewrite URLs as you mention. If apache is running on your server, try this . If your server is running IIS, try this .

As for the second question, if id does not exist, try redirecting game.php to a name that you know does not exist (for example, 9123912.html). The server must be configured to deliver 404 initially.

0
source

Probably the best way is to redirect the page to fix the url like code: (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 the .htaccess file you can also set RewriteBase to something like RewriteBase / or RewriteBase /YOUR_SCRIPT_PATH_WITHOUT_HOST_NAME/

also see Apache Doc

0
source

Source: https://habr.com/ru/post/1385670/


All Articles