Dipesh KC
Dipesh KC

Reputation: 3317

auto redirect to clean urls

how can i auto redirect a site from dirty url to clean url in php , something like

http://www.mysite.com?page=page1&action=action1

to

http://www.mysite.com/page1/action1

Upvotes: 2

Views: 1859

Answers (3)

Treffynnon
Treffynnon

Reputation: 21563

If you are running Apache you can use the mod_rewrite module and set the rules in a .htaccess file in your httpdocs folders or web root. I don't see any reason to invoke a PHP process to do redirection when lower level components will do the job far better.

An example from Simon Carletti:

RewriteEngine On
RewriteCond %{REQUEST_URI}  ^/page\.php$
RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^(.*)$ http://mydomain.site/page/%1.pdf [R=302,L]

Upvotes: 3

Your Common Sense
Your Common Sense

Reputation: 157981

You have to check if it was clean request or not. Otherwise you will fall into infinite loop

Here is an example from one of my projects:

.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'];

So, you have to verify, if it was direct "dirty" call or rewritten one.
And then redirect only if former one.
You need some code to build clean url too.

And it is also very important to show 404 instead of redirect in case url is wrong.

Upvotes: 5

Fender
Fender

Reputation: 3055

try

header("Location: http://www.mysite.com/".$_GET['page']."/".$_GET['action']);

you should check whether the values are set before trying to redirect

Upvotes: 2

Related Questions