
Mod Rewrite rules are the backbone of the Apache mod_rewrite module, allowing you to manipulate URLs and create custom redirects.
The most basic RewriteRule format is "RewriteRule pattern substitution [flags]", which is used to define a new rule. This format is used in the example "RewriteRule ^/?index\.html$ / [R=301,L]".
A RewriteRule can be made more specific by adding flags, such as the "L" flag, which stands for "last", and the "R" flag, which stands for "redirect". The "R=301" flag, for example, is used to specify a permanent redirect.
The RewriteRule pattern can also be made more complex by using regular expressions. For example, the pattern "^/?index\.html$" matches the URL "/index.html" or "/index.html/" exactly.
Intriguing read: R E P O Mods
Regular Expressions
Regular Expressions are a powerful tool in mod rewrite, allowing you to match and manipulate patterns in URLs. They're used to create complex rules, but don't worry, we'll break them down into manageable bits.
A dot (.) matches any character, while an asterisk (*) matches zero or more of the previous symbol. You can also use a plus sign (+) to match one or more of the previous symbol, and a question mark (?) to match zero or one of the previous symbol.
Special characters have special meanings, but you can escape them with a backslash (\). For example, a caret (^) matches the start of a string, and a dollar sign ($) matches the end of a string.
You can also group patterns together using parentheses, which creates a special variable that can be used later. For example, (pattern) groups the pattern and makes it available for later use.
Here's a list of special characters and their meanings:
- . (full stop) - match any character
- * (asterisk) - match zero or more of the previous symbol
- + (plus) - match one or more of the previous symbol
- ? (question) - match zero or one of the previous symbol
- \? (backslash-something) - match special characters
- ^ (caret) - match the start of a string
- $ (dollar) - match the end of a string
- [set] - match any one of the symbols inside the square braces.
- [^set] - match any symbol that is NOT inside the square braces.
- (pattern) - grouping, remember what the pattern matched as a special variable
- {n,m} - from n to m times matching the previous character (m could be omitted to mean >=n times)
In practice, I've found that using groups to capture patterns can be really helpful. For example, if you're trying to match a URL like /test/1234, you can use a group to capture the id (1234) and then use that group in a later part of the rule.
Rule Basics
A RewriteRule consists of three main arguments: Pattern, Substitution, and flags. The Pattern is a regular expression that matches incoming URLs.
The Pattern is initially matched against the URL-path of the incoming request, which is the part of the URL after the hostname but before any question mark. This means it's matched against the path before any query string is added.
The Substitution can be one of three things: a fixed path, a path with back-references to parts of the incoming URL-path matched by the Pattern, or a combination of both.
Here's a breakdown of the Substitution options:
- A fixed path: This is a direct mapping of requests to a specific path. For example, if DocumentRoot is set to /usr/local/apache2/htdocs, a request for http://example.com/games would be mapped to the path /usr/local/apache2/htdocs/puzzles.html.
- A path with back-references: This allows you to include parts of the incoming URL-path in the Substitution. For example, a request for http://example.com/product/r14df/view would be mapped to the path /var/web/productdb/r14df.
Back-references are denoted by the variable $1, $2, $3, and so on, where $1 corresponds to the first expression in parenthesis in the Pattern.
Rule Basics
A RewriteRule consists of three arguments separated by spaces: the Pattern, the Substitution, and the flags. The Pattern is a regular expression that matches incoming URLs.
The Pattern is initially matched against the URL-path of the incoming request, or the request's path relative to the directory for which the rule is defined. Once a substitution has occurred, the rules that follow are matched against the substituted value.
The Substitution can be one of three things: a static path, a back-reference to a part of the incoming URL-path matched by the Pattern, or a combination of both. A back-reference is created when a part of the Pattern is enclosed in parentheses.

The variable $1 will be replaced with whatever text was matched by the expression inside the parenthesis in the Pattern. For example, a request for http://example.com/product/r14df/view will be mapped to the path /var/web/productdb/r14df.
Here's a breakdown of the RewriteRule syntax:
The Substitution can contain back-references to parts of the incoming URL-path matched by the Pattern. These back-references are created when a part of the Pattern is enclosed in parentheses and are available in the variables $1, $2, $3, and so on.
Cookies
Cookies can be easily accessed and manipulated in RewriteCond statements.
To check if a cookie exists and has the correct value, you can simply use a RewriteCond like this: %{COOKIE:cookie_name} = "value".
You can also set cookies with a RewriteRule, for example: RewriteRule ^(.*)$ /index.php?setcookie=on [L,R=301].
It's worth noting that using SetEnvIf to capture the entire referer string can be tricky, as it will split the cookie statement in the wrong place if it contains a colon.
A cookie can be set to expire in approximately 1440 minutes (24 hours) by using the RewriteRule with a cookie expiration parameter, like this: RewriteRule ^(.*)$ /index.php?setcookie=on&expires=1440 [L,R=301].
The cookie "path" can be set to "/" to cover the entire site, which is the default behavior.
URL Manipulation
URL manipulation is a powerful feature of mod rewrite that allows you to rewrite URLs internally before they're handled by the web server. This can be done using the url.rewrite-once directive.
You can also use url.rewrite-if-not-file to rewrite URLs unless the target exists and is a regular file. This is useful with frameworks like Drupal, where you want lighttpd to serve static files and rewrite everything else to use the dynamic backend.
Rewriting URLs can be configured in the main server configuration, inside a VirtualHost container, or even in a .htaccess file. However, keep in mind that rewriting inside a .htaccess file can be more complex and requires using the RewriteBase to properly map the request.
On a similar theme: Iis Mod Rewrite
Url Once
Url Once is a feature that rewrites a set of URLs internally in the webserver before they are handled. This means that the URL is modified in a way that's not visible to the user.

