How to encode special characters using mod_rewrite & Apache?

前端 未结 5 1184
逝去的感伤
逝去的感伤 2020-11-29 07:38

I would like to have pretty URLs for my tagging system along with all the special characters: +, &, #, %, and =

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 07:45

    The underlying problem is that you are moving from a request that has one encoding (specifically, a plus sign is a plus sign) into a request that has different encoding (a plus sign represents a space). The solution is to bypass the decoding that mod_rewrite does and convert your path directly from the raw request to the query string.

    To bypass the normal flow of the rewrite rules, we’ll load the raw request string directly into an environment variable and modify the environment variable instead of the normal rewrite path. It will already be encoded, so we don't generally need to worry about encoding it when we move it to the query string. What we do want, however, is to percent-encode the plus signs so that they are properly relayed as plus signs and not spaces.

    The rules are incredibly simple:

    RewriteEngine On
    
    RewriteRule ^script.php$ - [L]
    
    # Move the path from the raw request into _rq
    RewriteCond %{ENV:_rq} =""
    RewriteCond %{THE_REQUEST} "^[^ ]+ (/path/[^/]+/[^? ]+)"
    RewriteRule .* - [E=_rq:%1]
    
    # encode the plus signs (%2B)  (Loop with [N])
    RewriteCond %{ENV:_rq} "/path/([^/]+)/(.*)\+(.*)$"
    RewriteRule .* - [E=_rq:/path/%1/%2\%2B%3,N]
    
    # finally, move it from the path to the query string
    # ([NE] says to not re-code it)
    RewriteCond %{ENV:_rq} "/path/([^/]+)/(.*)$"
    RewriteRule .* /path/script.php?%1=%2 [NE]
    

    This trivial script.php confirms that it works:

    
    

提交回复
热议问题