Formatting a URL in htaccess
Change the URL format to make beautiful and SEO friendly.
Making your webpages url more readable is more appealing in the eye of your readers. And some says it's good for SEO.
For example, you have this url that access a product page.
https://devjunky.com/product.php?id=143
Ideally, you want to have like this
https://devjunky.com/product/143/ or https://devjunky.com/{ProductName}/
We can do this by adding a bit of codes in the htaccess file.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^product\/(.*?)\/$ product.php?id=$1 [L]
Just make sure you dont have any product directory. Since we will be forcing a redirect and we will redirect the user if the directory doesn't exist.
Now accessing https://devjunky.com/product/143/ will be the same as accessing https://devjunky.com/product.php?id=143
Here's a line by line explanation.
RewriteCond %{REQUEST_FILENAME} !-f
If viewer is not accessing a file.
Ex. product.php
RewriteCond %{REQUEST_FILENAME} !-d
If viewer is not accessing a not existing directory.
Ex. product
RewriteRule ^product\/(.*?)\/$ product.php?id=$1 [L]
If both RewriteCond are true then show the product.php but don't redirect to it.
Here's the rule breakdown.
^product\/(.*?)\/$ ## anything after the word "product/" and before "/" will be saved in a variable. Ex. "https://devjunky.com/product/{ThisValue}/"
product.php?id=$1 ## access the product.php file and pass the saved variable $1 will be the 143
[L] ## don't redirect the page anywhere else. just stay in this page.
Replies (0)
Reply