Mantra Networking Mantra Networking

F5 LTM Load Balancer: iRules

F5 LTM Load Balancer: iRules
Created By: Lauren R. Garcia

Table of Contents

  • Overview
  • What are iRules?
  • Key Use Cases for iRules
  • Basic Structure of an iRule
  • Example iRules
  • Blocking Specific URIs
  • Logging Client IPs
  • Commonly Used Events
  • Best Practices
  • Conclusion

F5 LTM Load Balancer: iRules — Overview

What Are F5 iRules?

iRules are a dynamic scripting feature available in the F5 BIG-IP Local Traffic Manager (LTM). With iRules, administrators can write custom rules using the TCL scripting language to control, manipulate, and inspect network traffic at a very granular level. They enable real-time decision-making—allowing BIG-IP devices to react dynamically to specific conditions or patterns in traffic.

Why You Need to Know About iRules

  • Flexible Traffic Management: Default load balancing policies often aren’t enough for complex environments. iRules fill this gap by letting you tailor how traffic is routed, intercepted, logged, or transformed, supporting both simple requirements and highly advanced use cases.
  • Enhanced Security: iRules can enforce security policies such as blocking malicious requests, redirecting suspicious clients, or logging specific activities for compliance—without making changes to the applications themselves.
  • Adaptability: Business needs, regulatory standards, and security threats evolve constantly. With iRules, you can quickly respond to these changes by deploying or updating scripts on the load balancer, avoiding lengthy development cycles or application downtime.
  • Operational Visibility: iRules can extract and log critical information from network flows, providing operations and security teams with essential insights for monitoring and troubleshooting.

How It Works

  • Event-Driven Scripting: iRules operate based on specific events in the network traffic lifecycle—such as a new client connection, an HTTP request, or a server response. When such an event occurs, the associated iRule logic is executed in real time.
  • Deep Inspection: iRules allow inspection of nearly any aspect of the packet or request—from IP addresses to HTTP headers and payloads—enabling highly specific controls.
  • Dynamic Actions: Depending on the conditions set in the script, iRules can perform actions like rewriting URLs, redirecting traffic, refusing or dropping requests, modifying headers, or logging data.
  • Layer 2–7 Customization: iRules provide programmability from network layers (e.g., IP, TCP) up to the application layer (HTTP), making them versatile for almost any application delivery scenario.

In summary: iRules transform the F5 LTM from a standard load balancer into a highly customizable, programmable gateway—equipping organizations with powerful tools for security, optimization, compliance, and operational agility.

What are iRules?

iRules are a dynamic scripting feature within the F5 BIG-IP Local Traffic Manager (LTM) that allow administrators to customize and control how traffic is handled on the load balancer. Written using the TCL scripting language, iRules provide the flexibility to inspect, modify, and direct network traffic based on virtually any layer 2-7 data.

  • Custom Traffic Handling: iRules enable F5 LTM to make traffic decisions based on protocol, headers, content, source, destination, and even payload, far beyond what’s possible with default configuration.
  • Event-Driven Architecture: Each iRule is event-based. Common triggers include when an HTTP request is received, when a client connects, or when a server responds.
  • Extensive Use Cases: Organizations use iRules for security enforcement, traffic redirection, protocol validation, session management, logging, and more.
  • Scripting Language: iRules use a lightweight version of the TCL scripting language, making them easy to read and maintain for those familiar with scripting.

By leveraging iRules, organizations can fine-tune their application delivery, protect assets, and adapt quickly to new requirements without lengthy upgrades or complex changes.

Key Use Cases for iRules

iRules empower organizations to customize how network traffic is processed within the F5 BIG-IP LTM, giving granular control that extends well beyond standard load balancer features. Here are the primary ways iRules are commonly used:

  • Custom Traffic Routing: Dynamically direct requests based on criteria such as URI, HTTP headers, client IP address, or even payload content—enabling advanced application steering that responds to business and application needs.
    Example: Route mobile app traffic to a dedicated pool for optimized performance.
  • Security Enforcement: Block, redirect, or log suspicious requests in real time. iRules help mitigate threats such as malformed packets, injection attempts, or access to sensitive URIs.
    Example: Reject all requests to /admin from unauthorized IPs.
  • Session Persistence (Sticky Sessions): Implement custom logic to keep user sessions on the same backend server, ensuring consistent user experiences or compliance, such as using a specific cookie, header, or device attribute.
  • Traffic Modification: Rewrite, insert, or remove HTTP headers or alter payload content dynamically—useful for compliance, legacy integration, or browser-specific fixes.
    Example: Add security headers to outgoing responses.
  • Application Analytics and Logging: Extract, log, or report pertinent data (such as user IDs, geolocation, or request types) from live traffic for auditing, troubleshooting, or business analytics.
  • Protocol Validation and Transformation: Enforce protocol compliance or adapt protocol flows on the fly, enabling integration with a wide variety of legacy or non-standard applications.

By leveraging these use cases, organizations can introduce agile and secure traffic management, reduce downtime, and rapidly adapt to new application requirements without waiting for software upgrades or custom development cycles.

Basic Structure of an iRule

