【问题标题】:htaccess URL rewrite space replacementhtaccess URL 重写空间替换
【发布时间】:2021-04-13 04:01:31
【问题描述】:

编辑说明:将代码修改为 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 替换了空格,所以现在可以访问包含空格的博文标题,但我希望空格变成破折号 - 我做错了。

有很多文章谈到将空格变成破折号,但在测试了其中一些后,我发现我很难将它们的规则与我现有的规则匹配。

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

【问题讨论】:

    标签: .htaccess url-rewriting


    【解决方案1】:

    要将空间转换为-,您可以在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]
    

    【讨论】:

    • 哇,谢谢@anubhava,当空格变成破折号时效果很好,非常感谢。但是现在,当我尝试访问包含带有空格的变量的 URL(现在更改为破折号)时,它会删除部分路径,位于 blog/ 或 brand/ 之前。我一直在尝试调整它大约一个小时或更长时间,我搞砸了哈哈非常感谢您的帮助!
    • 只有在以下情况下才会发生这种情况 1. 这些规则不是RewriteEngine On 下面的第一条规则或 2. 您将这些规则放在DocumentRoot 的子目录中。
    • 这些规则就在RewriteEngine On 的正下方,并且.htaccess 与文件位于同一目录中,否则在添加这两行之前我已经遇到问题了。已测试 Chrome39、FF35、IE11。
    • 哦!不要管那个 ! \s 我直接在重写规则中添加被破坏了。现在它完美无缺。谢谢!
    • 在阅读了几篇 SO 之后,我尝试了这行的几个变体,例如 ([a-zA-Z0-9_'\-]+)([a-zA-Z0-9\'\-]+) 以允许在 url 中使用单引号,但问题似乎出在其他地方。这个案子很费时间,哈哈。当我为其他人了解所发生的事情时,我会及时更新详细信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    相关资源
    最近更新 更多