htaccess URL重写空间替换

时间:2015-01-22 18:01:22

标签: .htaccess url-rewriting

编辑注意:修改代码到Documentroot

我正在为客户的网站做重写规则,我开始使用自己网站的博客重写规则,因为它们符合客户的需求。现在每个规则都根据客户需求进行了修改,我很高兴它的工作非常精细。这是最后的样子;

Options +FollowSymlinks
RewriteEngine on

# executes repeatedly as long as there are more than 1 spaces in URI
RewriteRule "^(\S*)\s+(\S*\s.*)$" /$1-$2 [L,NE]

# executes when there is exactly 1 space in URI
RewriteRule "^(\S*)\s(\S*)$" /$1-$2 [L,R=302,NE]

#Rewrite des urls blog
RewriteRule fashion/blog/([a-zA-Z0-9\s]+)/([a-zA-Z0-9\s]+)-([0-9]+) fashion/blogpost.php?brand=$1&url=$2&id=$3

#Rewrite des urls brands
RewriteRule fashion/brand/([a-zA-Z0-9\s]+)-([0-9]+) fashion/brand.php?brand=$1&id=$2

#Rewrite des urls shop brands
RewriteRule fashion/shop/brands/([a-zA-Z0-9\s]+)-([0-9]+) fashion/shopbrand.php?brand=$1&id=$2

#Rewrite des urls shop category
RewriteRule fashion/shop/category/([a-zA-Z0-9\-]+)-([0-9]+) fashion/shopcategory.php?url=$1&id=$2

#Enlever l'extension
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^(.*)$ $1.php [L] 

ErrorDocument 404 http://localhost/fashion/404.php

#RewriteCond %{REQUEST_URI} !/maintenance.php$
#RewriteCond %{REMOTE_ADDR} !^24\.201\.45\.57
#RewriteRule $ /maintenance.php [R=302,L]

我想避免在博客标题或品牌名称中出现空格问题,因此我进行了一些搜索,并在我的规则中添加了\s。它运行正常,因为它用%20替换空格,所以现在可以访问包含空格的博客标题,但我希望空格变成破折号 - 我无法做到正确。

有很多文章提到将空格变成破折号,但经过测试后,我发现我很难将规则与现有规则相匹配。

非常感谢任何提示或解释!

1 个答案:

答案 0 :(得分:3)

要将空间转换为-,您可以在RewriteEngine On行下面使用这两条规则:

# executes repeatedly as long as there are more than 1 spaces in URI
RewriteRule "^(\S*)\s+(\S*\s.*)$" /$1-$2 [L,NE]

# executes when there is exactly 1 space in URI
RewriteRule "^(\S*)\s(\S*)$" /$1-$2 [L,R=302,NE]