The basic building block of any iRule is its event-driven structure. iRules operate by specifying one or more events that trigger custom TCL script actions when specific network traffic conditions are met.

  1. Choose an Event:
    Each iRule begins with a specific event keyword (such as HTTP_REQUEST or CLIENT_ACCEPTED) that determines when the script runs.
  2. Define the Actions:
    Inside curly braces { }, use TCL scripting to specify what action should occur if the trigger condition is met. Actions can include commands to redirect, reject, log, or modify traffic.
when <EVENT> {
    # Your logic here
}

Example:

when HTTP_REQUEST {
    if {[HTTP::host] eq "example.com"} {
        HTTP::redirect "https://newsite.com[HTTP::uri]"
    }
}

Explanation:
- when HTTP_REQUEST { ... } triggers the code block for every incoming HTTP request.
- Inside, an if statement checks whether the Host header matches example.com.
- If true, the request is redirected to newsite.com.

  • Indentation: Use clear indentation inside event blocks for readability.
  • Comments: Add inline comments (#) to explain logic for future administrators.

With just this structure, you can intercept, inspect, and transform traffic flowing through your F5 LTM using highly customizable logic.

Example iRules

Here are several practical iRule examples that showcase how F5 BIG-IP LTM can manipulate, redirect, or secure network traffic through event-driven Tcl scripting.

  • HTTP-to-HTTPS Redirect:
    Redirect all HTTP requests to HTTPS for better security.
    when HTTP_REQUEST {
        HTTP::redirect "https://[HTTP::host][HTTP::uri]"
    }
    This iRule ensures all web traffic is encrypted by redirecting users to the HTTPS version of the site.
  • URI-based Pool Selection:
    Route traffic to different server pools based on the requested URI.
    when HTTP_REQUEST {
        if { [HTTP::uri] contains "aol" } {
            pool aol_pool
        } else {
            pool all_pool
        }
    }
    Requests containing "aol" in the URI go to the aol_pool, while all others use all_pool.
  • Block Requests to Sensitive Paths:
    Deny access to administrative URLs for security reasons.
    when HTTP_REQUEST {
        if { [HTTP::uri] starts_with "/admin" } {
            reject
        }
    }
    Any attempt to access URIs starting with /admin is rejected immediately.
  • User-Agent Based Routing:
    Send users to different server pools depending on their browser type.
    when HTTP_REQUEST {
        if { [HTTP::header "User-Agent"] contains "MSIE" } {
            pool /Common/IE_pool
        } elseif { [HTTP::header "User-Agent"] contains "Mozilla" } {
            pool /Common/Mz_pool
        }
    }
    Internet Explorer and Mozilla-based browsers are routed to separate backend pools.
  • Log Client IPs:
    Record the IP address of each connecting client for auditing or troubleshooting.
    when CLIENT_ACCEPTED {
        log local0. "[IP::client_addr] connected"
    }
    Creates a log entry each time a client establishes a connection, showing their IP.
  • Rewrite HTTP Headers:
    Modify or add custom HTTP headers on the fly.
    when HTTP_REQUEST {
        HTTP::header replace "X-Forwarded-Proto" "https"
    }
    Replaces or adds the X-Forwarded-Proto header to indicate secure protocol usage.

These examples illustrate just a few ways iRules empower granular, event-driven traffic control on F5 LTM devices. Each iRule can be further modified or combined to meet complex business, security, or technical requirements.

Blocking Specific URIs

F5 iRules make it easy to enforce access control policies by blocking requests to sensitive or restricted Uniform Resource Identifiers (URIs). Blocking specific URIs is often used to secure administrative dashboards, private APIs, or other sensitive application routes.

  1. Identify Sensitive or Restricted Paths:
    Determine the exact URI patterns (such as /admin, /private, or /config) that should be blocked from external user access.
  2. Create the iRule Using an HTTP Event:
    Use the HTTP_REQUEST event to inspect the incoming HTTP request URI and apply logic that blocks unwanted access.
  3. Use Logic to Match and Block:
    Insert conditional logic with if statements to check if the requested URI starts with or matches your restricted pattern. The reject command then drops the connection or request.
when HTTP_REQUEST {
    if { [HTTP::uri] starts_with "/admin" } {
        reject
    }
}

Explanation:

  • This iRule triggers on every HTTP request received by the F5 LTM.
  • It checks whether the requested URI starts with /admin.
  • If the condition is true, the reject command immediately terminates the connection, preventing access to sensitive paths.

Tips for Effective Blocking:

  • Use Regular Expressions: For more complex matching, such as variable paths or file extensions, you can use matches_regex in your condition.
  • Combine with IP Filtering: Only allow specific sources (like internal admin IPs) to access restricted URIs, blocking everyone else.
  • Log Attempted Access: Add logging for monitoring or investigating unauthorized access attempts.
    when HTTP_REQUEST {
        if { [HTTP::uri] starts_with "/admin" } {
            log local0. "Blocked attempt to /admin from [IP::client_addr]"
            reject
        }
    }

Using iRules to block specific URIs provides a fast, flexible way to tighten security without application code changes or backend server modifications.

Logging Client IPs

Monitoring and auditing client connections is a frequent requirement in both troubleshooting and security. With F5 iRules, you can log the source IP address of every client that connects to your virtual server, providing critical visibility into access patterns and potential threats.

  1. Select the Event:
    Use the CLIENT_ACCEPTED event, which triggers whenever a new TCP connection is established between a client and the BIG-IP LTM device.
  2. Retrieve the Client IP:
    Use the [IP::client_addr] command, which returns the source IP address of the connecting client.
  3. Log the Event:
    Use the log command to write the IP address to the local system log or a remote syslog server.
when CLIENT_ACCEPTED {
    log local0. "[IP::client_addr] connected"
}

Explanation:

  • The CLIENT_ACCEPTED event fires upon every new client connection.
  • [IP::client_addr] extracts the source IP address of the client.
  • log local0. writes the message to the F5 LTM's system log (typically /var/log/ltm).

Enhancements:

  • Log To Remote Syslog: Send log entries to a centralized syslog server for compliance or easier searching.
    when CLIENT_ACCEPTED {
        log 192.168.1.100 local0.info "[IP::client_addr] connected"
    }
    Replace 192.168.1.100 with your syslog server’s IP address.
  • Include Additional Details: Log not just the IP, but also port numbers, destination IP, or protocol as needed.
  • Rate-Limit Logging: Avoid log flooding by implementing conditional logic that limits excessive logging in high traffic environments.

Logging client IPs with iRules helps teams monitor access, investigate incidents, and support compliance—all directly from the F5 load balancer, without modifying application code or web servers.

Commonly Used Events

iRules operate by responding to specific events that occur during the lifecycle of client-server interactions. Understanding these events is essential to writing effective iRules that trigger at the right moment.

Event Name Description
CLIENT_ACCEPTED Triggered when a client TCP connection is accepted by the LTM, before any data is sent or received.
HTTP_REQUEST Fires when the full HTTP request headers have been received and parsed, allowing inspection and modification before forwarding to backend servers.
SERVER_CONNECTED Occurs when the LTM establishes a TCP connection to the selected backend server, enabling actions to be taken before data exchange.
HTTP_RESPONSE Triggers when the complete HTTP response headers are received from the backend server, allowing for response inspection or modification.
STREAM_MATCHED Activated when streaming payload data matches a specified pattern or condition, useful for deep inspection of data flows.

Selecting the appropriate event is crucial because it defines when your iRule logic executes. For example, use HTTP_REQUEST to modify or route web requests, while CLIENT_ACCEPTED is useful for connection-level logging.

Best Practices

To maximize the benefits of iRules while ensuring performance and maintainability, consider the following best practices when writing and deploying iRules on your F5 BIG-IP LTM:

  1. Keep iRules Simple and Focused:
    Avoid overly complex logic in a single iRule. Split different functionalities into separate iRules when appropriate for clarity and easier debugging.
  2. Prefer Built-in Features When Possible:
    Use native LTM profiles and functionality first before resorting to iRules. iRules should enhance, not replace, core platform features.
  3. Test Thoroughly in a Lab Environment:
    Always validate iRules on a non-production environment to ensure they work as expected and don’t introduce unintended side effects.
  4. Optimize for Performance:
    Minimize processing overhead by avoiding unnecessary loops, complex regular expressions, or excessive logging in high-traffic environments.
  5. Use Clear Comments and Documentation:
    Document your iRules thoroughly with inline comments and maintain a separate repository or change log so others can understand and maintain your code.
  6. Monitor Impact After Deployment:
    Keep an eye on CPU and memory usage post-deployment, as complex or inefficient iRules can affect load balancer performance.
  7. Limit the Number of Active iRules:
    Attaching too many iRules to a single virtual server can introduce latency. Combine related logic when appropriate.
  8. Use Event Appropriately:
    Choose the correct iRule event to reduce unnecessary execution. For example, don’t use HTTP_REQUEST events if you only need connection-level information.

By following these best practices, you can create robust, maintainable, and performant iRules that help you unlock the full power of your F5 LTM load balancer.

Conclusion

In this blog post, we've explored the powerful capabilities of F5 LTM load balancer iRules – what they are, how they work, and why they are an essential tool for granular traffic management and customization. We delved into key use cases such as custom routing, security enforcement, session persistence, and traffic modification, illustrating how iRules can adapt your application delivery to fit precise business and technical needs.

You learned the basic structure of an iRule, along with practical examples showing real-world implementations like HTTP redirects, URI blocking, and logging client IPs for auditing purposes. We also covered commonly used events that drive iRule execution and best practices to ensure your iRules are efficient, maintainable, and safe.

By leveraging iRules thoughtfully, you can extend the flexibility of your F5 BIG-IP LTM to solve complex challenges without waiting for code changes or vendor updates. Whether you’re enhancing security, optimizing traffic flows, or gaining deep visibility into your applications, iRules empower you to do it all with precision.

Thank you for joining this deep dive into F5 iRules! We hope this guide helps you confidently harness the power of your load balancer and inspires your next traffic management innovation. Happy scripting!