简体   繁体   中英

Apache mod_rewrite [R,C] not working

I have following setup

RewriteCond %{REQUEST_URI}  ^/search.php$
RewriteCond %{QUERY_STRING} ^what=(.*)&where=(.*)$
RewriteRule ^ /%1/%2? [R=302]

With this setup everything is working as excepted

example.com/search.php?what=foo&where=bar

is rewritten to

example.com/foo/bar

But I also need to hit search.php again so I added

    RewriteCond %{REQUEST_URI}  ^/search.php$
RewriteCond %{QUERY_STRING} ^what=(.*)&where=(.*)$
RewriteRule ^ /%1/%2? [R=302,C]
RewriteRule ^ /search.php?what=$1&where=$2 [L]

Now it 'skips' the redirect and its rewritten

from example.com/search.php?what=foo&where=bar to example.com/search.php?what=foo&where=bar

Is the redirect not working with the C flag?

You cannot do this:

RewriteCond %{REQUEST_URI}  ^/search.php$
RewriteCond %{QUERY_STRING} ^what=(.*)&where=(.*)$
RewriteRule ^ /%1/%2? [R=302,C]
RewriteRule ^ /search.php?what=$1&where=$2 [L]

For http://www.example.com/search.php?what=foo&where=bar , you cannot hit at the same time /foo/bar and /search.php?what=foo&where=bar, Rewrite results only in a unique URL.

In the above rules, http://www.example.com/search.php?what=foo&where=bar , it will match all the 4 lines, at the last line, it gives /search.php?what=&where=, as $1 and $2 are empty.

So the solution is to remove the last line, like this:

RewriteCond %{REQUEST_URI}  ^/search.php$
RewriteCond %{QUERY_STRING} ^what=(.*)&where=(.*)$
RewriteRule ^ /%1/%2? [R=302]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM