60

How may I perform a rule if the URL is NOT matching the path "forums"?

For example:

RewriteCond IF URL IS NOT forums
RewriteRule !\.(js|gif|css|jpg|png)$ %{DOCUMENT_ROOT}/index.php [L]
MrWhite
  • 43,179
  • 8
  • 60
  • 84
jcoahd
  • 713
  • 2
  • 6
  • 7

1 Answers1

99

Apache's RewriteCond as well as the RewriteRule directive support the exclamation mark to specify a non-matching pattern:

You can prefix the pattern string with a '!' character (exclamation mark) to specify a non-matching pattern.

This should work:

RewriteCond %{REQUEST_URI} !^/forums.*
RewriteRule !\.(js|gif|css|jpg|png)$ /index.php [L]

--> redirect all requests not beginning with forums and not ending with the listed suffices to index.php

marapet
  • 54,856
  • 12
  • 170
  • 184
  • 17
    It's worth noting that the order of processing is (1) check the RewriteRule for a matching pattern, then, only if it matches: (2) go back up to the 1st associated RewriteCond and check whether it matches. (and continue with any subsequent RewriteConds). So in the example above, the chronological description is For all requests not ending in (.js, .gif, .css, .jpg, .png) ... which have a URL that does not begin with "/forums" ... forward to index.php (and, per [L], ignore any subsequent RewriteRules that might otherwise impact the request.) HTH :) – cweekly Oct 24 '14 at 20:40
  • @cweekly This seems to be the case for [IIS mod_rewrite](http://www.micronovae.com/ModRewrite/ref/RewriteCond.html) - is this also true for apache mod_rewrite? – marapet Sep 05 '15 at 20:53
  • [The rule is only used if both the current state of the URI matches its pattern, and if the conditions are met.](http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond) So why does the order matter? – Tamás Bolvári Dec 04 '16 at 03:28
  • @cweekly thanks for this, i was scratching my head why i was having an infinite redirect earlier – khakiout May 24 '17 at 05:25
  • 2
    @TamásBolvári In this example, the order may not matter, but that's not the point cweekly was raising in his comment (which I assume is what you are referring to). It's just that the "description" in the answer is back-to-front to what actually happens. Knowing the order of processing is important when creating efficient rules. – MrWhite Sep 07 '18 at 21:14