It's like a behind-the-scenes change that happens before the user even sees the URL. The "rewrite-once" feature is a specific type of URL manipulation that's used to simplify complex URLs or to change their structure in a way that's more user-friendly.
One example of this is the "url.rewrite-once" feature, which is mentioned in the documentation as a way to rewrite URLs internally in the webserver. This feature is useful for developers who want to make changes to their website's URL structure without affecting the user's experience.
Url - Repeat If Not File
This feature rewrites URLs internally in the webserver before they are handled unless the target exists and is a regular file.
It's akin to Apache's !-f RewriteRule, and is useful with frameworks where lighttpd should serve static files and everything else should be rewritten to use the dynamic backend.
All URLs with path-info appended to the end of the URL will be treated as file not existing, making it a simple solution for many frameworks.
For example, you can have lighttpd serve static files if they exist, or else rewrite to send the request to /index.php.
You can use the url.rewrite-if-not-file option to achieve this, with an example like url.rewrite-if-not-file = ( "" => "/index.php?path=${url.path}${qsa}" ).
.htaccess Files
Rewriting is typically configured in the main server configuration setting or inside VirtualHost containers, which is the easiest way to do rewriting and is recommended.
This technique is called per-server rewrites and is the simplest way to configure rewriting rules.
Rewriting can also be done inside Directory sections or .htaccess files, but this technique is called per-directory rewrites and is more complex.
In per-directory rewrites, the path prefix of the directory containing the .htaccess file is stripped before matching in the RewriteRule.
To ensure the request is properly mapped, you should use the RewriteBase in per-directory rewrites.
Related reading: Next Js Rewrites
Redirect and Rewrite
Since version 1.4.40, you can specify a blank target to the rewrite rule to leave the URL unmodified, skipping any further rewrite rules.
You can use regular expressions to match variables in URLs and construct new URLs with them. This means you can match the part inside (.+) and use it to construct "$1" in the new URL.
With mod_rewrite, you can create "flat links" by converting URLs with query strings and multiple variables into solid domain/path/flat/link structures. For example, a URL like https://mysite/grab?file=my.zip can be converted to https://mysite/files/games/hoopy.zip.
Flags
Flags can be applied to RewriteRules to modify their behavior.
The [NC] flag makes the matching behavior of a rule case-insensitive, allowing for rules that work regardless of the case of the URL.
You can apply one or more flags to the end of a RewriteRule to change its behavior.
Passing GET Variables
Passing GET variables is a powerful technique in redirect and rewrite rules. You can use the [QSA] flag to tag all the original variables back onto the end of the target URL.
To capture variables from the query string, you can use the %{QUERY_STRING} Apache server string and RewriteCond statements. This is similar to doing if...then...do in programming languages.
If you want to pass the Query String to the rewrite destination, you can use ${qsa} with modern versions of lighttpd. The "qsa" is short for "query-string-append".
You can also explicitly match the query string in older versions of lighttpd. For example, you can use a RewriteCond statement to check that the query string has a certain variable set, and then capture its value.
RewriteCond statements can be used to check conditions and then apply the RewriteRule. For example, you can check if the query string has a certain variable set, and then capture its value using a regular expression.
Capturing variables can be used to create new variables in the target URL. For example, you can capture the value of a variable and then use it as a directory in the target URL.
The [QSA] flag can be used to merge the query string manipulations with the original query string. This allows you to create complex rewrite rules that can handle multiple variables and conditions.
In summary, passing GET variables is a powerful technique that can be used to create complex rewrite rules. By using RewriteCond statements, capturing variables, and the [QSA] flag, you can create rules that can handle multiple variables and conditions.
Maps
Maps can be used to call an external function to do your rewriting for you.
The RewriteMap directive provides a way to do this, as discussed in greater detail in the RewriteMap supplementary documentation.
You can use RewriteMap to create more complex rewriting rules, but it's not necessary for simple tasks like creating flat links.
To create flat links, you can use regular expressions to match variables and construct new URLs, as shown in the example of rewriting a URL like https://mysite/grab?file=my.zip into a flat link like https://mysite/files/games/hoopy.zip.
RewriteCond can be used as a safety-net to prevent endless loops, by only allowing requests that have something in their query string to be processed by the RewriteRule.
Redirecting and Rewriting
Redirecting and rewriting URLs is a powerful tool for manipulating links on your website. Since version 1.4.40, Apache's mod_redirect allows you to specify a blank target to the rewrite rule, leaving the URL unmodified and skipping further rewrite rules.
One of the most useful applications of rewriting URLs is to create "flat links". This can be achieved by using regular expressions to match variables and constructing a new URL with a flat link structure. For example, a URL like https://mysite/grab?file=my.zip can be rewritten to a flat link like https://mysite/files/games/hoopy.zip.
To create flat links, you can use the RewriteRule directive with regular expressions to match variables and construct a new URL. This can be useful for search engines that don't follow generated links, and can also make your links more user-friendly.
Another use of rewriting URLs is to prevent hot-linking, where other websites steal your content by linking directly to it. You can use the RewriteCond directive to check the value of the "Referer" header, which is usually sent by the browser, and block requests that don't come from your own website.
Rewriting URLs can also be used to strip query strings from URLs, making them more user-friendly. This can be achieved by putting a ? at the end of the target part of the RewriteRule directive. Additionally, the RewriteCond directive can be used to check if a request has a query string before processing it with the RewriteRule directive, preventing endless loops.
Troubleshooting
The most common issue with mod rewrite is a 404 error, which occurs when the server can't find the file you're trying to rewrite to.
Make sure you've enabled the mod rewrite module in your Apache configuration, as seen in the "Enabling Mod Rewrite" section.
A 500 internal server error can also occur if the rewrite rule is not properly formatted, as mentioned in the "Basic Rewrite Rules" example.
Check your rewrite rules for any syntax errors or typos, and double-check that the file path is correct.
Workaround for Windows 'File Name Too Long' Error
You may encounter a "File name too long" error on Windows while running Lighttpd, resulting in a 500 Internal Server Error. This can happen when the computed filename exceeds 255 characters.
The error will appear in the error log as "File name too long" or "File not found" with a reference to a very long path.
To avoid this error, you can use mod_rewrite as a workaround.
If your error handler is PHP, you can access the full URI in the $_SERVER['REQUEST_URI'] variable.
Cooler Access Denied

