Create SEO friendly URL by Rewriting in Core PHP via .htaccess

Rating: 4.5. From 2 votes.
Please wait...

Hey Friends,

Today PHP HURDLES presents the basic but highly efficient tutorial on how you can rewrite your project URL by using Htaccess file. Htacess do wonders when it comes to extending the functionality of a project without affecting the internal logic or coding part of your website.

Today we will learn how we can create an SEO friendly URL with help of rewrite condition in CORE PHP.

So let’s start by taking various scenarios into the account.

CASE 1: Rewrite simple URL 

Suppose we have an URL http://phphurdles.com/view_portfolio.php and we want to rewrite it to http://phphurdles.com/view-portfolio.php  then you need to implement following code in your .htaccess file to make it working

To make Rewriting work do not forget to turn Rewrite engine ON

1
2
3
RewriteEngine on

RewriteRule ^view-portfolio$ view_portfolio.php

Now just mention view-portfolio.php in your anchor tag and page will get redirected to view_portfolio.php but your URL will become view-portfolio.php.

CASE 2: Rewrite Url having 1 query string

Now, in this case, suppose we have an URL http://phphurdles.com/view_portfolio.php?id=123 and we want it to be http://phphurdles.com/view-portfolio.php/id/123  then we need following code in our  .htaccess file

1
2
3
RewriteEngine on

RewriteRule ^view-portfolio/id/([0-9]+)\.php$ view_portfolio.php?id=$1

 

Now just mention view-portfolio.php/id/$variable in your anchor tag and page will get redirected to view_portfolio.php?id=$variable but your URL will become  view-portfolio.php/id/$variable.

 

CASE 2: Rewrite Url having 2 query string

Now, in this case, suppose we have an URL http://phphurdles.com/view_portfolio.php?id=123&sort=1 and we want it to be http://phphurdles.com/view-portfolio.php/id/123/sort/1  then we need following code in our  .htaccess file

1
2
3
RewriteEngine on

RewriteRule view-portfolio/id/([0-9]+)/sort/([0-9]+)\.php$ view_portfolio.php?id=$1&sort=$1

After this mention  view-portfolio.php/id/$variable1/sort/$variable2 in your anchor tag and page will get redirected toview_portfolio.php?id=$variable1&sort=$variable2 but your URL will become view-portfolio.php/id/$variable1/sort/$variable2.

We hope this small snippet will help you in understanding and implementing the logic behind URL Rewriting in Htacess file in PHP.

If you have any query do write us at help@phphurdles.com.

You can also view some of our trending posts below.

Sending JSON Post Request To Server In PHP

Eliminating Wrong Data Type Issue Using MySQL Typecasting

 

Because we believe Hurdles aren’t really Hurdles.

Cheers!

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *