# Conditional Rules

Conditional Rules let you customize smoxy's behavior based on rich conditions like IP addresses, geographic location, headers, cookies, and more. Unlike Page Rules which stop at first match, Conditional Rules allow multiple rules to apply to the same request, making them perfect for complex, layered configurations.

### What are Conditional Rules?

Conditional Rules allow you to override any smoxy configuration setting based on powerful conditional logic. They're ideal for scenarios where you need multiple configuration changes to stack together or when URL patterns alone aren't sufficient.

**Key characteristics:**

* Execute **fourth (last)** in the rule sequence (after Access, Rewrite, and Page Rules)
* **Rich condition matching** - IP, country, headers, cookies, user agents, and more
* Evaluated in **position order** (1, 2, 3...)
* **All matching rules apply** - multiple rules can modify the same request
* **Optional Stop** - set `stop=true` to halt further evaluation
* Can **override any smoxy setting** from your site configuration

### How Conditional Rules Work

Conditional Rules are evaluated in ascending position order (1 → 2 → 3...) for every incoming request. When a rule's conditions match, its settings are applied, and evaluation **continues** to the next rule (unless `stop=true`).

#### Position-Based Evaluation

```
Request from Germany, mobile device
    ↓
Conditional Rule (Position 1) → Match (Country = DE)? → Apply Settings → CONTINUE
    ↓
Conditional Rule (Position 2) → Match (Mobile)? → Apply Settings → CONTINUE
    ↓
Conditional Rule (Position 3) → Match (URI = /api)? → No match → Skip
    ↓
Response (with settings from Rule 1 AND Rule 2)
```

**Important:** Unlike Page and Access Rules, Conditional Rules do **not** automatically stop after the first match. All matching rules apply their settings unless a rule has `stop=true`.

### Conditions & Expressions

Conditional Rules use a rich condition builder that lets you match requests based on various characteristics including:

* **URI**: Request path
* **Host**: Domain name
* **IP**: Client IP address or IP ranges
* **Country**: ISO 3166-2 country code
* **City**: Client's city
* **Subdivisions**: State/region
* **Is European**: Boolean - `true` if request is from EU
* **Method**: HTTP method (GET, POST, PUT, DELETE, etc.)
* **User Agent**: Browser or client identifier
* **Referer**: Referring page URL
* **Accept Language**: Client's preferred language
* **Cookie**: Specific cookie value
* **Arg**: Query parameter value
* **HTTP**: Any HTTP header value
* **Cache-Control**: Cache-Control header directives

#### Operators

* **Equal**: Value matches exactly
* **Not Equal**: Value doesn't match
* **In**: Value is in a list
* **Not In**: Value is not in a list
* **Matches**: Matches regex pattern
* **Contains**: Contains substring
* **Not Contains**: Doesn't contain substring
* **Exists**: Field exists (regardless of value)
* **Not Exists**: Field doesn't exist

#### AND/OR Logic

Combine multiple conditions with AND/OR operators to create sophisticated rules:

```
(Country = "DE" OR Country = "AT" OR Country = "CH")
AND
URI starts with /checkout
```

### Stop Behavior

The **Stop** option is unique to Conditional Rules and controls whether evaluation continues after a rule matches.

#### How Stop Works

**When `stop=false` (default):**

* Rule's settings are applied
* Evaluation continues to the next Conditional Rule
* Multiple rules can modify the same request

**When `stop=true`:**

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

#### When to Use Stop

Use `stop=true` when:

* A rule should be **final** and no further modifications are needed
* You want to **prevent conflicting settings** from other rules
* You're implementing **maintenance mode** or similar override scenarios

**Example:**

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

### When to Use Conditional Rules

#### Use Conditional Rules When:

* ✅ You need **complex conditions** (IPs, countries, headers, cookies, etc.)
* ✅ You want **multiple rules to apply** to the same request
* ✅ You need **advanced AND/OR logic** with multiple conditions
* ✅ URL patterns alone aren't sufficient
* ✅ Different conditions require different configurations that should stack

#### Use Page Rules Instead When:

* ❌ You only need **simple URL-based matching**
* ❌ You want **first match wins** behavior
* ❌ The logic can be expressed with URL patterns only

### Settings: Override Any Configuration

Conditional Rules can override **any setting** from your site's configuration, just like Page Rules. This includes:

* **Routing**: Choose different origins or load balancers
* **Caching**: Control cache TTL, cache keys, cache tags, bypass cache
* **Image Optimization**: AVIF, WebP, JPEG, PNG quality levels
* **Security**: Enable/disable WAF, basic auth, custom error pages
* **Headers**: Add, modify, or remove request/response headers
* **Optimization**: HTML/JS/CSS minification
* **Advanced**: Maintenance mode, debug headers, proxy timeouts

Simply select the settings you want to override when creating or editing a Conditional Rule. The available settings are grouped by category in the smoxy dashboard.

### Use Cases & Examples

#### Example 1: Geographic Content Optimization

**Scenario:** Serve higher quality images to users in wealthy markets, standard quality elsewhere.

```
Position: 1
Condition: Country in ["US", "GB", "DE", "CH", "AU"]
Settings:
- JPEG Quality: 85
- WebP Quality: 85

Position: 2
Condition: Country in ["IN", "BR", "MX"]
Settings:
- JPEG Quality: 70
- WebP Quality: 70

Result: Both rules can apply (if conditions match), US users get higher quality
```

