Path Traversal Pattern Regex for Java
/(?:\.\./|\.\.\\|%2e%2e%2f|%2e%2e/|\.%2e/|%2e\./|%252e%252e|\.\.%c0%af|\.\.%c1%9c|\.\./|%00|\.php\x00|\.asp\x00)/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching path traversal pattern, ported and verified for Java. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.
Java Implementation
// Path Traversal Pattern
// ReDoS-safe | RegexVault — Security > Injection Patterns
import java.util.regex.Pattern;
public class PathTraversalPatternValidator {
private static final Pattern PATTERN =
Pattern.compile("(?:\\.\\./|\\.\\.\\\\|%2e%2e%2f|%2e%2e/|\\.%2e/|%2e\\./|%252e%252e|\\.\\.%c0%af|\\.\\.%c1%9c|\\.\\./|%00|\\.php\\x00|\\.asp\\x00)");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("../../etc/passwd")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
../../etc/passwd | /var/www/html/index.html |
%2e%2e%2f | uploads/profile.jpg |
../../../ | C:\Users\Public\Documents |
..%c0%af | — |
%00injection | — |
When to use this pattern
This pattern is drawn from the Security > Injection Patterns category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Path traversal defense must happen AFTER URL decoding. A filter that blocks ../ before decoding will miss %2e%2e%2f. Use the real path function (os.path.realpath in Python, path.resolve in Node.js) and verify it starts with the intended base directory.
Technical Notes
Path traversal (directory traversal) allows attackers to read files outside the intended directory. Double encoding (%252e = %) is used to bypass naive decoders. Null byte (%00) terminates strings in some C-based systems. Real defense: use path canonicalization and compare against the allowed base directory.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern