Creating SEO and human freindly/readable URLs using PHP and IIS7
I am running PHP5.3.6 and IIS7. I am currently working on a product centric site where I have one php page that dynamically generates a page based on a query string such as /product.php?id=12345
.
The volume of products that I have in the database varies, but measures in the hundreds. They have unique IDs and names.
I want for each page to be addresses by their name instead of by the query string.
For example, instead of:
/product.php?id=12345
I wou开发者_运维百科ld prefer:
/acme-super-widget-in-blue-with-cool-groovy-gadget-attachment
I have the URL Rewrite
component in IIS7, but I don't want to enter values manually. I would rather have a dynamic process in place. I believe the needed functionailty here is to add an URL Rewrite rule to the web.config
file, but I'm not sure if that is true or the best approach.
Thank you.
I would recommend using the ID along with the name so that you can support products with the same name (future proofing), or products with non-ascii characters... should you have international names. I would also recommend using only ascii characters in the URL's for now as I've noticed some sites and browser tend to expand non-ascii characters in to ugly percent encoding.
IIS 7 is a bit trickier than Apache, but I think this might work for you http://blogs.iis.net/bills/archive/2008/05/31/urlrewrite-module-for-iis7.aspx
Here is an example rewrite rule which will strip the name off the id and pass just the id to the script.
IIS 7 Using the module in the link above
Match URL
^([0-9]+)[^/]*/?$
Action
index.php?id={R:1} [QSA,L]
Apache just for good messure ;)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([0-9]+)[^/]*/?$ index.php?id=$1 [QSA,L]
Here is a PHP function that will generate the id name portion of your friendly URLs.
function friendlyURL($id, $title) {
$string = $title;
$paramcount = func_num_args();
for ($i = 2; $i < $paramcount; $i++) {
$string .= "-" . func_get_arg($i);
}
$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i', '-', $string);
$string = htmlentities($string, ENT_COMPAT, "utf-8");
$string = preg_replace("`&([a-z]+);`i", "", $string);
$string = preg_replace("`['\[\]]`", "", $string);
$tmp = $string;
$string = preg_replace(array("/[^A-Za-z0-9]/", "`[-]+`"), "-", $string);
$string = trim($string, '-');
return trim($id . "-" . $string, '-');
}
This would give you URL's like
Product ID = 12345, Name = "acme super widget"
/12345-acme-super-widget/
Product ID = 12345, Name = "Japanese product ギター"
/12345-japanese-product/
It looks like this: http://www.iis.net/download/URLRewrite is exactly what you need.
精彩评论