Strange problem with Apache and mod_rewrite rule

June 15, 2013 2.1k views
Hello to all, I have apache installed on ubuntu, the re-written module is configured correctly, but one of the rules insists not work. .htaccess RewriteEngine On RewriteRule ^test/([a-z0-9-]+)/([a-z0-9-]+)-([a-z0-9-]+)/?$ /cidade.php?cod=$3 [NC] RewriteRule ^cidade/([a-z0-9-]+)/([a-z0-9-]+)-([a-z0-9-]+)/?$ /cidade.php?cod=$3 [NC] cidade.php The url /test/el-monte-cl/587-369451/ print: Array ( [cod] => 369451 ). Its ok. But /cidade/el-monte-cl/587-369451/ print: Array ( ) The rules are identical, only changes the prefix (city / test). Maybe someone can tell me a solution? thank you
2 Answers
It's because of the [C] flag:

The [C] or [chain] flag indicates that the RewriteRule is chained to the next rule. That is, if the rule matches, then it is processed as usual and control moves on to the next rule. However, if it does not match, then the next rule, and any other rules that are chained together, will be skipped.

The two rules are chained, the first one doesn't match so it skips the rest of the chain which would be the second one in this case.

Remove the C flag from both rules and it should work. You don't need the N flag, so get rid of that one too.

I suspect the problem is not in the .htaccess at all, but rather somewhere in the PHP code or usage. Is it possible what's being printed moves around a whole lot so the '369451' that referenced it once is not quite right any more only a bit later?

The "flags" in .htaccess can be confusing because they're so highly abbreviated yet don't all follow the exact same pattern. [N] is "next", [C] is "chain", [NC] is "no case" (i.e. ignore the case of each letter when making this test), etc. Next and Chain together would be [N,C].

Have another answer? Share your knowledge.