Denying access to certain files and folders can be a bit like slamming a door in someone's face, resulting in a 403 "Access Denied" error.
Fortunately, mod_rewrite can redirect users to a more user-friendly location, like the parent folder.
Redirecting users to the parent folder can be a wee bit tricky with URLs, but it's a great method to employ.
You can also use a harder location to avoid potential issues in indexed directories, where folks can get in a loop.
Sometimes you'll only want to deny access to most of the files in a directory, but allow access to specific files or file types, like .css (stylesheet) and Javascript files.
The "!" sign in mod_rewrite simply means "not something", so you can use it to exclude certain file types or files, like the "special.zip" file.
You can add as many types as you need, and even bundle them into one line using the "|" (or) syntax.
For example, you could redirect requests for any file type except .css, Javascript, and "special.zip" back up to the main "/chat/" directory.
Ban Bad Users and Traffic

You have every right to exert control over who gets to access your site, just like you do with your home.
It's not just about blocking malicious scripts, but also unwanted traffic from places you don't want to be associated with.
Use .htaccess + mod_rewrite to protect your content from unwanted "guests".
The basic formula is standard if-then logic: if the request meets a particular condition, then rewrite the request.
You can ban requests based on the referrer header, the page they asked for, or a particular query parameter.
For example, you can deny access to "Teleport Pro", a download manager known to suck up a lot of bandwidth.
You can use the [OR] flag and line up a huge list of user agents you'd rather not have eating your bandwidth.
Remember, thorough testing is strongly recommended to ensure your rules are working correctly.
You can send fake HTTP requests using a scripting language like php or Perl, or a tool like cURL.
Multiple Domains
You can have multiple domains living on a single host, even if it doesn't support it natively. This can be achieved by using .htaccess and mod_rewrite.
In this setup, each domain has its own folder in the web server root, for example, one/ and two/. All incoming requests for a domain are rewritten to its corresponding folder.
For instance, all requests for domain-one.com are rewritten to the one/ directory, unless they've already been rewritten there. This is done using RewriteCond statements in the root .htaccess file.
It's worth noting that other general settings and php directives can also go in this root .htaccess file, but it's generally easier to do further rewrites, like short URL's, in the sub-directory's .htaccess files.
Expand your knowledge: Htaccess Mod Rewrite
Testing and Debugging
Testing and debugging your mod rewrite rules is an essential step to ensure they're working as expected. You can test your rewrite rules by visiting the URLs that should be affected in your web browser.
Directly visiting the old URLs in your web browser is a straightforward way to check if they redirect to the new URLs as expected. Check the address bar to ensure that the URL has changed.
You can also use the command-line tool curl with the -I option to see the HTTP header and check the redirect status. Look for a "Location" header with the new URL and a 301 or 302 status code, depending on your configuration.
If any of the tests fail, consult your Apache error log (/var/log/apache2/error.log) for detailed information on what might be going wrong.
Here's a quick reference table for testing and debugging your mod rewrite rules:
Remember to check the address bar for the new URL and look for a "Location" header with the new URL and a 301 or 302 status code.
Featured Images: pexels.com