**Why not Page Rules?** Page Rules can't match on country - you need Conditional Rules for geographic targeting.

#### Example 2: Disable Basic Auth for Office IPs

**Scenario:** Your site uses basic authentication, but your team shouldn't need to login from the office.

```
Position: 1
Condition: IP in [203.0.113.0/24, 198.51.100.50]
Settings:
- Basic Authentication: Disabled

Position: 2
Condition: URI starts with "/admin"
Settings:
- Basic Authentication: Enabled
- Basic Auth Users: admin_users

Result: Office bypasses auth (Rule 1), but auth is still enabled for admin area (Rule 2)
```

**Why not Access Rules?** Access Rules are for blocking/challenging/whitelisting, not for toggling features like basic auth.

#### Example 3: Mobile-Optimized Images

**Scenario:** Mobile users should get more aggressive image optimization to save bandwidth.

```
Position: 1
Condition: User Agent matches "(Mobile|Android|iPhone|iPad)"
Settings:
- JPEG Quality: 75
- PNG Quality: 80
- WebP Quality: 75
- Image Max Width: 1200px

Position: 2
Condition: Country = "IN" AND User Agent matches "(Mobile|Android)"
Settings:
- JPEG Quality: 65
- WebP Quality: 65

Result: Mobile users get optimized images, mobile users in India get extra optimization
```

**Why multiple rules?** Both rules can apply - Rule 1 sets baseline mobile optimization, Rule 2 adds extra optimization for specific markets.

### Conditional Rules vs Page Rules

The key differences:

| Feature         | Page Rules              | Conditional Rules                            |
| --------------- | ----------------------- | -------------------------------------------- |
| **Matching**    | URL patterns only       | Rich conditions (IP, country, headers, etc.) |
| **Execution**   | First match wins, stops | All matching rules apply                     |
| **Stop option** | No                      | Yes (optional)                               |
| **Position**    | 3rd in sequence         | 4th (last) in sequence                       |
| **Settings**    | Override any setting    | Override any setting                         |

**Can you use both?** Absolutely! They complement each other:

```
Page Rule: /api/* → Set API load balancer
Conditional Rule: User-Agent = "mobile" → Enable mobile optimizations
→ Both apply to mobile requests to /api/users
```

**Execution order:** Page Rule executes first (stops on match), then Conditional Rules evaluate (all matching apply).

### Rule Order Best Practices

#### 1. Critical Rules First

Place rules that should always take precedence at lower positions:

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

#### 2. Use Stop Strategically

```
Position 1: IF (emergency mode) THEN (minimal features) STOP
Position 2+: Normal operational rules (skipped during emergency)
```

#### 3. Layer Complementary Rules

Since all matching rules apply, you can build layered configurations:

```
Position 1: IF (Country = "DE") THEN (GDPR-compliant headers)
Position 2: IF (Mobile) THEN (Mobile optimizations)
Position 3: IF (URI = /checkout) THEN (High security)
→ German mobile checkout gets all three!
```

#### 4. Avoid Conflicting Settings

If multiple rules set the same configuration key, the **last matching rule wins**:

```
Position 1: IF (Country = "US") THEN (Cache TTL = 3600)
Position 2: IF (URI = /api) THEN (Cache TTL = 60)
→ US requests to /api get TTL = 60 (last match wins)
```

### Using IP Lists

Instead of hardcoding IPs in each rule, create reusable IP Lists in your account settings:

1. Create an IP List named "office\_ips" with your office IP ranges
2. Reference it in your Conditional Rule conditions

**Benefit:** Update the IP list once, and all rules using it are automatically updated across all your sites.

### Uniqueness

Each site can only have **one Conditional Rule per unique expression**. If you try to create a duplicate, you'll see: "The rule for this expression already exists."

This prevents duplicate rules and keeps your configuration clean.

### Common Mistakes

❌ **Forgetting rules stack**

```
Position 1: IF (URI = /api) THEN (Cache = disabled)
Position 2: IF (URI = /api/*) THEN (Cache = enabled & Cache TTL = 3600)
→ Both apply, last one wins: Cache = enabled with TTL 3600
```

✅ **Be aware of interactions**

```
Use stop=true or consolidate into one rule when needed
```

***

❌ **Using Stop too early**

```
Position 1: IF (Country = "US") THEN (settings) STOP
Position 2: IF (Mobile) THEN (mobile settings) [never applies to US mobile users]
```

✅ **Stop only when necessary**

```
Remove stop=true unless you specifically need to halt evaluation
```

***

❌ **Using Conditional Rules for simple URLs**

```
Condition: URI starts with "/admin"
→ Should use Page Rule instead
```

✅ **Use Page Rules for URL-only logic**

```
Page Rule: Match /admin/* → Settings
(Simpler and executes earlier)
```

***

❌ **Conflicting settings from multiple rules**

```
Position 1: IF (Mobile) THEN (Image Quality = 80)
Position 2: IF (Country = "US") THEN (Image Quality = 90)
→ US mobile users get Quality = 90 (last match wins)
```

✅ **Plan for overlapping conditions**

```
Either use stop, adjust positions, or accept last-match-wins behavior
```

### Testing Conditional Rules

1. **Enable Debug Headers** in your site configuration
2. **Make test requests** with different conditions (IPs, user agents, etc.)
3. **Check response headers** to see which Conditional Rules matched
4. **Verify settings** are being applied in the expected order
5. **Test overlapping conditions** to ensure the last-match-wins behavior is acceptable
