Galactic Civilizations 3
Redirection mechanism for the url rewriting

Redirection mechanism for the url rewriting

Category: Php.
Posted by on the 22/12/2013.
Last update on the 23/12/2013.

<<Previous tutorial 


This tutorial explains how to put in place the redirection to the good file after the url rewriting and the url schema definition.


This tutorial is intended for people under Linux that use apache2 server as webserver. In this tutorial we consider that the root folder of your website is /var/www/tutorielsenfolie. Furthermore, all commands in this tutorial are executed as root. (su command).


Now we will forward the request to the good file if the url asked by the user exists. If it is not the case we redirect the user to an error page.

To do that, execute the following command:

nano /var/www/tutorielsenfolie/router.php

We will now write the file router.php.


// We open the XML file.
$dom = new DOMDocument;

// By default we redirect to the error page.
$page = dirname(__FILE__).'/404.php';
foreach($dom->getElementsByTagName('route') as $route) {
if(preg_match('`^'.$route->getAttribute('url').'$`', $_SERVER['REQUEST_URI'], $matches)){
   // If there is a correspondance between the regular expression and the url requestion by the user.
   // We retrieve the name of the file to display.
   $page = $route->getAttribute('file');
      // If there are variables, we retrieve it.
      $vars = explode(',', $route->getAttribute('vars'));   
      foreach($matches as $cle => $valeur){
         if($cle !== 0) $_GET[$vars[$cle - 1]] = $valeur;
// We display the page.
require $page;

Test of the redirection

We can test the redirection. To do that, open a browser and go to the following urls:

  • « http://localhost/tutorielsenfolie/»
  • « http://localhost/tutorielsenfolie/articles-9.html»
  • « http://localhost/tutorielsenfolie/test.html»

The following messages should appear:

URL rewriting: homepage

URL rewriting: articles

URL rewriting: error

You like this tutorial ?
Like this website in order to promote it on facebook !

<<Previous tutorial 

You like this tutorial ? Share it with your friends !
Partager sur Facebook Partager sur Twitter Partager sur Myspace Partager sur Stumbleupon Soumettre sur Reddit Partager sur Digg Ajouter à vos favoris Technorati Ajouter à vos favoris Live Ajouter à vos favoris Google Ajouter sur vos favoris Yahoo