Friday, 7 April 2017

Tuning an Apache server in 5 minutes

https://rudd-o.com/linux-and-free-software/tuning-an-apache-server-in-5-minutes

How to get Apache to run fine without stampeding occurring in high-traffic, low-resource situations.
Hello again. This time, I'll show you how to make a Web server running Apache and Linux survive heavy loads.
Before we go on, you should know something: this is not an article about securing Apache. This is an article about making Apache behave under heavy load conditions.
Okay, now that we're here, let's discuss scalability.

Scalability

Scalability is simply the ability of a server to withstand heavy loads. If you tried to read the last article, Hardening a Linux server in 10 minutes, you probably noticed that this server was down.
That's a scalability fault.
Let's put it in another light. This server has 512 MB of RAM. The surge of traffic (thanks to LinuxToday links pointing to this site) caused the server to fail (more accurately, the MySQL server appeared to hang). Brag all you want about Linux's ability to survive these events, nothing will help you against a misconfigured server.

It all boils down to configuration

In this particular case, the misconfiguration was Apache's. Weighing 13 MB per httpd process (though some of it is shared with other processes), it's pretty simple to understand that a runaway Apache server can bring your server down completely. When your Apache server starts serving a lot of requests, all those processes quickly fill the available memory (physical and virtual). When your Linux server runs out of RAM, it will start killing processes it deems 'memory hogs'. Usually the first ones to go down are the MySQL processes. If you're serving dynamic pages, that's a disaster.

On to Apache configuration

By default, Apache comes preconfigured to serve a maximum of 256 clients simultaneously. This particular configuration setting can be found in the file /etc/httpd/conf/httpd.conf(though the location of the file may vary, depending on the Linux distribution you use).
Whip your favorite text editor out and open that file (remember that you should be doing this as root — the administrative account on the majority of Linux servers out there).
Look for MaxClients. It will probably look like this:
# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# ServerLimit: maximum value for MaxClients for the lifetime of the server
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule prefork.c>
StartServers       4
MinSpareServers    3
MaxSpareServers   10
ServerLimit      256
MaxClients       256
MaxRequestsPerChild  10000
</IfModule>
That's the configuration section for the prefork module. 99% of the Apache servers out there use the prefork module to serve requests, so unless you have an exotic configuration, you'll be changing these settings.
Time to calculate a good value for the MaxClients directive. Find out how much memory your Apache processes use. Using top, check the RES column. That's the resident memory size. It should say the size in megabytes that your Apache processes are taking. In my example, it's 22m.
Figure out a good value. If your server has 512 MB of RAM (in my case, this is true), and you're sharing your server with MySQL and Sendmail (true in my case, as well), you'll want to reserve about half of it for Apache (256 MB). Divide that by the resident memory each process takes up, and you'll have a number of processes (say, 11). That's the maximum amount of processes you can run without resorting to virtual memory. Resorting to virtual memory (swap) will make your server thrash and become extremely slow.
It's, of course, all about balance. If you have one gigabyte of swap, you may want to raise the number of Apache processes. Raising it too much will cause heavy traffic to spawn lots of Apache processes, bringing your server down.

Setting the MaxClients and StartServers directive

You now have your start value (in our example, it was 11). Change the MaxClients and the ServerLimit directives to it. Save the file and restart Apache (/sbin/service httpd restart does that trick in Fedora Core).
Now it's time to start testing. Keep a root login open to that server. Using your favorite testing tool (ab and wget are good at this), start a storm of connections (more than 1024 simultaneous requests) directed to a page served by your Apache server (ideally, one that exercises the server, like dynamic pages with lots of queries). Issuing the uptime command in your root login should not yield a load average above 1, and the server should respond to commands quickly.
[rudd-o@amauta2 conf]$ uptime
 15:54:18 up  1:41,  3 users,  load average: 0.86, 0.70, 1.50

Tuning the configuration

That's great. Once the test is finished, duplicate MaxClients and StartServers, and try your storm test again. The load average should be low.
Keep tuning until you hit your maximum desired load average. For servers used interactively often, having a load above 3 is way too much to use the server comfortably. For servers used mostly as real servers, a maximum load average of 10 should be acceptable. More than that, and you'll find yourself needing to reboot the server when experiencing heavy traffic conditions, because no terminal or remote console will respond quickly to commands, and managing the server will be impossible.

