replace space by - using htaccess

后端 未结 2 1222
旧巷少年郎
旧巷少年郎 2020-12-18 15:13

hi i have this code in my htaccess


Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \\s/+sin         


        
相关标签:
2条回答
  • 2020-12-18 15:40

    Have your rules like this:

    <IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{THE_REQUEST} \s/+single\.php\?title=([^\s&]+) [NC]
    RewriteRule ^ %1/? [R=302,L,NE]
    
    ## Adding a trailing slash
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{THE_REQUEST} \s/+(.*?)[^/][?\s]
    RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301]
    
    # convert %20 to -
    RewriteRule "^(\S*) +(\S* .*)$" $1-$2 [N,NE]
    RewriteRule "^(\S*) (\S*)$" $1-$2 [L,R=302,NE]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+?)/?$ single.php?title=$1 [NE,L,QSA]
    </IfModule>
    
    0 讨论(0)
  • 2020-12-18 15:42

    You could try replacing the first rule with something like:

    RewriteCond %{ENV:REDIRECT_STATUS} !200
    RewriteCond %{THE_REQUEST} \s/+single\.php\?title=([^\s&]+) [NC]
    RewriteRule ^ /%1? [L,NE]
    
    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteCond %{THE_REQUEST} \s/+single\.php\?title=([^\s&]+) [NC]
    RewriteRule ^(.*)(?:\ |\+)(.*)$ /$1-$2 [L,NE]
    
    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteCond %{THE_REQUEST} \s/+single\.php\?title=([^\s&]+) [NC]
    RewriteCond %{REQUEST_URI} !(\ |\+)
    RewriteRule ^(.*)$ /$1 [R=301,L,NE]
    

    So instead of just redirecting direct requests to the "/title", you first internally rewrite it to "/title" (first rule), then iteratively replace all spaces and "+"'s with dashes "-" (second rule). When there are no more spaces or "+"'s in the URI, redirect (third rule).

    Then you'd need to edit your single.php so that it can interpret "title"'s with dashes instead of spaces.

    0 讨论(0)
提交回复
热议问题