如何使用htaccess文件创建干净的URL

问题描述 投票:0回答:2

我有一个房产网站,其中已经上传了很多房产,目前房产的网址看起来像这样

http://propertyonline.com.ng/property.php?product_id=255

但是为了谷歌优化我知道它不应该保持这样,所以我试图将我的网址重写为像财产的标题一样干净的东西。

而不是例如

http://propertyonline.com.ng/property.php?product_id=255

我们将有

http://propertyonline.com.ng/3 Bedroom Flat Large Compound On Banana Island Ikoyi

我有一个变量,目前在此页面上动态地基于上述属性的id回声属性的标题

<?php  echo $row_prop['title']; ?>

请问如何使用htaccess动态重写网址

谢谢

php apache .htaccess mod-rewrite url-rewriting
2个回答
1
投票

您可以将URL格式化为以下方法:

http://propertyonline.com.ng/{product_id}-{product_slug}

{product_id}是数值,{product_slug}可以是任何字符串,后跟产品ID。然后你可以使用这个RewriteRule$1是对([0-9]+)的分组部分{product_id}的反向引用。 [^/]*匹配除正斜杠字符之外的任何字符串,表示为{product_slug}

RewriteRule ^([0-9]+)-[^/]* /property.php?product_id=$1 [QSA,L]

0
投票

如果你想要干净的url使用产品slug对于slug使用下面的代码将删除字符串中的空格和不需要的字符

function to_prety_url($str)
{
    if($str !== mb_convert_encoding( mb_convert_encoding($str, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32') )
        $str = mb_convert_encoding($str, 'UTF-8', mb_detect_encoding($str));
    $str = htmlentities($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace('`&([a-z]{1,2})(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig);`i', '\1', $str);
    $str = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace(array('`[^a-z0-9]`i','`[-]+`'), '-', $str);
    $str = strtolower( trim($str, '-') );
    return $str;
}

更改.htaccess代码(或添加)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/$    index.php    [L]

#this is for product section
RewriteRule ^property/([A-Za-z0-9-]+)/?$    property.php?slug=$1  [NC,L]
ErrorDocument 404 http://www.akshadainfosystem.com/

RewriteRule ^([^\.]+)$ $1.php [NC,L] 
© www.soinside.com 2019 - 2024. All rights reserved.