# Rules Execution & Ordering

Understanding how smoxy evaluates and executes rules is crucial for building effective traffic management and security policies. This page explains the execution flow, ordering system, and behavior patterns across all rule types.

### Execution Flow Between Rule Types

Requests are processed in a specific sequence:

1. **Access Rules**: Security layer, evaluated first, handle security decisions (block, challenge, skip, continue).
2. **Rewrite Rules**: URL rewriting, modifies the request URL before other rules are applied.
3. **Conditional Rules**: Condition-based settings, applied last.

**Importance of Order:**

* **Access Rules first**: Prioritize security actions.
* **Rewrite Rules second**: Transform URLs for consistent processing.
* **Conditional Rules last**: Implement complex logic conditions.

**Example:** A request to `/old-page` may be rewritten to `/new-page` via a Rewrite Rule. Then, Conditional Rules for `/new-page` are applied.

### Position Within Each Rule Type

#### How Position Works

Within each rule type, rules are evaluated based on their **position** (also called order):

* Position starts at **1** (not 0)
* Rules are evaluated in **ascending order** (1 → 2 → 3 → ...)
* When you create a new rule, it's automatically assigned the next available position
* Position is independent for each rule type (e.g., Access Rule #1 and Conditional Rule #1 are separate)

**Example:**

```
Access Rules: Position 1, 2, 3, 4, 5...
Rewrite Rules: Position 1, 2, 3...
Conditional Rules: Position 1, 2, 3, 4...
```

#### Position Determines Evaluation Order

The position number determines which rule is evaluated first within its type:

```
Position 1: Evaluated FIRST
Position 2: Evaluated SECOND
Position 3: Evaluated THIRD
...
Position N: Evaluated LAST
```

This is especially important for:

* **Access Rules**: Whitelist rules (skip, or continue actions) should have lower positions than block rules
* **Rewrite Rules**: More specific URL patterns should come before general patterns
* **Conditional Rules**: Rules you want to apply first should have lower positions

### Reordering Rules

You can change the execution order of your rules at any time using the drag-and-drop interface in the smoxy dashboard.

#### How Reordering Works

When you move a rule to a new position:

1. **Moving UP** (to a smaller position number):
   * All rules between the new and old position shift down (+1)
2. **Moving DOWN** (to a larger position number):
   * All rules between the old and new position shift up (-1)
3. **Moving to Bottom**:
   * Set a very high position number (e.g., 100)
   * The system automatically places it at the end

**Example:**

```
Before: [Rule-1, Rule-2, Rule-3, Rule-4, Rule-5]
Move Rule-5 to position 2
After:  [Rule-1, Rule-5, Rule-2, Rule-3, Rule-4]
```

#### Position Validation

The system ensures:

* No duplicate positions
* No gaps in position numbers
* Sequential ordering is maintained
* If conflicts are detected, all positions are automatically recalculated

### First Match vs All Matching

Different rule types have different execution patterns:

| Rule Type             | Execution Pattern  | Stops After Match? | Notes                                   |
| --------------------- | ------------------ | ------------------ | --------------------------------------- |
| **Access Rules**      | All matching apply | ⚠️ Optional        | `skip` action can skip subsequent rules |
| **Rewrite Rules**     | First match wins   | ✅ **Yes**          | Stops after first URL match             |
| **Conditional Rules** | All matching apply | ⚠️ Optional        | Continues unless `stop=true`            |

#### Access Rules - Position-Based with Skip

Access Rules evaluate in position order, but the `skip` action affects subsequent execution:

* **Block/Challenge actions**: Continue to next Access Rule
* **Skip action with flags**:
  * `access_rules=true`: Skip remaining Access Rules
  * `waf=true`: Bypass Web Application Firewall

**Best Practice:** Place skip rules (whitelist) at lower positions (1, 2, 3...) and block/challenge rules at higher positions.

**Exception:** If a rule has `stop=true`, no further Access Rules are evaluated.

#### Rewrite Rules - First Match Wins

Rewrite Rules stop after the **first matching URL pattern**:

```
Position 1: Match /old-path → Rewrite to /new-path → STOP
Position 2: Match /legacy/* → NOT EVALUATED
Position 3: Match /* → NOT EVALUATED
```

**Important:** Order matters! More specific patterns should come before general patterns.

#### Conditional Rules - All Matching Apply

Conditional Rules evaluate **all enabled rules** that match the conditions:

```
Position 1: Match (IP from office) → Settings Applied → Continue
Position 2: Match (Country = US) → Settings Applied → Continue
Position 3: Match (URI = /api/*) → Settings Applied → Continue
All three rules can apply to the same request!
```

**Exception:** If a rule has `stop=true`, no further Conditional Rules are evaluated.

### Stop Behavior (Conditional & Access Rules)

The **Stop** option is only available for Conditional & Access Rules.

#### How Stop Works

When enabled (`stop=true`):

* The rule's settings are applied
* **All subsequent Rules are skipped**
* Other rule types (Rewrite, Conditional) are not affected

When disabled (`stop=false`, default):

* The rule's settings are applied
* Evaluation continues to the next Rule

**Use Case Example:**

```
Position 1: IF (maintenance mode) THEN (show maintenance page) STOP
Position 2: IF (office IP) THEN (disable basic auth) [never evaluated during maintenance]
Position 3: IF (mobile) THEN (optimize images) [never evaluated during maintenance]
```

### Cache Hit vs Cache Miss Execution

Rules execute at different stages depending on whether content is served from cache or fetched from your origin:

#### Typical Execution Context

* **Access Rules**: Execute on **both cache hit and miss** (security always applies)
* **Rewrite Rules**: Execute **before cache lookup** (URL transformation happens first)
* **Conditional Rules**: Execute based on request conditions (independent of cache status)

#### Debug Headers

Enable **Debug Headers** in your site's configuration to see:

* Which rules were applied
* Cache hit/miss status
* Rule evaluation details

This helps you understand exactly how your rules are being executed for each request.

### Best Practices for Rule Ordering

#### 1. Access Rules - Whitelist First

```
Position 1-3: Skip rules (trusted IPs, internal tools)
Position 4+: Block/Challenge rules (suspicious traffic)
```

#### 2. Rewrite Rules - Specific Before General

```
Position 1: /exact-old-url → /new-url (most specific)
Position 2-3: Regex patterns
Position 4-5: Catch-all patterns (max 5 rules total)
```

#### 4. Conditional Rules - Critical First

```
Position 1: Maintenance mode (with stop=true)
Position 2-5: Business logic rules
Position 6+: Optimization rules
```

### Testing Your Rule Order

1. **Enable Debug Headers** in your site configuration
2. **Make test requests** to your site
3. **Check response headers** to see which rules were applied
4. **Adjust positions** based on the results
5. **Repeat** until you achieve the desired behavior
