Most webshell hunts look for suspicious .php files. A file named b374k.php or c99.php sitting in a web directory is obvious. But what if no standalone malicious file exists on disk at all? Attackers can embed execution logic directly inside .htaccess using RewriteRule, AddHandler, AddType, or php_value directives, turning an innocent-looking image or text file into a live PHP backdoor. The server parses and executes it on every matching request, and traditional file scanners often skip .htaccess entirely.
This article walks through how Apache processes these directives internally, what the malicious patterns look like, how to find them with grep, and how to enable mod_rewrite tracing to confirm whether your server is silently executing injected code.
How Apache Processes .htaccess Internally
When a request arrives, Apache resolves the filesystem path for the URI, then walks the directory tree from the document root down to the target directory. At each level, if AllowOverride permits it, Apache reads and merges any .htaccess file it finds. This happens on every request (unless caching is configured), which is why .htaccess changes take effect immediately without a server reload.
The critical detail: .htaccess can contain directives that change how Apache handles files in that directory. Three categories matter here:
-
Handler mapping (
AddHandler,AddType,SetHandler): These tell Apache which module should process files with a given extension. If an attacker writesAddType application/x-httpd-php .icointo.htaccess, every.icofile in that directory gets parsed as PHP. Upload afavicon.icocontaining<?php eval($_POST['cmd']); ?>and you have a webshell with no.phpextension anywhere. -
RewriteRule with forced handler: mod_rewrite can internally rewrite a request to a different file or append a handler flag. A rule like
RewriteRule ^logo\\.png$ logo.png [T=application/x-httpd-php]forces Apache to treatlogo.pngas PHP. The[T=...]flag sets the MIME type, which selects the PHP handler. -
php_value directives: When PHP runs as an Apache module (mod_php),
.htaccesscan set PHP configuration values. The directivephp_value auto_prepend_file /tmp/.cache_xforces PHP to include and execute a file before every script in that directory. The prepended file can be stashed anywhere readable by the web server user.
All three techniques share one property: the malicious payload does not need a .php extension, and the .htaccess file itself looks like normal server configuration to anyone not reading it carefully.
What Malicious .htaccess Patterns Look Like
Attackers typically obfuscate just enough to survive a casual glance. Common patterns found in compromised .htaccess files:
AddHandler application/x-httpd-php .jpg .png .ico .txt— maps image or text extensions to PHP.SetHandler application/x-httpd-php— forces PHP handling for everything in the directory.RewriteRule .* - [T=application/x-httpd-php]— rewrites all requests to be treated as PHP.RewriteCond %{HTTP_USER_AGENT}with a specific string, followed by aRewriteRulethat proxies or redirects to an external payload. This variant only triggers for requests carrying a secret User-Agent header, making it invisible to normal browsing.php_value auto_prepend_fileorphp_value auto_append_filepointing to a hidden file.
Some attackers pad the .htaccess with hundreds of blank lines or comment lines before the malicious block, pushing it below the visible area of a text editor. Others base64-encode a payload and use RewriteRule to pipe it through a decoder.
Searching with grep
Start broad. Search every .htaccess file under your document root for handler-related directives and suspicious PHP configuration overrides:
# Find all .htaccess files and search for handler/rewrite/php directives
find /home -name '.htaccess' -exec grep -Hn -iE '(AddHandler|AddType|SetHandler|auto_prepend_file|auto_append_file|x-httpd-php|application/x-httpd-php|\\[T=)' {} \\;
This prints the filename, line number, and matching line. Legitimate .htaccess files rarely contain AddHandler for image extensions or auto_prepend_file. Any match deserves manual inspection.
For RewriteRule-based attacks that conditionally trigger on User-Agent or query string:
# Search for RewriteCond targeting User-Agent or specific query patterns
find /home -name '.htaccess' -exec grep -Hn -iE '(RewriteCond.*HTTP_USER_AGENT|RewriteCond.*QUERY_STRING|base64_decode|eval\\()' {} \\;
Also check for .htaccess files in unexpected locations. A file at /home/user/public_html/wp-content/uploads/.htaccess that contains handler directives is suspicious — the uploads directory typically only needs rules to deny script execution, not enable it.
On shared hosting servers or cPanel environments, .htaccess files can exist in every account's directory tree. Running these searches server-wide (starting from /home) catches injections across all accounts.
For deeper context on hunting post-compromise .htaccess injections, see Auditing .htaccess Files for Injected Redirects After a cPanel Server Compromise.
Enabling mod_rewrite Trace Logging
Finding a suspicious directive is step one. Confirming it actually executes on incoming requests requires mod_rewrite trace logging.
In Apache 2.4, the old RewriteLog and RewriteLogLevel directives no longer exist. Instead, rewrite tracing uses the unified LogLevel directive inside a VirtualHost block or the main server config:
# Add inside the relevant <VirtualHost> block, not in .htaccess
LogLevel alert rewrite:trace3
Trace levels range from trace1 (minimal) to trace8 (extremely verbose). Level trace3 typically shows each rule evaluation, whether conditions matched, and what substitution occurred. This is enough to see if a RewriteRule with a [T=application/x-httpd-php] flag is firing.
After adding the directive, reload Apache (apachectl graceful or systemctl reload apache2). Then check the error log:
- Debian/Ubuntu: typically
/var/log/apache2/error.log - RHEL/CentOS: typically
/var/log/httpd/error_log - cPanel: typically
/var/log/apache2/error_logor per-domain logs under/var/log/apache2/domlogs/
The exact path depends on your configuration.
With tracing active, send a request to the suspected path (for example, curl -s -o /dev/null -w '%{http_code}' https://example.com/wp-content/uploads/logo.png) and watch the error log. If mod_rewrite is applying a handler override, you will see log lines showing the rule match, the [T=...] flag application, and the resulting internal redirect to the PHP handler.
Sample output format (illustrative, actual format varies):
[rewrite:trace3] [pid 12345] mod_rewrite.c(XXX): [client 192.0.2.1:54321] 192.0.2.1 - - [example.com/sid#...][rid#.../initial] applying pattern '.*' to uri '/wp-content/uploads/logo.png'
[rewrite:trace3] [pid 12345] mod_rewrite.c(XXX): [client 192.0.2.1:54321] 192.0.2.1 - - [example.com/sid#...][rid#.../initial] forcing type application/x-httpd-php
If you see "forcing type application/x-httpd-php" for a non-PHP file, that confirms the .htaccess directive is live and the server is executing the file as PHP.
Important: Rewrite tracing generates significant log volume on busy servers. Enable it temporarily for diagnosis, then set it back to LogLevel alert or your normal level when done.
The Request Flow, Step by Step
To understand why this is hard to catch, trace a single request through the engine:
- Client sends
GET /wp-content/uploads/logo.png HTTP/1.1with a specific User-Agent string. - Apache resolves the path to
/home/user/public_html/wp-content/uploads/logo.png. - Apache walks the directory tree, reading
.htaccessat each level. In/wp-content/uploads/.htaccess, it finds aRewriteCondmatching the User-Agent and aRewriteRulewith[T=application/x-httpd-php]. - mod_rewrite evaluates the condition — User-Agent matches. The rule fires. Apache internally marks the response type as
application/x-httpd-php. - Apache's content handling phase sees the PHP MIME type and passes the file to mod_php (or php-fpm via mod_proxy_fcgi, depending on configuration).
- PHP parses
logo.png, finds embedded<?php ... ?>tags, and executes them. - The response goes back to the client. The access log shows a normal
200forlogo.png. Nothing in the log suggests PHP execution occurred.
This is why access logs alone do not reveal the attack. The request looks like a normal image fetch. Only the rewrite trace log or manual .htaccess inspection exposes it.
If the attacker uploaded the disguised payload through a vulnerable upload endpoint, the upload itself may also be hard to spot in logs. For techniques on finding those upload events, see Webshell Uploaded but No Suspicious File in access_log? Search POST Requests to Upload Endpoints.
Remediation and Prevention
Once you confirm a malicious .htaccess directive:
- Remove or comment out the malicious lines. Check the file modification timestamp (
stat .htaccess) and compare it against known deployment dates. - Find and remove the payload file (the
.png,.ico, or whatever file contains the PHP code). Search for PHP tags inside non-PHP files:grep -rl '<?php' /home/user/public_html/wp-content/uploads/. - Check how the
.htaccesswas modified. Look at FTP/SFTP logs, cPanel file manager logs, or the access log for POST requests to vulnerable scripts (plugin uploaders, theme editors, etc.). - Restrict
AllowOverridein your Apache configuration. If a directory (likeuploads) should never execute scripts, setAllowOverride Noneand addSetHandler noneorphp_admin_flag engine offin the vhost config (not in.htaccess, since an attacker who can write.htaccesscan override it). Thephp_admin_flagandphp_admin_valuedirectives can only be set in server config or vhost context, not.htaccess, making them resistant to this attack. - On servers running php-fpm instead of mod_php,
php_valuedirectives in.htaccesshave no effect. This removes one attack vector but does not preventAddHandlerorSetHandlerabuse.
The core takeaway: scanning for .php files is not enough. Any .htaccess audit must include handler directives, rewrite flags, and PHP configuration overrides. Pair periodic grep sweeps with restrictive AllowOverride settings, and use mod_rewrite tracing when you need to confirm whether a suspicious rule is actively executing.