【问题标题】:htaccess fails to redirect when encounter whitespacehtaccess 在遇到空格时无法重定向
【发布时间】:2016-02-26 17:01:33
【问题描述】:

我正在使用 htaccess 获取干净的 url。只要参数不带有空格,它就可以正常工作。在这种情况下,它会转换 %20 中的空间,我收到 404 错误。

所以基本上是 URL:http://localhost:8080/series/dynamics/admin/cleanURL/green%20apple

给我 404 错误。但 URL:http://localhost:8080/series/dynamics/admin/cleanURL/greenapple 工作正常。

还有一种方法可以从 URL 中删除目录详细信息,我试过了

RewriteRule ^series/dynamics/admin/cleanURL/(.*)$ /$1 [L,NC,R]

但是没用

htaccess

<IfModule mod_rewrite.c>
     Options +MultiViews 
     Rewriteengine on
     RewriteBase /series/dynamics/admin/cleanURL/
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule ^series/dynamics/admin/cleanURL/(.*)$ /$1 [L,NC,R]
     Rewriterule ^([a-zA-Z0-9]+)/?$ index.php?product=$1
     RewriteRule ^(.*)(\s|%20)(.*)$ /$3-$4 [R=301,L,NE]
     #rewrite group and subgroup e.g. http://.../value1/value2/ [L,NC,QSA]
     Rewriterule ^([a-zA-Z0-9]+(.*)+)/([^/]+(.*)+)/?$ index.php?product=$1&subgroup=$2 [L,NC,QSA]
     </IfModule>

【问题讨论】:

    标签: apache .htaccess clean-urls


    【解决方案1】:

    您需要在站点根目录 .htaccess 中添加此规则:

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.*) series/dynamics/admin/cleanURL/$1 [L]
    

    那么在/series/dynamics/admin/cleanURL/.htaccess中有这些规则:

    Options +MultiViews 
    Rewriteengine on
    RewriteBase /series/dynamics/admin/cleanURL/
    
    RewriteCond %{THE_REQUEST} /series/dynamics/admin/cleanURL/(\S*)\s [NC]
    RewriteRule ^ /%1 [L,R=302,NE]
    
    RewriteRule ^([^\s\x20]*)[\s\x20]+(.*)$ $1-$2 [L,R=302,NE]
    
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    
    Rewriterule ^(\w+)/?$ index.php?product=$1 [L,QSA]
    
    #rewrite group and subgroup e.g. http://.../value1/value2/ [L,NC,QSA]
    Rewriterule ^([a-zA-Z0-9]+(.*))/([^/]+(.*))/?$ index.php?product=$1&subgroup=$2 [L,NC,QSA]
    

    【讨论】:

    • @anubhava..感谢您的调查。我已经设法从 url 中删除目录。然而,当它遇到空格时,URL 看起来像:localhost:8080/-,而它是localhost:8080/green-apple。我现在还有另一个问题,因为我正在使用 php $_GET 函数使用 url 上的参数从数据库中提取更多数据,我已经完全失去了这个 chnge
    • 当进一步检查 print_r($_SERVER);我实际上得到空查询字符串 [QUERY_STRING] => [REQUEST_URI] => /apple [SCRIPT_NAME] => /series/dynamics/admin/cleanURL/index.php [PHP_SELF] => /series/dynamics/admin/cleanURL/ index.php
    • 你能解释一下 RewriteRule ^ /%1 [L,R=302,NE] 实际上在做什么吗?
    • 抱歉,看来我要花很长时间才能解决这个问题。现在,在上面的代码的帮助下,我已经成功地用连字符替换了空格。但是我怎么能让后端的 url 像 index.php?product=Green apple 一样,因为 php 既不识别 Green-apple 也不识别 Green%20apple。提前致谢。
    • 感谢@anubhava :),感谢您在解决此问题时表现出的耐心。
    猜你喜欢
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 2011-03-31
    • 1970-01-01
    相关资源
    最近更新 更多