使用PHP和IIS7创建SEO和人类友好/可读的url


Creating SEO and human freindly/readable URLs using PHP and IIS7

我运行的是PHP5.3.6和IIS7。我目前在一个以产品为中心的网站上工作,我有一个php页面,根据查询字符串动态生成一个页面,如/product.php?id=12345

我在数据库中拥有的产品数量各不相同,但都有数百种。它们有唯一的id和名称。

我希望每个页面的地址是由他们的名称,而不是由查询字符串。

例如,不用:

/product.php?id=12345

我更喜欢:

/acme-super-widget-in-blue-with-cool-groovy-gadget-attachment

我在IIS7中有URL Rewrite组件,但我不想手动输入值。我宁愿有一个动态的过程。我相信这里需要的功能是添加一个URL重写规则到web.config文件,但我不确定这是真的还是最好的方法。

谢谢。

我建议将ID与名称一起使用,这样您就可以支持具有相同名称的产品(将来的验证)或具有非ascii字符的产品…如果你有国际名字。我还建议目前在URL中只使用ascii字符,因为我注意到一些网站和浏览器倾向于将非ascii字符扩展为丑陋的百分比编码。

IIS 7比Apache更复杂,但我认为这可能对你有用http://blogs.iis.net/bills/archive/2008/05/31/urlrewrite-module-for-iis7.aspx

下面是一个重写规则的例子,它会从id中去掉名字,只把id传递给脚本。

IIS 7使用上面链接中的模块

匹配的URL

^([0-9]+)[^/]*/?$
行动

index.php?id={R:1} [QSA,L]

Apache;)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([0-9]+)[^/]*/?$ index.php?id=$1 [QSA,L]

这是一个PHP函数,它将生成您的友好url的id名称部分。

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, '-');
}

这会给你URL,比如

产品ID = 12345,名称= "acme super widget"

/12345-acme-super-widget/

产品ID = 12345,名称= "日本产品"

/12345-japanese-product/

看起来是这样的:http://www.iis.net/download/URLRewrite正是您所需要的