Path Traversal Pattern Regex for Python
/(?:\.\./|\.\.\\|%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 Python. 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 Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.
Python Implementation
# Path Traversal Pattern
# ReDoS-safe | RegexVault — Security > Injection Patterns
import re
path_traversal_pattern_pattern = re.compile(r'(?:\.\./|\.\.\\|%2e%2e%2f|%2e%2e/|\.%2e/|%2e\./|%252e%252e|\.\.%c0%af|\.\.%c1%9c|\.\./|%00|\.php\x00|\.asp\x00)')
def validate_path_traversal_pattern(value: str) -> bool:
return bool(path_traversal_pattern_pattern.fullmatch(value))
# Example
print(validate_path_traversal_pattern("../../etc/passwd")) # TrueTest 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 Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. 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