When you need precise protection against specific attacks—such as malicious API calls, suspicious requests, or high-frequency scanning—use custom rules to build tailored protection strategies with flexible match conditions and rule actions.
Key concepts
custom rule: A protection module within Core Web Protection. To enable this module, you must create a protection template. You can create multiple protection templates.
protection template: A set of protection rules that defines their content and scope. A protection template consists of a template type, protection rules, and apply-to objects.
Template type: You must specify a type when you create a protection template, and you cannot change its type after creation. Two template types are available:
Template type
Description
Use cases
Default protection template
By default, the template applies to all existing and new protected objects and protected object groups.
You can manually exclude specific objects by setting their status to "Not Applied".
You can create only one default protection template within the custom rule module.
Deploy global, general-purpose protection rules.
Custom protection template
You must manually specify which protected objects or protected object groups the template applies to.
Deploy fine-grained protection rules for specific services, such as login or payment APIs.
protection rule: Defines the specific detection logic and response action. A protection template can contain multiple protection rules. Each rule consists of the following components:
match condition: Defines the request characteristics to inspect, such as the request path or the client IP address.
Protection Type: Supports three detection dimensions: Access Control, Rate Limiting, and Extension Execution.
rule action: Defines the action to take when a request matches a rule. The actions are prioritized from highest to lowest: Block, Strict CAPTCHA, CAPTCHA, JavaScript Validation, and Log.
NoteIf a request matches multiple rules that have the same rule action within the same protection module, WAF randomly applies one of the matching rules.
apply-to object: Specifies the target of a protection template. You can use this setting to apply protection rules to specific protected objects or protected object groups. A protected object or protected object group can be associated with multiple protection templates.
protected object: The system automatically creates a protected object for each domain or cloud service instance that you add to WAF.
protected object group: You can add multiple protected objects to a group for centralized management.
Procedure
Before you begin, ensure that you have added your web service to Web Application Firewall (WAF) and that a protected object exists. If you have not added your service, see Add a domain to WAF.
Log on to the Web Application Firewall (WAF) console. In the top navigation bar, select the resource group and region (Chinese Mainland or Outside Chinese Mainland) of your WAF instance. In the left-side navigation pane, choose .
Step 1: Configure template type
On the Core Web Protection page, find the Custom Rule section and click Create Template. In the Create Template panel, configure the following parameters.
Template Name: Enter a name for the template.
Save as Default Template: You can set only one default template in the custom rule module, and you can set it only when you create a new template.
Yes: You do not need to configure an Apply To. When the template is created, it applies to all protected objects and object groups by default. It also automatically applies to new objects that are added later. You can manually exclude specific objects by setting their status to 'Inactive'.
No: You must set the Apply To to manually specify the protected objects or object groups.
Step 2: Add protection rules
In the Rule Configuration area, click Create Rule and configure the following parameters.
Rule Name: Enter a name for the rule.
Match Condition: Defines the request characteristics that the rule inspects. Click Add Condition to add a condition. Each condition consists of a Match Field, Logical Operator, and Match Content. The following table provides configuration examples.
NoteIf a rule contains multiple conditions, a request must match all conditions (a logical AND relationship) to trigger the rule. You cannot configure a logical OR relationship between conditions. To block requests that match any one of several keywords or characteristics (for example, keyword A or keyword B), create a separate protection rule for each condition. For more information about match fields and logical operators, see Match conditions.
Match Field
Logical Operator
Match Content
Description
URI Path
Contains
/login.phpThe rule matches if the request path contains
/login.php.IP
Belongs To
192.1.XX.XXThe rule matches if the client IP address is
192.1.XX.XX.NoteComplex match rules
1. Multi-value matching logic and limits
To apply the same rule to multiple API endpoints, you can use logical operators that support multiple values, such as Contains One of Multiple Values, Equals One of Multiple Values, Does Not Contain Any Value, or Does Not Equal Any Value. The configuration requirements are as follows:Delimiter: You must use a comma (,) to separate multiple match values. The system splits the values by commas and processes them independently.
Quantity and deduplication: You can enter up to 50 values. Duplicate values are not allowed.
2. Handling special characters
If the match content contains a comma (for example, in some User-Agent strings), the system may misinterpret it as a multi-value delimiter, causing the match to fail. In this case, do not use multi-value logical operators. We recommend the following alternatives:Regular expression matching: Matches content using a regular expression and treats commas as literal characters.
Single rule: Create a separate rule for the specific string and use a single-value logical operator.
3. Regex application examples
Match a specific version number range: To match Chrome browser versions between 100 and 200, set the match field to
User-Agent, the logical operator to Regex Match, and the match content toChrome/(1[0-9]{2}|200)\..Block multiple URL encodings: To block requests that are URL-encoded multiple times, for example, where
%is encoded as\x25, set the logical operator to "Regex Match" and the match content to\x25.*\x25.
4. Recommendations for production environments
When you configure complex match conditions like regular expressions in a production environment, we recommend that you first use the Monitor action or a canary test to verify the rule's behavior. After you confirm that there are no issues, you can apply the rule to all traffic.Protection Rule Type: Three types are supported: Access Control, Rate Limiting, and Extension Execution.
Access Control: Ideal for scenarios that require precise control over specific types of requests.
Rate Limiting: Ideal for scenarios that require protection based on access frequency, such as preventing credential stuffing and brute-force attacks. This feature is available only on subscription (Enterprise or Ultimate Edition) and pay-as-you-go WAF instances.
Extension Execution: Ideal for personalized security scenarios that require custom Lua scripts to implement complex business logic. We recommend that you configure extensions first.
Access control
Configure an access control rule to perform a specified action on individual requests that meet specific conditions.
Rate limiting
Configure a rate limiting rule to restrict excessive access from clients.
Rate detection conditions: If the number of times a single Statistical Object matches the rule within the specified Statistical Interval (Seconds) exceeds the configured Threshold (Times), WAF triggers the blacklist action.
Parameter
Description
Statistical Object
Select the object for which to measure request frequency. Options include:
IP: Measures the request frequency from a single IP address. If you deploy a Layer 7 proxy, such as a CDN or Anti-DDoS, in front of WAF, ensure that you set the Is a Layer 7 proxy (such as Anti-DDoS/CDN) deployed before WAF? parameter to Yes when you add the asset to WAF. Incorrect configuration prevents WAF from obtaining the real client IP address, and IP-based rules will fail.
Custom Header: Groups requests by the value of a custom request header, such as
Referer, and measures the request frequency for each group with the same header value within the specified time period.Custom Parameter: Measures the request frequency for requests that contain a specific parameter in the URL. For example, if the parameter is
user_id, WAF measures the frequency of requests with the sameuser_idvalue.Custom Cookie: Measures the frequency of HTTP requests that contain a specific cookie within the specified time period. For example, if the custom cookie name is User, WAF counts the occurrences of each User value within the time period.
Session: WAF establishes a session ID by setting a cookie named
acw_tcin the response and measures client request frequency based on this cookie's value.Account: Measures the request frequency from the same account. You must configure User Identification on the Protected Objects page before you can use this option. For more information, see Configure protected objects and protected object groups.
Statistical Interval (Seconds)
Set the statistical period in seconds.
Threshold (Times)
Set the maximum number of times the Statistical Object is allowed to match the Match Condition within the Statistical Interval (Seconds).
Status code detection conditions: If the Quantity or Percentage (%) of responses with a specific Status Code exceeds the configured threshold, WAF triggers the blacklist action. If you enable status code detection, the statistical object must meet both rate detection and status code conditions to trigger the action.
Parameter
Description
Status Code
Set the status code to count.
Quantity
Set the maximum number of times the specified Status Code can appear in responses within the statistical period.
Percentage (%)
Set the maximum percentage of responses with the specified Status Code within the statistical period.
Blacklist action conditions: Adds statistical objects that meet the preceding detection conditions to a blacklist. For the duration of the Timeout Period, WAF applies the configured Rule Action to requests from the blacklisted object that fall within the Apply To scope.
Parameter
Description
Apply To
Set the scope for the blacklist action. Options include:
Current Match Condition: The action applies only to requests that meet the Match Condition of the current rule.
Protected Object: The action applies to all requests from the statistical object, such as an IP address, to the current protected object.
Timeout Period
Set the duration of the blacklist action. Unit: seconds. Value range: 60 to 86400.
Extension execution
Select from your configured extension rules to implement personalized security controls.
NoteExtension Execution rules support only two rule actions: Block and Log.
Rule Action: Select the action to perform when a request matches the rule.
Parameter
Description
JavaScript Validation
WAF returns a JavaScript snippet to the client for validation. A standard browser automatically executes this code. If the client's browser executes the code successfully, WAF allows all requests from that client for a period (30 minutes by default). Otherwise, WAF blocks the requests.
Block
Blocks requests that match the rule and returns a block response page to the client.
NoteWAF uses a default block page. You can also use the Custom Response feature to customize the block page.
Log
Allows requests that match the rule but records the match in the logs. When you test a new rule, you can first use the Log mode to analyze WAF logs and confirm that the rule does not block legitimate requests, and then switch to a different rule action.
CAPTCHA
WAF returns a CAPTCHA page to the client. If the client successfully completes the CAPTCHA, WAF allows all requests from that client for a period (30 minutes by default). Otherwise, WAF blocks the requests.
NoteFor a WAF instance that uses the pay-as-you-go billing method, this rule action incurs additional fees. For more information, see Pay-as-you-go billing details.
Strict CAPTCHA
WAF returns a CAPTCHA page to the client. If the client successfully completes the CAPTCHA, WAF allows the request. Otherwise, WAF blocks it. In this mode, every request from the client that matches this rule requires CAPTCHA verification.
NoteFor a WAF instance that uses the pay-as-you-go billing method, this rule action incurs additional fees. For more information, see Pay-as-you-go billing details.
NoteThe CAPTCHA action is available only on subscription (Enterprise or Ultimate Edition) and pay-as-you-go WAF instances.
JavaScript Validation and CAPTCHA actions apply only to synchronous requests. For asynchronous requests, such as those made with XMLHttpRequest or the Fetch API, you must inject the Web SDK. Otherwise, these features will not work correctly. For more information, see the JavaScript validation and CAPTCHA sections in Bot management.
After you enable JavaScript Validation or CAPTCHA and the client passes the verification, WAF uses Set-Cookie to set a cookie named
acw_sc__v2(for JavaScript Validation) oracw_sc__v3(for CAPTCHA) in the response header. The client then includes this identifier in the Cookie header of subsequent requests.
Advanced Settings (Optional): The following advanced features are available only for WAF instances of Enterprise Edition or Ultimate Edition that use the subscription billing method, and for pay-as-you-go WAF instances.
Parameter
Description
Canary Rule
Configure the percentage of traffic to which the rule applies, based on a specified dimension.
After you enable a canary rule, you must also set the Dimension and Canary Release Proportion. Valid values for Dimension are IP, Custom Header, Custom Parameter, Custom Cookie, and Session.
NoteA canary rule takes effect based on the configured Dimension, rather than being randomly applied to a percentage of all requests. For example, if you set Dimension to IP and Canary Release Proportion to 10%, WAF selects approximately 10% of all IP addresses. WAF then applies the rule to all requests from the selected IP addresses, not to a random 10% of all requests.
Effective Mode
Permanently Effective (Default): The rule is always in effect when the protection template is enabled.
Fixed Schedule: The rule is in effect only during a specified time period.
Recurring Schedule: The rule is in effect only during a specified recurring time cycle.
Step 3: Set apply-to objects
In the Apply To area, select the protected objects and protected object groups to which you want to apply the template.
How the template is applied depends on the configuration you made in Step 1:
If you set the template as the default protection template: You do not need to configure apply-to objects. The template is applied to all existing and new protected objects and protected object groups by default. You can manually exclude specific objects by setting their status to "Not Applied".
If you did not set the template as the default protection template: You must manually specify the protected objects and protected object groups to which the template applies.
You can manually adjust the application status for protected objects or protected object groups both during and after template creation.
Protection rule configuration examples
The following configuration examples are for reference only. Before you deploy rules in a production environment, you must adjust them based on your actual business traffic and attack patterns. Directly copying and applying these examples may cause business disruption or ineffective protection.
Restrict admin panel access to specific IP addresses
Block all access requests to the /wp-admin path, and allow only requests from the administrator's IP address, 192.1.XX.XX.
Match Condition:
Set Match Field to
IP, Logical Operator toNot Belong To, and Match Content to the administrator's allowlisted IP address192.1.XX.XX.Set Match Field to
URI Path, Logical Operator toContains, and Match Content to the path you want to restrict access to:/wp-admin.
Protection Rule Type: Access Control.
Rule Action: Block.
Allowlist an IP address to test a domain
Allow only a specific allowlisted IP address to access a test domain that is added to WAF, and block all other public traffic.
Match Condition:
Set Match Field to
IP, Logical Operator toNot Belong To, and Match Content to the allowlisted IP address range, such as203.xx.xx.200/32.Set Match Field to
Host, Logical Operator toEquals, and Match Content to the test domain, such astest.example.com.
Protection Rule Type: Access Control.
Rule Action: Block.
Block requests with a mismatched host header
If a request's Host header does not match your legitimate business domain, you can use the following rule to block it. This helps reduce the risk of CC attacks or malicious probing.
Match Condition:
Match Field:
Host.Logical Operator:
Not Equal To.Match Content: Enter the legitimate domain name used by your business.
Protection Rule Type: Access Control.
Rule Action: Block.
Block malicious crawlers and scanners
When you configure custom rules, you can use the following common User-Agent (UA) patterns to identify different types of traffic:
Security scanning tools: Such as
sqlmap,nmap, andnikto, which are commonly used for vulnerability scanning.Automated scripts and libraries: Such as
python-requests,Python-urllib,curl/, andWget/, which are often used for scripted calls or non-browser access.Data scraping crawlers: Such as
MJ12bot,AhrefsBot, andSemrushBot, which are used for SEO analysis or content scraping.Mainstream search engines: Such as
Googlebot,Baiduspider, andbingbot.Mobile identifiers: Such as
Mobile,Android,iPhone, andiPad.
Relying solely on the UA field is not a reliable way to identify malicious traffic because attackers often spoof their UA to mimic normal browsers. When you configure custom rules, we recommend that you also consider IP reputation, access frequency, and WAF logs for a comprehensive assessment to avoid blocking legitimate business requests.
The following example blocks HTTP requests where the UA field contains the string bot.
Match Condition: Set Match Field to
User-Agent, Logical Operator toContains, and Match Content to the UA patternbot.Protection Rule Type: Access Control.
Rule Action: Block.
Use human verification to block bots
Enable JavaScript validation for a request path under malicious attack, such as /index.php, to block automated attack tools without affecting normal browser access.
For static pages, you can configure JavaScript validation or CAPTCHA rules to ensure that requests originate from standard browsers that can execute JavaScript. These verification methods apply only to synchronous requests and are not suitable for asynchronous requests, such as those made with XMLHttpRequest or the Fetch API.
For backend-only API endpoints used for service-to-service communication, we do not recommend configuring Run JavaScript Validation. Run JavaScript Validation relies on a browser environment to execute. API clients are typically server-side programs or automated scripts that cannot parse and execute JavaScript, which would continuously block legitimate requests. When you configure match conditions, we recommend that you exclude API endpoints from the scope of Run JavaScript Validation.
Match Condition: Set Match Field to
URI Path, Logical Operator toContains, and Match Content to/index.php.Protection Rule Type: Access Control.
Rule Action: Run JavaScript Validation or Run Slider CAPTCHA.
To enable JavaScript validation for all request paths, you can set the match content to /. Because this configuration applies to all requests, we recommend following the principle of least privilege by precisely defining the rule's scope and using global matching with caution.
Rate limit API endpoints
Enable rate limiting for all API endpoints except example.com/api/pay. This example assumes that all API endpoint URIs contain the string /api.
Match Condition:
Set Match Field to
URI Path, Logical Operator toNot Equal To, and Match Content to/api/pay.Set Match Field to
URI Path, Logical Operator toContains, and Match Content to/api.
Protection Rule Type: Rate Limiting.
Statistical Object: IP.
Statistical Interval (Seconds): 10.
Threshold (Times): 5.
Apply To: Current Match Condition.
Timeout Period: 1800.
Rule Action: Block.
Production deployment
To avoid disrupting your business, do not create and enable protection rules that use the Block action directly in a production environment. We recommend that you follow this deployment process.
Analyze request characteristics: Use WAF security reports and logs to identify the characteristics of legitimate business requests and malicious attacks, such as IP address, User-Agent, Header, and URI. If you plan to configure a rate limiting rule, you must also determine the baseline request frequency for your normal business traffic.
Configure an allowlist: Before you create a custom rule template, we recommend that you create an allowlist rule to add trusted IP addresses to the allowlist. This prevents new rules from blocking trusted requests.
Perform canary testing: After you create a custom rule, use one of the following methods to test it before you deploy it to the production environment.
Apply the rule to a non-production environment for testing.
Set the Rule Action to Log.
Enable Canary Rule in the Advanced Settings.
Analyze test results: After the rule runs for a period, check the security reports and logs for false positives among the matched requests.
Apply to production: After you confirm that the false positive rate is acceptable, change the rule action to the intended action and apply the rule to your production environment.
Continuously monitor and optimize: Monitor the security reports and logs. Dynamically adjust and optimize your rules based on business traffic changes and their effectiveness.
Daily operations
Manage protection templates
New protection templates are enabled by default. You can perform the following operations in the protection template list:
View the number of associated Protected Object/Group entries for a template.
Enable or disable a template by using the Status switch.
Click Create Rule for the template.
Edit, Delete, or Copy a protection template.
Click the
icon to the left of a protection template name to view the rules in the template.
Manage protection rules
New rules are enabled by default. You can perform the following operations in the rule list:
View information such as the Rule ID and Rule Condition.
Enable or disable a rule by using the Status switch.
Edit or Delete a rule.
Quotas and limits
Only WAF instances of Enterprise Edition or Ultimate Edition that use the subscription billing method, and pay-as-you-go WAF instances, support the CAPTCHA, Rate Limiting, and Advanced Settings features.
A single protection rule can have a maximum of five Match Condition.
When you use logical operators such as Equals One of Multiple Values or Contains One of Multiple Values, you can enter a maximum of 50 match content values. To match more than 50 values, we recommend that you either split them into multiple rules or use operators such as Contains or Regex Match.
A rule qualifies as an "advanced rule" if it meets any of the following conditions. For subscription WAF instances, advanced rules are supported only by Enterprise Edition and higher. For pay-as-you-go WAF instances, WAF bills advanced rules differently from basic rules. For pricing details, see Pay-as-you-go billing details.
Rule type is rate limiting.
Uses match fields: Cookie, Content-Type, Content-Length, X-Forwarded-For, Body, Http-Method, File Extension, Filename, Server-Port, Header, Cookie Name, or Body Parameter.
Uses logical operators: Regex Match or Regex Not Match.
Uses advanced settings: rule grayscale or effective time pattern.
FAQ
Why is my rule not working?
If a configured WAF custom rule does not work as expected, or if the number of intercepted requests is significantly lower than expected, we recommend that you systematically troubleshoot the issue in the following areas.
Check basic configuration and status
Verify protected object association: Verify that you have correctly created and associated the custom rule template with the target Protected Object/Group (such as an ALB instance or a domain name). Ensure its status is Effective; otherwise, WAF cannot deliver and execute the rule.
Check the template and rule status: Check that both the protection template's Status switch and the specific rule's Status switch are turned on. If either switch is off, the corresponding rule will be inactive.
Verify the rule action: Confirm that the rule's Rule Action is set to something other than Log. The Log action only records events and does not block requests.
Validate match conditions and logic
Match condition accuracy: Thoroughly check whether the rule's Match Field, Logical Operator, and Match Content correctly match the target requests. If you use a regular expression, strictly verify that you wrote escape characters correctly.
Strategy for dynamic paths: If the target path contains dynamically generated random segments (such as random parameters or IDs), we recommend setting the match field to
URI Pathand using the Contains logical operator to match only the fixed, unchanging string in the path. Avoid matching the full path, as dynamic changes can cause the rule to fail.Handling missing headers: For request header fields that might be missing, such as
RefererorUser-Agent, note that "the field's value is empty" and "the field does not exist in the request header" are two different logical states. We recommend configuring conditions for both logical states to prevent the rule from failing due to an unhandled state.
Check rule priority and trigger conditions
Other rules may take precedence: Check for other configured protection rules or modules. For example, if an allowlist rule is configured, a request might pass before your block rule can evaluate it.
Rate limiting with status code conditions: If you configure a Rate Limiting rule and enable status code detection, WAF triggers the rule only if the statistical object meets both the "access frequency threshold" and "status code characteristics" conditions within the statistical period. You need to confirm that the origin server actually returns the specified status code (such as 404) for the relevant requests. Otherwise, WAF will not trigger the rule even if the access frequency reaches the threshold.
Rate limit a domain on a shared instance
Rate limiting rules restrict the request frequency of a single statistical object based on the protected object. If a single cloud service instance handles traffic for multiple domains, WAF aggregates the access frequency across all domains for statistical purposes. If you need to limit the access frequency for only a specific domain, you can use one of the following methods:
Add the domain as a WAF protected object and apply the rate limiting rule to that object. For more information, see Configure protected objects and protected object groups.
In the Match Condition of the rate limiting rule, use the Host field to specify the domain for which you want to limit access frequency.
Troubleshooting the body parameter match field
The likely reason is that the match content is too short. When you use the Body Parameter field, make sure the match content is at least five characters long. Otherwise, WAF cannot detect the traffic.
How to protect against nighttime attacks
For services with minimal legitimate traffic at night, you can configure stricter protection rules to defend against attacks. To do this, set the rule's Effective Mode to Recurring Schedule and select the correct Time Zone to apply precise protection during nighttime hours.
If your service does not cater to users in specific regions (for example, if it only serves domestic users), you can also configure regional blocking rules to directly block access requests from those regions, thereby blocking anomalous traffic.
Allow specific requests and block others
Configuration logic for allowing specific requests and blocking all others
WAF custom rules use a "match and trigger" logic, which does not directly support a positive allowlist model of "allow only specified requests, block all others". To implement this security policy, you must use reverse logic: "block all requests that do not match the allow criteria". For a specific configuration method, see Restrict admin panel access to specific IP addresses.
Differences between WAF and Cloud Firewall ACLs
WAF differs fundamentally from Cloud Firewall ACLs and ECS security groups in its defense model:
Cloud Firewall ACL: Configured based on fixed and enumerable "business intents". For example, you can restrict an internal database to allow access only from specific application server IP addresses. It uses a "deny all by default, allow by exception" strategy to precisely reduce the network attack surface.
WAF: Provides defense based on signatures and behavior, primarily for HTTP/HTTPS requests. Web application traffic is highly complex, involving numerous dynamic requests and user interactions. If you were to adopt a "deny all, allow by exception" strategy in WAF, you would need to enumerate all legitimate request characteristics, such as URLs, parameters, and headers. This strategy is not only difficult to implement but also extremely costly to maintain.
Recommended fine-grained WAF strategies
Given these differences, we do not recommend configuring a global "block all, allow specific" rule in WAF. Instead, adopt the following fine-grained configuration strategy:
Precise access control: For sensitive paths like admin panels or core API endpoints, configure precise access control rules based on IP address, User-Agent, or specific headers to enforce strict access control.
Baseline protection: For regular traffic from the public, rely on WAF's Core Web Protection rules and CC protection modules to identify and block known attack patterns and anomalous behaviors, rather than using a blanket block.
Continuous tuning: Regularly analyze WAF event logs. Continuously iterate and refine your access control rules based on changes in business traffic and the threat landscape to ensure a balance between security and business availability.
Using the contains operator to avoid duplicate rules
When you set the match field to URI Path and the logical operator to Contains, a request matches if the specified string appears anywhere in the request path.
Example: If you enter /resources/author/ as the match content, it can match multilingual paths such as /cn/resources/author/ and /en/resources/author/.
Use case: For multi-level directories or multilingual sites that share a common, fixed path segment, this method can effectively reduce the need for duplicate rules.