Conclusions

That's it! With practice, you'll be able to skip the memory math and learn the ideal setting for any server. Other tuning options you may try (in order of diminishing returns):
  • Eliminating unnecessary Apache modules from the configuration (perhaps uninstalling them altogether, by use of RPM or your favorite distribution's packaging tool)
  • Recompiling Apache, optimizing for memory consumption (the -Os option of gcc)
  • Recompiling Apache, building modules in instead of having them run as modules
Remember: if you have any questions or suggestions, please leave them as comments below. Happy hacking!

Hardening a Linux server in 10 minutes

https://rudd-o.com/linux-and-free-software/hardening-a-linux-server-in-10-minutes

Did you know that a freshly installed Linux server can be hardened in less than 10 minutes? Here's how!
You'll need a bit of experience with the Linux command-line environment, as the following commands are usually issued in a terminal. You will need root access on your server as well. By the way, the following instructions apply to any LSB-compliant Linux distribution, but I'll use Fedora Core as an example.
Step 1: turn all unneeded services off
There are two kinds of network services:
  • those that get started as init.d services
  • those that get started by xinetd
This distinction is important, as xinetd can start services on demand, while services started through init.d run all the time.
Okay, time to start securing your server. On a terminal, as root (and, for the purposes of this tutorial, assume this from now on) run netstat -ltunp. You should see a listing like this one:
[root@andrea rudd-o]# netstat -ltunp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 0.0.0.0:3493                0.0.0.0:*                   LISTEN      30562/upsd
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      12461/mysqld
tcp        0      0 0.0.0.0:6543                0.0.0.0:*                   LISTEN      12490/mythbackend
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      1771/portmap
tcp        0      0 0.0.0.0:6544                0.0.0.0:*                   LISTEN      12490/mythbackend
tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN      31537/cupsd
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      2143/sendmail: acce
tcp        0      0 :::80                       :::*                        LISTEN      5024/httpd
tcp        0      0 :::22                       :::*                        LISTEN      2009/sshd
tcp        0      0 0.0.0.0:19                  0.0.0.0:*                   LISTEN      2019/xinetd

Those are all processes listening to specific ports. As you can see, the PID (process ID) and the program name are displayed as well.
Make two lists: - one for the services you absolutely need (which you should already know by heart), and - one for the services that are expendable or you can start manually when they're needed (tip: each program name usually ships with a man page).
Shutdown each service on the second list (except for xinetd) That's a pretty straightforward task. Each one of those services are started by init.d. To find out the name of the service control script, just hop to /etc/rc.d/init.d and look for a file with a name similar to the program name.
Example: suppose I don't need mythbackend. To stop it: /etc/rc.d/init.d/mythbackend stop (some distributions provide the service mythbackend stop command, which is easier on your fingers). Now, to disable it: chkconfig --del mythbackend. After doing this, you should check to see if the offending service went away, with the same netstat -ltunpcommand.

That pesky xinetd

Great. So you got rid of the unneeded services. But there's more. As we saw earlier, xinetd has its own ways. In practice, this means that some services will be started on demand — thus, you won't see them under your netstat -ltunp listing.
To find out which services xinetd manages, hop to /etc/xinetd.d and do a directory listing. You should see some service configuration files. Identify the ones you won't be using, and edit each one of them, adding a line that says disable = yes between the curly braces.
Note that some services already ship with disable = yes, but some ship with disable = no. If one of the configuration files says disable = no, just change it to disable = yes. Now reload xinetd with the famous /etc/rc.d/init.d/xinetd reload, and run netstat -ltunp again, just to be sure.
That's step 1. With a bit of practice, you should be doing this in five minutes or less.

Step 2: limit access to running services using iptables

Great, our server now runs the absolutely required services, and no more. But some of those services aren't meant to be accessed from everywhere, right? For example: I may have a MySQL database server running, but that doesn't mean MySQL should be accessible from any random IP address on the Internet, right?
So, we'll use the firewall to stop evil at the door. Again, make a list of services. For each item on the list, identify which IP addresses should be able to reach the service. For each service on your list, write down the TCP/UDP port(s) they use.
In my example, MySQL uses TCP port 3306, and should only be accessible by localhost (127.0.0.1).
Time to compose and activate the iptables rules. Doing a quick check with iptables -L, I can see that my INPUT chain (the one I'll be working with, since I want to disallow INPUTs to my server) is empty:
[root@andrea xinetd.d]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
Your mileage may vary, because your distribution may already have set up some basic iptables rules; to make these instructions foolproof, I will be inserting rules at the beginning of the INPUT chain.
In this case, I want to allow access to 127.0.0.1:3306, and deny access to everyone else on port 3306, in that order. So two rules are needed. I'll add the "allow" rule into position 1 (the very first):
[root@andrea xinetd.d]# iptables -I INPUT 1 --protocol tcp --destination-port 3306 -s 127.0.0.1 -j ACCEPT
[root@andrea xinetd.d]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  localhost.localdomain  anywhere            tcp dpt:mysql
Great. I'm telling the firewall to -j ACCEPT all --protocol tcp connections to --destination-port 3306 from the address -s 127.0.0.1. Now, I'll insert the "deny" rule into position 2:
[root@andrea xinetd.d]# iptables -I INPUT 2 --protocol tcp --destination-port 3306 -j REJECT
[root@andrea xinetd.d]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  localhost.localdomain  anywhere            tcp dpt:mysql
REJECT     tcp  --  anywhere             anywhere            tcp dpt:mysql reject-with icmp-port-unreachable
See how easy it is? Let me explain: rule 2 tells the firewall to -j REJECT all --protocol tcp connections to --destination-port 3306 from any address (since I omitted the address). Since rules are processed "top-down" (from 1 to n), the first one that matches an incoming connection is applied. If no rules match, then the default policy (which is normally ACCEPT) kicks in.
Lather. Rinse. Repeat for every service that you want to secure.
Finally, save the rules. For this, you'll need to use your distribution's tools. For Fedora Core, that's as easy as issuing the command service iptables save and ensuring that the iptables service runs at boot time: chkconfig --add iptables.
It's worth noting that some people prefer to -j DROP instead of DENYing. DROP means that your server will ignore connection attempts (neither denying connections nor accepting them). I prefer DENY, because it's easier to pinpoint a problem with iptables rules that way, and (most importantly) DROP rules make those ports appear as filtered to a hostile port scanner (which hints to the attacker that a service is running).
So that's it, from insecure to secure in 10 minutes! If you have any suggestions or questions, please leave them as comments below. Happy hacking!

Thursday, 6 April 2017

RewriteRule Flags

https://httpd.apache.org/docs/current/rewrite/flags.html

This document discusses the flags which are available to the RewriteRule directive, providing detailed explanations and examples.

Introduction

RewriteRule can have its behavior modified by one or more flags. Flags are included in square brackets at the end of the rule, and multiple flags are separated by commas.
RewriteRule pattern target [Flag1,Flag2,Flag3]
Each flag (with a few exceptions) has a short form, such as CO, as well as a longer form, such as cookie. While it is most common to use the short form, it is recommended that you familiarize yourself with the long form, so that you remember what each flag is supposed to do. Some flags take one or more arguments. Flags are not case sensitive.
Flags that alter metadata associated with the request (T=, H=, E=) have no affect in per-directory and htaccess context, when a substitution (other than '-') is performed during the same round of rewrite processing.
Presented here are each of the available flags, along with an example of how you might use them.
top

B (escape backreferences)

The [B] flag instructs RewriteRule to escape non-alphanumeric characters before applying the transformation.
mod_rewrite has to unescape URLs before mapping them, so backreferences are unescaped at the time they are applied. Using the B flag, non-alphanumeric characters in backreferences will be escaped. For example, consider the rule:
RewriteRule "^search/(.*)$" "/search.php?term=$1"
Given a search term of 'x & y/z', a browser will encode it as 'x%20%26%20y%2Fz', making the request 'search/x%20%26%20y%2Fz'. Without the B flag, this rewrite rule will map to 'search.php?term=x & y/z', which isn't a valid URL, and so would be encoded as search.php?term=x%20&y%2Fz=, which is not what was intended.
With the B flag set on this same rule, the parameters are re-encoded before being passed on to the output URL, resulting in a correct mapping to /search.php?term=x%20%26%20y%2Fz.
RewriteRule "^search/(.*)$" "/search.php?term=$1" [B,PT]
Note that you may also need to set AllowEncodedSlashes to On to get this particular example to work, as httpd does not allow encoded slashes in URLs, and returns a 404 if it sees one.
This escaping is particularly necessary in a proxy situation, when the backend may break if presented with an unescaped URL.
top

C|chain

The [C] or [chain] flag indicates that the RewriteRule is chained to the next rule. That is, if the rule matches, then it is processed as usual and control moves on to the next rule. However, if it does not match, then the next rule, and any other rules that are chained together, are skipped.
top

CO|cookie

The [CO], or [cookie] flag, allows you to set a cookie when a particular RewriteRule matches. The argument consists of three required fields and four optional fields.
The full syntax for the flag, including all attributes, is as follows:
[CO=NAME:VALUE:DOMAIN:lifetime:path:secure:httponly]
If a literal ':' character is needed in any of the cookie fields, an alternate syntax is available. To opt-in to the alternate syntax, the cookie "Name" should be preceded with a ';' character, and field separators should be specified as ';'.
[CO=;NAME;VALUE:MOREVALUE;DOMAIN;lifetime;path;secure;httponly]
You must declare a name, a value, and a domain for the cookie to be set.
Domain
The domain for which you want the cookie to be valid. This may be a hostname, such as www.example.com, or it may be a domain, such as .example.com. It must be at least two parts separated by a dot. That is, it may not be merely .com or .net. Cookies of that kind are forbidden by the cookie security model.
You may optionally also set the following values:
Lifetime
The time for which the cookie will persist, in minutes.
A value of 0 indicates that the cookie will persist only for the current browser session. This is the default value if none is specified.
Path
The path, on the current website, for which the cookie is valid, such as /customers/ or /files/download/.
By default, this is set to / - that is, the entire website.
Secure
If set to securetrue, or 1, the cookie will only be permitted to be translated via secure (https) connections.
httponly
If set to HttpOnlytrue, or 1, the cookie will have the HttpOnly flag set, which means that the cookie is inaccessible to JavaScript code on browsers that support this feature.
Consider this example:
RewriteEngine On
RewriteRule "^/index\.html" "-" [CO=frontdoor:yes:.example.com:1440:/]
In the example give, the rule doesn't rewrite the request. The "-" rewrite target tells mod_rewrite to pass the request through unchanged. Instead, it sets a cookie called 'frontdoor' to a value of 'yes'. The cookie is valid for any host in the .example.com domain. It is set to expire in 1440 minutes (24 hours) and is returned for all URIs.
top

DPI|discardpath

The DPI flag causes the PATH_INFO portion of the rewritten URI to be discarded.
This flag is available in version 2.2.12 and later.
In per-directory context, the URI each RewriteRule compares against is the concatenation of the current values of the URI and PATH_INFO.
The current URI can be the initial URI as requested by the client, the result of a previous round of mod_rewrite processing, or the result of a prior rule in the current round of mod_rewrite processing.
In contrast, the PATH_INFO that is appended to the URI before each rule reflects only the value of PATH_INFO before this round of mod_rewrite processing. As a consequence, if large portions of the URI are matched and copied into a substitution in multiple RewriteRule directives, without regard for which parts of the URI came from the current PATH_INFO, the final URI may have multiple copies of PATH_INFO appended to it.
Use this flag on any substitution where the PATH_INFO that resulted from the previous mapping of this request to the filesystem is not of interest. This flag permanently forgets the PATH_INFO established before this round of mod_rewrite processing began. PATH_INFO will not be recalculated until the current round of mod_rewrite processing completes. Subsequent rules during this round of processing will see only the direct result of substitutions, without any PATH_INFO appended.
top

E|env

With the [E], or [env] flag, you can set the value of an environment variable. Note that some environment variables may be set after the rule is run, thus unsetting what you have set. See the Environment Variables document for more details on how Environment variables work.
The full syntax for this flag is:
[E=VAR:VAL]
[E=!VAR]
VAL may contain backreferences ($N or %N) which are expanded.
Using the short form
[E=VAR]
you can set the environment variable named VAR to an empty value.
The form
[E=!VAR]
allows to unset a previously set environment variable named VAR.
Environment variables can then be used in a variety of contexts, including CGI programs, other RewriteRule directives, or CustomLog directives.
The following example sets an environment variable called 'image' to a value of '1' if the requested URI is an image file. Then, that environment variable is used to exclude those requests from the access log.
RewriteRule "\.(png|gif|jpg)$" "-" [E=image:1]
CustomLog "logs/access_log" combined env=!image
Note that this same effect can be obtained using SetEnvIf. This technique is offered as an example, not as a recommendation.
top

END

Using the [END] flag terminates not only the current round of rewrite processing (like [L]) but also prevents any subsequent rewrite processing from occurring in per-directory (htaccess) context.
This does not apply to new requests resulting from external redirects.
top

F|forbidden

Using the [F] flag causes the server to return a 403 Forbidden status code to the client. While the same behavior can be accomplished using the Deny directive, this allows more flexibility in assigning a Forbidden status.
The following rule will forbid .exe files from being downloaded from your server.
RewriteRule "\.exe" "-" [F]
This example uses the "-" syntax for the rewrite target, which means that the requested URI is not modified. There's no reason to rewrite to another URI, if you're going to forbid the request.
When using [F], an [L] is implied - that is, the response is returned immediately, and no further rules are evaluated.
top

G|gone

The [G] flag forces the server to return a 410 Gone status with the response. This indicates that a resource used to be available, but is no longer available.
As with the [F] flag, you will typically use the "-" syntax for the rewrite target when using the [G] flag:
RewriteRule "oldproduct" "-" [G,NC]
When using [G], an [L] is implied - that is, the response is returned immediately, and no further rules are evaluated.
top

H|handler

Forces the resulting request to be handled with the specified handler. For example, one might use this to force all files without a file extension to be parsed by the php handler:
RewriteRule "!\." "-" [H=application/x-httpd-php]
The regular expression above - !\. - will match any request that does not contain the literal . character.
This can be also used to force the handler based on some conditions. For example, the following snippet used in per-server context allows .php files to be displayed by mod_php if they are requested with the .phps extension:
RewriteRule "^(/source/.+\.php)s$" "$1" [H=application/x-httpd-php-source]
The regular expression above - ^(/source/.+\.php)s$ - will match any request that starts with /source/ followed by 1 or n characters followed by .phps literally. The backreference $1 referrers to the captured match within parenthesis of the regular expression.
top

L|last

The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.
If you are using RewriteRule in either .htaccess files or in <Directory> sections, it is important to have some understanding of how the rules are processed. The simplified form of this is that once the rules have been processed, the rewritten request is handed back to the URL parsing engine to do what it may with it. It is possible that as the rewritten request is handled, the .htaccess file or <Directory> section may be encountered again, and thus the ruleset may be run again from the start. Most commonly this will happen if one of the rules causes a redirect - either internal or external - causing the request process to start over.
It is therefore important, if you are using RewriteRule directives in one of these contexts, that you take explicit steps to avoid rules looping, and not count solely on the [L] flag to terminate execution of a series of rules, as shown below.
An alternative flag, [END], can be used to terminate not only the current round of rewrite processing but prevent any subsequent rewrite processing from occurring in per-directory (htaccess) context. This does not apply to new requests resulting from external redirects.
The example given here will rewrite any request to index.php, giving the original request as a query string argument to index.php, however, the RewriteCondensures that if the request is already for index.php, the RewriteRule will be skipped.
RewriteBase "/"
RewriteCond "%{REQUEST_URI}" "!=/index.php"
RewriteRule "^(.*)" "/index.php?req=$1" [L,PT]
top

N|next

The [N] flag causes the ruleset to start over again from the top, using the result of the ruleset so far as a starting point. Use with extreme caution, as it may result in loop.
The [Next] flag could be used, for example, if you wished to replace a certain string or letter repeatedly in a request. The example shown here will replace A with B everywhere in a request, and will continue doing so until there are no more As to be replaced.
RewriteRule "(.*)A(.*)" "$1B$2" [N]
You can think of this as a while loop: While this pattern still matches (i.e., while the URI still contains an A), perform this substitution (i.e., replace the A with a B).
In 2.4.8 and later, this module returns an error after 32,000 iterations to protect against unintended looping. An alternative maximum number of iterations can be specified by adding to the N flag.
# Be willing to replace 1 character in each pass of the loop
RewriteRule "(.+)[><;]$" "$1" [N=64000]
# ... or, give up if after 10 loops
RewriteRule "(.+)[><;]$" "$1" [N=10]
top

NC|nocase

Use of the [NC] flag causes the RewriteRule to be matched in a case-insensitive manner. That is, it doesn't care whether letters appear as upper-case or lower-case in the matched URI.
In the example below, any request for an image file will be proxied to your dedicated image server. The match is case-insensitive, so that .jpg and .JPG files are both acceptable, for example.
RewriteRule "(.*\.(jpg|gif|png))$" "http://images.example.com$1" [P,NC]
top

NE|noescape

By default, special characters, such as & and ?, for example, will be converted to their hexcode equivalent. Using the [NE] flag prevents that from happening.
RewriteRule "^/anchor/(.+)" "/bigpage.html#$1" [NE,R]
The above example will redirect /anchor/xyz to /bigpage.html#xyz. Omitting the [NE] will result in the # being converted to its hexcode equivalent, %23, which will then result in a 404 Not Found error condition.
top

NS|nosubreq

Use of the [NS] flag prevents the rule from being used on subrequests. For example, a page which is included using an SSI (Server Side Include) is a subrequest, and you may want to avoid rewrites happening on those subrequests. Also, when mod_dir tries to find out information about possible directory default files (such as index.html files), this is an internal subrequest, and you often want to avoid rewrites on such subrequests. On subrequests, it is not always useful, and can even cause errors, if the complete set of rules are applied. Use this flag to exclude problematic rules.
To decide whether or not to use this rule: if you prefix URLs with CGI-scripts, to force them to be processed by the CGI-script, it's likely that you will run into problems (or significant overhead) on sub-requests. In these cases, use this flag.
Images, javascript files, or css files, loaded as part of an HTML page, are not subrequests - the browser requests them as separate HTTP requests.
top

P|proxy

Use of the [P] flag causes the request to be handled by mod_proxy, and handled via a proxy request. For example, if you wanted all image requests to be handled by a back-end image server, you might do something like the following:
RewriteRule "/(.*)\.(jpg|gif|png)$" "http://images.example.com/$1.$2" [P]
Use of the [P] flag implies [L] - that is, the request is immediately pushed through the proxy, and any following rules will not be considered.
You must make sure that the substitution string is a valid URI (typically starting with http://hostname) which can be handled by the mod_proxy. If not, you will get an error from the proxy module. Use this flag to achieve a more powerful implementation of the ProxyPass directive, to map remote content into the namespace of the local server.

Security Warning

Take care when constructing the target URL of the rule, considering the security impact from allowing the client influence over the set of URLs to which your server will act as a proxy. Ensure that the scheme and hostname part of the URL is either fixed, or does not allow the client undue influence.

Performance warning

Using this flag triggers the use of mod_proxy, without handling of persistent connections. This means the performance of your proxy will be better if you set it up with ProxyPass or ProxyPassMatch
This is because this flag triggers the use of the default worker, which does not handle connection pooling.
Avoid using this flag and prefer those directives, whenever you can.
Note: mod_proxy must be enabled in order to use this flag.
top

PT|passthrough

The target (or substitution string) in a RewriteRule is assumed to be a file path, by default. The use of the [PT] flag causes it to be treated as a URI instead. That is to say, the use of the [PT] flag causes the result of the RewriteRule to be passed back through URL mapping, so that location-based mappings, such as AliasRedirect, or ScriptAlias, for example, might have a chance to take effect.
If, for example, you have an Alias for /icons, and have a RewriteRule pointing there, you should use the [PT] flag to ensure that the Alias is evaluated.
Alias "/icons" "/usr/local/apache/icons"
RewriteRule "/pics/(.+)\.jpg$" "/icons/$1.gif" [PT]
Omission of the [PT] flag in this case will cause the Alias to be ignored, resulting in a 'File not found' error being returned.
The PT flag implies the L flag: rewriting will be stopped in order to pass the request to the next phase of processing.
Note that the PT flag is implied in per-directory contexts such as <Directory> sections or in .htaccess files. The only way to circumvent that is to rewrite to -.
top

QSA|qsappend

When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.
Consider the following rule:
RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]
With the [QSA] flag, a request for /pages/123?one=two will be mapped to /page.php?page=123&one=two. Without the [QSA] flag, that same request will be mapped to /page.php?page=123 - that is, the existing query string will be discarded.
top

QSD|qsdiscard

When the requested URI contains a query string, and the target URI does not, the default behavior of RewriteRule is to copy that query string to the target URI. Using the [QSD] flag causes the query string to be discarded.
This flag is available in version 2.4.0 and later.
Using [QSD] and [QSA] together will result in [QSD] taking precedence.
If the target URI has a query string, the default behavior will be observed - that is, the original query string will be discarded and replaced with the query string in the RewriteRule target URI.
top

QSL|qslast

By default, the first (left-most) question mark in the substitution delimits the path from the query string. Using the [QSL] flag instructs RewriteRule to instead split the two components using the last (right-most) question mark.
This is useful when mapping to files that have literal question marks in their filename. If no query string is used in the substitution, a question mark can be appended to it in combination with this flag.
This flag is available in version 2.4.19 and later.
top

R|redirect

Use of the [R] flag causes a HTTP redirect to be issued to the browser. If a fully-qualified URL is specified (that is, including http://servername/) then a redirect will be issued to that location. Otherwise, the current protocol, servername, and port number will be used to generate the URL sent with the redirect.
Any valid HTTP response status code may be specified, using the syntax [R=305], with a 302 status code being used by default if none is specified. The status code specified need not necessarily be a redirect (3xx) status code. However, if a status code is outside the redirect range (300-399) then the substitution string is dropped entirely, and rewriting is stopped as if the L were used.
In addition to response status codes, you may also specify redirect status using their symbolic names: temp (default), permanent, or seeother.
You will almost always want to use [R] in conjunction with [L] (that is, use [R,L]) because on its own, the [R] flag prepends http://thishost[:thisport] to the URI, but then passes this on to the next rule in the ruleset, which can often result in 'Invalid URI in request' warnings.
top

S|skip

The [S] flag is used to skip rules that you don't want to run. The syntax of the skip flag is [S=N], where N signifies the number of rules to skip (provided the RewriteRulematches). This can be thought of as a goto statement in your rewrite ruleset. In the following example, we only want to run the RewriteRule if the requested URI doesn't correspond with an actual file.
# Is the request for a non-existent file?
RewriteCond "%{REQUEST_FILENAME}" "!-f"
RewriteCond "%{REQUEST_FILENAME}" "!-d"
# If so, skip these two RewriteRules
RewriteRule ".?" "-" [S=2]

RewriteRule "(.*\.gif)" "images.php?$1"
RewriteRule "(.*\.html)" "docs.php?$1"
This technique is useful because a RewriteCond only applies to the RewriteRule immediately following it. Thus, if you want to make a RewriteCond apply to several RewriteRules, one possible technique is to negate those conditions and add a RewriteRule with a [Skip] flag. You can use this to make pseudo if-then-else constructs: The last rule of the then-clause becomes skip=N, where N is the number of rules in the else-clause:
# Does the file exist?
RewriteCond "%{REQUEST_FILENAME}" "!-f"
RewriteCond "%{REQUEST_FILENAME}" "!-d"
# Create an if-then-else construct by skipping 3 lines if we meant to go to the "else" stanza.
RewriteRule ".?" "-" [S=3]

# IF the file exists, then:
    RewriteRule "(.*\.gif)" "images.php?$1"
    RewriteRule "(.*\.html)" "docs.php?$1"
    # Skip past the "else" stanza.
    RewriteRule ".?" "-" [S=1]
# ELSE...
    RewriteRule "(.*)" "404.php?file=$1"
# END
It is probably easier to accomplish this kind of configuration using the <If><ElseIf>, and <Else> directives instead.
top

T|type

Sets the MIME type with which the resulting response will be sent. This has the same effect as the AddType directive.
For example, you might use the following technique to serve Perl source code as plain text, if requested in a particular way:
# Serve .pl files as plain text
RewriteRule "\.pl$" "-" [T=text/plain]
Or, perhaps, if you have a camera that produces jpeg images without file extensions, you could force those images to be served with the correct MIME type by virtue of their file names:
# Files with 'IMG' in the name are jpg images.
RewriteRule "IMG" "-" [T=image/jpg]
Please note that this is a trivial example, and could be better done using <FilesMatch> instead. Always consider the alternate solutions to a problem before resorting to rewrite, which will invariably be a less efficient solution than the alternatives.
If used in per-directory context, use only - (dash) as the substitution for the entire round of mod_rewrite processing, otherwise the MIME-type set with this flag is lost due to an internal re-processing (including subsequent rounds of mod_rewrite processing). The L flag can be useful in this context to end the current round of mod_rewrite processing.