Recently, I was working through an issue where I wanted to conditionally increase PHP’s memory limit based on the request URL. Rather than building that logic into the application, handling via Apache directives seemed like a cleaner approach. Here I’ll outline how I achieved this.
Typically, in order to change configuration directives for certain URLs you should declare them inside a
<LocationMatch> use slightly different mechanics for matching the request URL against the supplied string.
<LocationMatch> is easy to understand, it simply interprets the string provided as a PCRE regular expression. The below would match any URL containing the string “api” in the path.
<LocationMatch "api"> php_value memory_limit 1G </LocationMatch>
The rules for the
<Location> section are a bit more tricky. They can be found in the Apache documentation..
The enclosed directives will be applied to the request if the path component of the URL meets any of the following criteria:
- The specified location matches exactly the path component of the URL.
- The specified location, which ends in a forward slash, is a prefix of the path component of the URL (treated as a context root).
- The specified location, with the addition of a trailing slash, is a prefix of the path component of the URL (also treated as a context root).
There are a few examples in the link above.
Apache provides a few other methods for applying directives at a specific scope, the
The important thing to understand is that these directives only apply to physical locations on disk. Typically, dynamic applications route requests to a single entry point (e.g. index.php) which is then responsible for passing the request along to the appropriate controller. As a result, these directives are almost certainly not what you’re looking for.
All Apache directives have an associated context, which defines where these directives can legally be included. While
<FilesMatch> are allowed in
<LocationMatch> are not. You must include these directives inside
<VirtualHost> containers in your server configuration files. The good news is you can simply gracefully reload Apache after making the required changes.
I hope this post came in useful for some people. If you have any questions or comments, feel free to drop a note below, or, as always, you can reach me on Twitter as well.
Hi, I'm Max!
I'm a software developer who mainly works in PHP, but also dabbles in Ruby and Go. Technical topics that interest me are monitoring, security and performance.
During the day I solve challenging technical problems at Something Digital where I mainly work with the Magento platform. I also blog about tech, work on open source and hunt for bugs.
I built a tool called Domain Clamp which monitors and alerts about expiring domains and SSL certificates.
If you'd like to get in touch with me the best way is on Twitter.