Mode rewrite | October 22nd, 2020
See how to use .htaccess and mod_rewrite to easily transform ugly PHP URLs into search engine friendly ones.
The coming together of PHP and MySQL to create dynamic pages is a wonderful thing. Instead of having hundreds of separate webpages, your entire site can be stored inside a MySQL database, and then retrieved and displayed using a handful of “template” PHP pages. This makes updating the site extremely easy, though the draw back is often that the resulting URLs for the pages aren’t very search engine friendly. For example:
The “?” and “&” characters within the URL will stump many search engines, even Google, from crawling the page. What we want instead is something like:
which makes the URL appear just like any normal directory structure, with which all search engines have no qualms about. So how do we go about transforming the parameters portion of a dynamic URL into such a setup instead? Here are the simple steps:
Step 1: Rename your template PHP page, such as “articles.php”, as “articles” instead, without any extension. We want to use this page instead to act as our new templates page.
Step 2: Herein lies the key to creating search engine friendly URLs- configuring Apache to interpret a particular file without extension as a normal PHP page instead. In this case, we want Apache to treat “articles” as if it were a PHP page. In your .htaccess file, add the below code inside it:
Notice how the word “articles” appear within the tag. By adding the above code to your site’s .htaccess file, it informs Apache to interpret “articles” as a PHP page. You can add additional files for Apache to treat as PHP pages by duplicating the above multiple times.
Step 3: With “articles” now being synomonous to “articles.php”, all that’s left is writing code within “articles” to identify the parameters portion of our new URL format, and store them as variables for further processing. As a reminder, our new working URL looks like:
What we want is to create code that detects the “3″ and “0″ portion of the URL, as they are the parameters. Within “articles”, you could do the following:
//split the URL into parts using "/" as the delimiter: $urlarray=explode("/", $REQUEST_URI); //Contains "3", or the ID of the article to display: $articleID=$urlarray; //Contains "0", or the page number of the article in question: $pageNum=$urlarray;
We now have two variables that contain the two parameters embedded inside our search engine friendly URL, which we can then pass into a MySQL query to display the corresponding article and page number. For example:
$getarticle=mysql_query("SELECT thearticle FROM articletable WHERE id=$articleID AND page=$pageNum"); echo mysql_result($getarticle, 0); //displays article
And there you have it. As mentioned, the key to creating search engine friendly URLs in PHP and MySQL is in fact via Apache’s .htaccess file.