繁体   English   中英

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

[英]how to create clean urls using htaccess file

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

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

但是为了Google优化,我知道它不应该像这样保留,因此我尝试将我的url重写为诸如属性标题之类的干净内容。

所以代替例如

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动态重写网址

谢谢

您可以将网址的格式设置为以下一种方法:

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

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

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

如果您想要干净的url,请使用product 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] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM