htaccess URL 重写 space 替换

htaccess URL rewrite space replacement

编辑注意:将代码修改为 Documentroot

我正在为一个客户的网站做重写规则,我从我自己网站的博客重写规则开始,因为它们有点符合客户的需求。现在每条规则都根据客户需求进行了修改,我很高兴它运行得非常好。这是最后的样子;

Options +FollowSymlinks
RewriteEngine on

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

# executes when there is exactly 1 space in URI
RewriteRule "^(\S*)\s(\S*)$" /- [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=&url=&id=

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

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

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

#Enlever l'extension
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^(.*)$ .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 替换了空格,所以现在可以访问包含空格的博文标题,但我希望空格变成破折号 - 但我做错了。

有很多文章都谈到了如何将空格转换为破折号,但在测试其中几篇之后,我发现我很难将它们的规则与我现有的规则相匹配。

任何提示或解释将不胜感激!

要将 space 转换为 -,您可以使用 RewriteEngine On 行下方的这 2 条规则:

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

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