nkuhta
nkuhta

Reputation: 11128

Conditional RewriteRule

I need to do conditional RewriteRule in .htaccess.

I have rule for JS files, and rule for other requests.

# Rule for js files
RewriteRule ^client/js/([A-Za-z0-9./]+)$ server/js.php

#Rule for other requests
RewriteRule (.*) server/controller.php

In that case of rule any request always go to controller.php. How to make rule logic something like this:

if (jsRule) {
   go_to_js_php();
} else {
   go_to_default_controller():
}

Upvotes: 1

Views: 2461

Answers (1)

SirDarius
SirDarius

Reputation: 42879

By default, Apache's mod_rewrite executes every RewriteRule from top to bottom.

So when the first one matches, your second rule will be executed and match too, because it's a generic catch-all and will therefore match the new url.

The solution in your case is to force mod_rewrite to stop executing after the first rule matches, which is done by adding the [L] (last) flag to the rewrite rule:

# Rule for js files
RewriteRule ^client/js/([A-Za-z0-9./]+)$ server/js.php [L]

#Rule for other requests
RewriteRule (.*) server/controller.php

It simply specifies that the current rule will be the last one executed by mod_rewrite if and only if this rule actually matches.

See http://httpd.apache.org/docs/current/en/rewrite/flags.html#flag_l for more details on this flag.

Upvotes: 3

Related Questions