【问题标题】:Implement friendly URLs with product name使用产品名称实现友好的 URL
【发布时间】:2013-05-16 00:18:17
【问题描述】:

我目前正在开发一个电子商务网站,其单个产品的 URL 格式如下:

examplesite.com/shop.php?sec=prod&prod=373

其中 373 是单个产品编号。我想重写所有产品 URL,使它们看起来像这样:

examplesite.com/product-name-here

很遗憾,某些产品名称包含 *、/ 和 ! 等字符,这些字符不应包含在 URL 中。

我可以访问所有内容,但技能有限,所以如果你回答,请假设我完全天真!

谢谢!

【问题讨论】:

    标签: url-rewriting seo friendly-url


    【解决方案1】:

    有时仅使用唯一的 slug(“product-name-here”)可能会很棘手。最好有这样的东西:

    examplesite.com/373/product-name-here.html // or
    examplesite.com/373-product-name-here
    

    ... 或任何其他组合,但将产品 ID 保留在 url 中。要创建蛞蝓,谷歌PHP slug generator

    如果您使用 Apache 运行服务器,则需要加载 mod_rewrite 模块并将 .htaccess 添加到项目的根目录(执行 index.php 的位置)

    RewriteEngine On
    Options FollowSymLinks
    
    # examplesite.com/373/product-name-here.html
    RewriteRule ^([0-9]*)/([a-zA-Z0-9+-_\.])\.html$ shop.php?sec=prod&prod=$1
    

    【讨论】:

    • 您好克劳迪奥,感谢您的回答!我找到了一个关于 slug 生成的好网站 (cubiq.org/the-perfect-php-clean-url-generator),但我不确定在哪里输入此代码。这与上面的 htaccess 相结合,可以完成这项工作吗?还是我错过了一些阶段?谢谢!
    • 嗨!您需要为您拥有的每个产品生成一个 slug。大多数时候,我将它保存在数据库中(我在 products 表中有一个字段 slug),但您也可以在创建链接时动态生成它:<a href="<?=createSlug($product->title)?>"><?=$product->title?></a>。在 PHP 中,您需要创建像 examplesite.com/373-product-name-here 这样的 url,.htaccess 中的规则将捕获它们并解析为您的原始 url (shop.php?sec=prod&prod=$1)
    猜你喜欢
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2011-11-24
    • 1970-01-01
    • 2010-09-25
    • 2010-11-17
    • 2010-10-14
    相关资源
    最近更新 更多