Problem with URL rewriting using .htaccess based Articles
This small writing is intended only for the beginners. It is not for the coders who have know-how of .htaccess and are experts or advanced programmers.
URL rewriting using .htaccess is very common now-a-days for the programmers who work especially in PHP on linux or unix based Operating systems with Apache as a web server.
.htaccess is a Global Configuration file in Apache. It is not only used to make redirection but it is also used for many other tasks like Stop displaying the directories of the site if there is no Index or start up page, changing the start up page to something else etc. I am not going into detail of it as you can find much about on internet.
Visit Apache rewrite guide for this purpose if you are interested in knowing further about the rewriting.
The only purpose for this small article was to address the issue with the articles for URL rewriting while they are written and published.
They mention in detail about what the rewriting URL is. They gave examples how to use that but they don’t mention about to change URLs in the code. Coders must write and make URLs according to SEO friendly format and then define a rule for them in .htaccess.
They just mention this is URL and see how it will be redirected.
Rewriting product.php?id=12 to product/ipod-nano/12.html
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+).html$ product.php?id=$2
The author has mentioned the URL and showed that how the URL will be redirected seamlessly. Definitely, it will come from the Browsers address bar. But he has not mentioned that this kind of URLs will be made in their programming coding.
Why it is essential because for the beginners it becomes difficult to understand. So whenever such articles must be written, they must start by making the ground.
A coder must think how the URLs will look like before making rules, then he must format the links generated from his code, for instance, make a link for editing the profile of a user according to what he has planned.
It must be generated through the code.
Then one can write a rule in .htaccess like this:
RewriteRule ^profile/([a-zA-Z]+)-([0-9]+)/$ acp/users/options/profile.php?name=$1&idPk=$2
This “acp/users/options/profile.php” is the directory structure where the profile.php is present. Use your own path.
One more thing to be noticed that when you write an SEO friendly URL which has some query string, You must enclose your query string portion with Parenthesis ‘()’ without the single quote. Because it tells the rule that now the subpattern is going to be started. And it assigns the value to the right-hand side’s variables defined as $1, $2 so on.
e.g, in the above rule this part ([a-zA-Z]+) tells the Rule to assign whatsoever is coming at letting to right-hand side’s 1** and this **([0-9]+)/ to $2. Note down the parenthesis.
Syed Murtaza Hussain Kazmi
Senior Software Architect
Efficiency in code is good but that must be reasonable.