Computer's Guy
Computer's Guy

Reputation: 5363

Transform GET vars from PHP into friendly URLs?

I'm running into a very common issue, I need to transform my site.com/page.php?id=1&title=page-title into site.com/page-title-id

I was thinking this could be easily done adding some mod_rewrite in the .htaccess file but I'm feeling it might not be the most SEO-friendly approach there is, what do you think?

Another way would be to make some changes within the PHP code, but I'm relatively new to this language and I don't know about all the libraries and functions that come with PHP and could make my life easier here.

So far, what I'm doing (Which is not working) in my .htaccess:

# BEGIN ocasion_system
<IfModule mod_rewrite.c>
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php\?title=([^&\s]+)&?
RewriteRule (.*)\.php$ /$1/%1/? [L,R=301]

RewriteRule ^([^/]+)/([^/]+)/$ $1.php?title=$2 [QSA,L]
</IfModule>

And my page.php has

//all includes up here..
$page = new Page();
$page->__set('title', $_GET["title"]); //this is how i set up my page interface, please don't laugh

if ($_GET["title"] != NULL){    
        $page = get_page($page, $db);       
        echo '<pre>';
        print_r($page);//works as intended when i access http://localhost/page.php?title=default prints all the Page object with that title.
        echo '</pre>';
    }

I guess a solution in PHP would be much better because I don't want to make search engines think I'm cloaking the site or redirecting or anything, just want the URL to be like site.com/page-title-id or similar.

EDIT: Tried a different approach within the .htaccess

Upvotes: 3

Views: 837

Answers (1)

Justin Iurman
Justin Iurman

Reputation: 19016

I need to transform my site.com/page.php?id=1&title=page-title into site.com/page-title-id

You can replace your current htaccess code by this one (assuming it is located in document root folder)

<IfModule mod_rewrite.c>
  Options +FollowSymLinks -MultiViews

  # Turn mod_rewrite on
  RewriteEngine On
  RewriteBase /

  RewriteCond %{THE_REQUEST} \s/page\.php\?id=([0-9]+)&title=([^\s&]+)\s [NC]
  RewriteRule ^ %2-%1? [R=301,L]

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^([^/]+?)-([0-9]+)$ page.php?id=$2&title=$1 [L]
</IfModule>

This code will redirect old url format (http://example.com/page.php?id=1&title=page-title) to its new format (http://example.com/page-title-1) and will then internally rewrite back new format to old format (without any infinite loop)

Upvotes: 1

Related Questions