如果有100000件产品,没有正则表达式的话就会有些麻烦,因为需要写正好那么多条颠倒是非——不能多也不能少。您不会真想管理具有100000条重写规则的.htaccess文件吧!那简直不可思议。
/roduct?P1.html product.php?product_id=1
/roduct?P2.html product.php?product_id=2
/roduct?P3.html product.php?product_id=3
/roduct?P4.html product.php?product_id=4
然而,正如在表中的原始URL列所看到的,所有的输入都遵循相同的模式。并且正如前面所建议的,正则表达式恰好可以派上用场!模式很有用,因为用一个简单的模式就能在理论上匹配无限多个可能的URL输入。因而,只需要对网站中每种URL地址写一个重写规则。
接下来将使用正则表达式来匹配roducts/Pn.html,并用mod_rewrite转换那些与模式product.php?product_id=n匹配的URL地址。这就恰好正确实现了上面的规则。
打开之前在seophp目录中创建的.htaccess文件,并添加如阴影所示的重写规则:
RewriteEngine On
#Rewrite numeric URLs
RewriteRule ^Products/P([0-9]+)\.html$ /product.php?product_id=$1 [L]