0

I am using mod-rewrite to redirect friendly URLs to a php script that looks up the actual URL in an associative array and then redirects with header("location: $url");

My rewrite rule is

RewriteEngine On
RewriteCond %{REQUEST_URI}  "^/$"
RewriteRule ^(.*) http://%{HTTP_HOST}/index.php [L,R=301] 
RewriteCond %{REQUEST_URI} !=/home.php
RewriteCond %{REQUEST_URI} !(\.php|\.html|\.htm|\.png|\.gif|\.css|\.htm|\.js|\.txt|\.xml)$ [NC]
RewriteRule ^([^/]*)$ /home.php?page=$1 [L] 

This results in the $url appearing in the browser's location bar whereas I want the friendly url to appear.

I understand from this post Rewriting URL and making new URL show in location bar why this occurs (because of the php location header) but I don't know how to achieve what I want.

There are a large number of dynamic pages that are built by several internal php scripts and writing mod-rewrite rules for all combinations of script and request parameters would be difficult.

So my questions is, how can I make the friendly url appear in the location bar.

Community
  • 1
  • 1
user1142052
  • 13
  • 2
  • 10
  • See also [Reference: mod\_rewrite, URL rewriting and "pretty links" explained](http://stackoverflow.com/q/20563772) on what RewriteRules are for, rewrite existing html, or how to make ping-pong redirects. – mario Aug 30 '16 at 01:01

2 Answers2

1

In your PHP script instead of redirecting the user using

header("location: $page");

you need to include that page. You'll definitely want to first ensure that the value of $page is an accepted value:

<?php

// /home.php

$page = $_GET['page'];

$valid_pages = array(
    'about',
    'contact',
);

if(in_array($page, $valid_pages)){
   include($page . '.php');
   exit;
}

die('Invalid Page.');
anakadote
  • 322
  • 2
  • 11
0

I've solved it now.

The include doesn't work for me consistently as many of $pages have content of the type '?a=b' .

I solved it with:

if(array_key_exists($page, $pages)){
$page = $pages[$page];
if (strpos($page,'?')) {        
    $html = file_get_contents(<site>.$page);
    echo  $html;
}
else include(<path>.$page);
exit;
}
die('Invalid Page.');

Thanks to Taylor for pointing me in the right direction. I've accepted his answer

user1142052
  • 13
  • 2
  • 10