Custom SEF URLS With HTACCESS


.HTACCESS Custom Rewrite Rules

When you use an .htaccess file within a root or other directory, you can set rules to write search engine friendly urls. For example, you may have a dynamic url like example.com/blog/id=100&title=mytitle. With a little work, you could make a rule so that an address in the browser such as example.com/blog/100-mytitle. When you make rewrite rules with htaccess, the original url and the new sef url will display the same content.

In order to make rules for htaccess usable, mod_rewrite must be installed and enabled on the server. It is often installed and enabled for shared hosting and can simply be enabled with a VPS or dedicated server.

HTACCESS RULES and CODE

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^blog/([^/]+)/([^/]+)$ blog/blog\.php?id=$1&title=$2 [NC]
#RewriteRule ^([^/]+)-([^/]+).html$ blog/blog\.php?id=$1&title=$2 [NC]
#RewriteRule ^(.+)-(.+).html$ blog/blog\.php?id=$1&title=$2 [NC]
RewriteRule ^(.*)-(.*).html$ blog/blog\.php?id=$1&title=$2 [NC]
</IfModule>

What Does the above code do?

The above code gives you the option to take the url example.com/blog/id=100&title=mytitle and be able to use it as example.com/blog/100-mytitle.html

The key code is RewriteRule. All rules with the comment '#' in front are inactive. The line that does the rewriting is:
RewriteRule ^(.*)-(.*).html$ blog/blog\.php?id=$1&title=$2 [NC]

Code Usage Example

Rewriting a url is one thing and is simple to use if we just link to the new sef url. However, if you have code that uses $_GET variables in the string you need to rewrite the php code so that it will point to the sef url. Here is an example of that.

Original code that will produce non-sef url like example.com/blog/id=100&title=mytitle

<div style="font-size:18px; margin-left:5px; display:none;"><a href="blog.php?id=<?php echo htmlentities(stripslashes($row['bookmark_id'])); ?>&title=<?php echo htmlentities(stripslashes($row['title'])); ?>"><?
   echo htmlentities(stripslashes($row['title'])).'</a></div>';?>
  
New Code to rewrite SEF URLS that will make sef url like example.com/blog/100-mytitle.html
     <div style="font-size:18px; margin-left:5px;"><a href="<?php echo htmlentities(stripslashes($row['bookmark_id']))."-".htmlentities(stripslashes($row['title'])).".html"; ?>"><?
   echo htmlentities(stripslashes($row['title'])).'</a></div>';?>