article

Saturday, June 2, 2012

URL Mod_Rewrite PHP and htaccess

URL Mod_Rewrite PHP and htaccess

Download


#.htaccess
RewriteEngine On

# Check if the file or directory actually exists - if it does we dont want to redirect
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Pass the rewritten URL onto index.php with a $_GET['url'] parameter
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
//index.php
<?php
$incommingURL = (isset($_GET['url']) ? $_GET['url'] : '');
 $url = array();
 // Split apart the URL String on the forward slashes.
 $url = explode('/', $incommingURL);
 switch($url[0]) {
  case 'home':
   include_once('home.php');
   break;
  case 'news':
   include_once('news.php');
   break;
  default:
   include_once('home.php');
   break;
 }
?>
//news.php
<h1>News</h1>
<a href="http://localhost/mod_rewrite/home/">http://localhost/mod_rewrite/home</a>

<h3>News Pages</h3>
<a href="http://localhost/mod_rewrite/news/page-1/">http://localhost/mod_rewrite/news/page-1</a><br>
<a href="http://localhost/mod_rewrite/news/page-2/">http://localhost/mod_rewrite/news/page-2</a><br>
<a href="http://localhost/mod_rewrite/news/page-3/">http://localhost/mod_rewrite/news/page-3</a>

<?php
 $pageNumber = (isset($url[1]) ? $url[1] : 'page-1');
 $page = explode('-', $pageNumber);
 echo '<h4>Page: '.$page[1].'</h4>';
?>

Related Post