Converting GET vars from PHP to friendly urls?
I am facing a very common problem, I need to convert site.com/page.php?id=1&title=page-title to site.com/page-title-id
I thought it could be done easily by adding some mod_rewrite to the .htaccess file, but I feel this is not the most SEO-friendly approach you think?
Another way would be to make some changes to the PHP code, but I am relatively new to this language and I do not know about all the libraries and functions that come with PHP and may make my life easier.
So far, what I am doing (which is not working) in my .htaccess is:
# 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 think a solution in PHP would be much better because I don't want the search engines to think that I am masking the site or redirecting or whatever, just want the url to be like site.com/page- title- id or similar.
EDIT: Tried a different approach in .htaccess
source to share
I need to convert my site.com/page.php?id=1&title=page-title to site.com/page-title-id
You can replace the current htaccess code with this one (assuming it's in the 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 the old url format ( http://example.com/page.php?id=1&title=page-title ) to the new format ( http://example.com/page-title-1 ) and then internally rewrite the new format back to the old format (no endless loop)
source to share