From: Joshua Slive Date: Sun, 22 Sep 2002 20:04:12 +0000 (+0000) Subject: Convert rewriteguide, perf-tuning and misc/index to xml. X-Git-Tag: WROWE_2_0_43_PRE1~53 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=70659546d594d8866f444bf40ea41758766800bd;p=thirdparty%2Fapache%2Fhttpd.git Convert rewriteguide, perf-tuning and misc/index to xml. Submitted by: Tim Gerundt git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@96950 13f79535-47bb-0310-9956-ffa450edef68 --- diff --git a/docs/manual/misc/index.html b/docs/manual/misc/index.html deleted file mode 100644 index eb40b5996f7..00000000000 --- a/docs/manual/misc/index.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - Apache Miscellaneous Documentation - - - - - - -

Apache Miscellaneous Documentation

- -

Below is a list of additional documentation pages that apply - to the Apache web server development project.

- -
-
How to use XSSI and - Negotiation for custom ErrorDocuments
- -
Describes a solution which uses XSSI and negotiation to - custom-tailor the Apache ErrorDocuments to taste, adding the - advantage of returning internationalized versions of the - error messages depending on the client's language - preferences.
- -
File Descriptor use in - Apache
- -
Describes how Apache uses file descriptors and talks - about various limits imposed on the number of descriptors - available by various operating systems.
- -
FIN_WAIT_2
- -
A description of the causes of Apache processes going - into the FIN_WAIT_2 state, and what you can do - about it.
- -
Known Client - Problems
- -
A list of problems in HTTP clients which can be mitigated - by Apache.
- -
Performance Notes -- Apache - Tuning
- -
Notes about how to (run-time and compile-time) configure - Apache for highest performance. Notes explaining why Apache - does some things, and why it doesn't do other things (which - make it slower/faster).
- -
Security Tips
- -
Some "do"s - and "don't"s - for keeping your Apache web - site secure.
-
- - - - diff --git a/docs/manual/misc/index.html.en b/docs/manual/misc/index.html.en new file mode 100644 index 00000000000..89d335a178d --- /dev/null +++ b/docs/manual/misc/index.html.en @@ -0,0 +1,74 @@ + + +Apache Miscellaneous Documentation - Apache HTTP Server
<-

Apache Miscellaneous Documentation

+ +

Below is a list of additional documentation pages that apply + to the Apache web server development project.

+ +
+
How to use XSSI and + Negotiation for custom ErrorDocuments
+ +
+

Describes a solution which uses XSSI and negotiation to + custom-tailor the Apache ErrorDocuments to taste, adding the + advantage of returning internationalized versions of the + error messages depending on the client's language + preferences.

+
+ +
File Descriptor use in + Apache
+ +
+

Describes how Apache uses file descriptors and talks + about various limits imposed on the number of descriptors + available by various operating systems.

+
+ +
FIN_WAIT_2
+ +
+

A description of the causes of Apache processes going + into the FIN_WAIT_2 state, and what you can do + about it.

+
+ +
Known Client + Problems
+ +
+

A list of problems in HTTP clients which can be mitigated + by Apache.

+
+ +
Performance Notes - Apache + Tuning
+ +
+

Notes about how to (run-time and compile-time) configure + Apache for highest performance. Notes explaining why Apache + does some things, and why it doesn't do other things (which + make it slower/faster).

+ +
Warning: + This document has not been fully updated + to take into account changes made in the 2.0 version of the + Apache HTTP Server. Some of the information may still be + relevant, but please use it with care.
+ +
+ +
Security Tips
+ +
+

Some "do"s - and "don't"s - for keeping your Apache web + site secure.

+
+
+ +
\ No newline at end of file diff --git a/docs/manual/misc/index.xml b/docs/manual/misc/index.xml new file mode 100644 index 00000000000..4b52d9aa319 --- /dev/null +++ b/docs/manual/misc/index.xml @@ -0,0 +1,80 @@ + + + + + + + + Apache Miscellaneous Documentation + + + +

Below is a list of additional documentation pages that apply + to the Apache web server development project.

+ +
+
How to use XSSI and + Negotiation for custom ErrorDocuments
+ +
+

Describes a solution which uses XSSI and negotiation to + custom-tailor the Apache ErrorDocuments to taste, adding the + advantage of returning internationalized versions of the + error messages depending on the client's language + preferences.

+
+ +
File Descriptor use in + Apache
+ +
+

Describes how Apache uses file descriptors and talks + about various limits imposed on the number of descriptors + available by various operating systems.

+
+ +
FIN_WAIT_2
+ +
+

A description of the causes of Apache processes going + into the FIN_WAIT_2 state, and what you can do + about it.

+
+ +
Known Client + Problems
+ +
+

A list of problems in HTTP clients which can be mitigated + by Apache.

+
+ +
Performance Notes - Apache + Tuning
+ +
+

Notes about how to (run-time and compile-time) configure + Apache for highest performance. Notes explaining why Apache + does some things, and why it doesn't do other things (which + make it slower/faster).

+ + Warning: + This document has not been fully updated + to take into account changes made in the 2.0 version of the + Apache HTTP Server. Some of the information may still be + relevant, but please use it with care. + +
+ +
Security Tips
+ +
+

Some "do"s - and "don't"s - for keeping your Apache web + site secure.

+
+
+ +
+ +
diff --git a/docs/manual/misc/perf-tuning.html b/docs/manual/misc/perf-tuning.html deleted file mode 100644 index 586486e8486..00000000000 --- a/docs/manual/misc/perf-tuning.html +++ /dev/null @@ -1,854 +0,0 @@ - - - - - - - Apache Performance Notes - - - - - - -
- Warning: This document has not been fully updated - to take into account changes made in the 2.0 version of the - Apache HTTP Server. Some of the information may still be - relevant, but please use it with care. -
- -

Apache Performance Notes

- -

Author: Dean Gaudet

- - -
- - - - - - - -
Related Modules
-
- mod_dir
- Multi-Processing - module
- mod_status
-
Related Directives
-
- AllowOverride
- DirectoryIndex
- HostnameLookups
- EnableMMAP
- KeepAliveTimeout
- MaxSpareServers
- MinSpareServers
- Options - (FollowSymLinks and FollowIfOwnerMatch)
- StartServers
-
- -

Introduction

- -

Apache 2.0 is a general-purpose webserver, designed to - provide a balance of flexibility, portability, and performance. - Although it has not been designed specifically to set benchmark - records, Apache 2.0 is capable of high performance in many - real-world situations.

- -

Compared to Apache 1.3, release 2.0 contains many additional - optimizations to increase throughput and scalability. Most of - these improvements are enabled by default. However, there are - compile-time and run-time configuration choices that can - significantly affect performance. This document describes the - options that a server administrator can configure to tune the - performance of an Apache 2.0 installation. Some of these - configuration options enable the httpd to better take advantage - of the capabilities of the hardware and OS, while others allow - the administrator to trade functionality for speed.

- -
- -

Hardware and Operating - System Issues

- -

The single biggest hardware issue affecting webserver - performance is RAM. A webserver should never ever have to swap, - swapping increases the latency of each request beyond a point - that users consider "fast enough". This causes users to hit - stop and reload, further increasing the load. You can, and - should, control the MaxClients setting so that - your server does not spawn so many children it starts - swapping.

- -

Beyond that the rest is mundane: get a fast enough CPU, a - fast enough network card, and fast enough disks, where "fast - enough" is something that needs to be determined by - experimentation.

- -

Operating system choice is largely a matter of local - concerns. But some guidelines that have proven generally - useful are:

- - -
- -

Run-Time Configuration - Issues

- -

HostnameLookups

- -

Prior to Apache 1.3, HostnameLookups defaulted - to On. This adds latency to every request because it requires a - DNS lookup to complete before the request is finished. In - Apache 1.3 this setting defaults to Off. However (1.3 or - later), if you use any Allow from domain or - Deny from domain directives then you will pay for - a double reverse DNS lookup (a reverse, followed by a forward - to make sure that the reverse is not being spoofed). So for the - highest performance avoid using these directives (it's fine to - use IP addresses rather than domain names).

- -

Note that it's possible to scope the directives, such as - within a <Location /server-status> section. - In this case the DNS lookups are only performed on requests - matching the criteria. Here's an example which disables lookups - except for .html and .cgi files:

- -
-
-HostnameLookups off
-<Files ~ "\.(html|cgi)$">
-    HostnameLookups on
-</Files>
-
-
- But even still, if you just need DNS names in some CGIs you - could consider doing the gethostbyname call in the - specific CGIs that need it. - -

Similarly, if you need to have hostname information in your - server logs in order to generate reports of this information, - you can postprocess your log file with logresolve, so that - these lookups can be done without making the client wait. It is - recommended that you do this postprocessing, and any other - statistical analysis of the log file, somewhere other than your - production web server machine, in order that this activity does - not adversely affect server performance.

- -

FollowSymLinks and SymLinksIfOwnerMatch

- -

Wherever in your URL-space you do not have an Options - FollowSymLinks, or you do have an Options - SymLinksIfOwnerMatch Apache will have to issue extra - system calls to check up on symlinks. One extra call per - filename component. For example, if you had:

- -
-
-DocumentRoot /www/htdocs
-<Directory />
-    Options SymLinksIfOwnerMatch
-</Directory>
-
-
- and a request is made for the URI /index.html. - Then Apache will perform lstat(2) on - /www, /www/htdocs, and - /www/htdocs/index.html. The results of these - lstats are never cached, so they will occur on - every single request. If you really desire the symlinks - security checking you can do something like this: - -
-
-DocumentRoot /www/htdocs
-<Directory />
-    Options FollowSymLinks
-</Directory>
-<Directory /www/htdocs>
-    Options -FollowSymLinks +SymLinksIfOwnerMatch
-</Directory>
-
-
- This at least avoids the extra checks for the - DocumentRoot path. Note that you'll need to add - similar sections if you have any Alias or - RewriteRule paths outside of your document root. - For highest performance, and no symlink protection, set - FollowSymLinks everywhere, and never set - SymLinksIfOwnerMatch. - -

AllowOverride

- -

Wherever in your URL-space you allow overrides (typically - .htaccess files) Apache will attempt to open - .htaccess for each filename component. For - example,

- -
-
-DocumentRoot /www/htdocs
-<Directory />
-    AllowOverride all
-</Directory>
-
-
- and a request is made for the URI /index.html. - Then Apache will attempt to open /.htaccess, - /www/.htaccess, and - /www/htdocs/.htaccess. The solutions are similar - to the previous case of Options FollowSymLinks. - For highest performance use AllowOverride None - everywhere in your filesystem. - -

Negotiation

- -

If at all possible, avoid content-negotiation if you're - really interested in every last ounce of performance. In - practice the benefits of negotiation outweigh the performance - penalties. There's one case where you can speed up the server. - Instead of using a wildcard such as:

- -
-
-DirectoryIndex index
-
-
- Use a complete list of options: - -
-
-DirectoryIndex index.cgi index.pl index.shtml index.html
-
-
- where you list the most common choice first. - -

Also note that explicitly creating a type-map - file provides better performance than using - MultiViews, as the necessary information can be - determined by reading this single file, rather than having to - scan the directory for files.

- -

Memory-mapping

- -

In situations where Apache 2.0 needs to look at the contents - of a file being delivered--for example, when doing server-side-include - processing--it normally memory-maps the file if the OS supports - some form of mmap(2). -

- -

On some platforms, this memory-mapping improves performance. - However, there are cases where memory-mapping can hurt the performance - or even the stability of the httpd:

- - - -

For installations where either of these factors applies, you - should use EnableMMAP off to disable the memory-mapping - of delivered files. (Note: This directive can be overridden on - a per-directory basis.)

- -

Process Creation

- -

Prior to Apache 1.3 the MinSpareServers, - MaxSpareServers, and StartServers - settings all had drastic effects on benchmark results. In - particular, Apache required a "ramp-up" period in order to - reach a number of children sufficient to serve the load being - applied. After the initial spawning of - StartServers children, only one child per second - would be created to satisfy the MinSpareServers - setting. So a server being accessed by 100 simultaneous - clients, using the default StartServers of 5 would - take on the order 95 seconds to spawn enough children to handle - the load. This works fine in practice on real-life servers, - because they aren't restarted frequently. But does really - poorly on benchmarks which might only run for ten minutes.

- -

The one-per-second rule was implemented in an effort to - avoid swamping the machine with the startup of new children. If - the machine is busy spawning children it can't service - requests. But it has such a drastic effect on the perceived - performance of Apache that it had to be replaced. As of Apache - 1.3, the code will relax the one-per-second rule. It will spawn - one, wait a second, then spawn two, wait a second, then spawn - four, and it will continue exponentially until it is spawning - 32 children per second. It will stop whenever it satisfies the - MinSpareServers setting.

- -

This appears to be responsive enough that it's almost - unnecessary to twiddle the MinSpareServers, - MaxSpareServers and StartServers - knobs. When more than 4 children are spawned per second, a - message will be emitted to the ErrorLog. If you - see a lot of these errors then consider tuning these settings. - Use the mod_status output as a guide.

- -

Related to process creation is process death induced by the - MaxRequestsPerChild setting. By default this is 0, - which means that there is no limit to the number of requests - handled per child. If your configuration currently has this set - to some very low number, such as 30, you may want to bump this - up significantly. If you are running SunOS or an old version of - Solaris, limit this to 10000 or so because of memory leaks.

- -

When keep-alives are in use, children will be kept busy - doing nothing waiting for more requests on the already open - connection. The default KeepAliveTimeout of 15 - seconds attempts to minimize this effect. The tradeoff here is - between network bandwidth and server resources. In no event - should you raise this above about 60 seconds, as - most of the benefits are lost.

-
- -

Compile-Time - Configuration Issues

- -

mod_status and ExtendedStatus On

- -

If you include mod_status and you also set - ExtendedStatus On when building and running - Apache, then on every request Apache will perform two calls to - gettimeofday(2) (or times(2) - depending on your operating system), and (pre-1.3) several - extra calls to time(2). This is all done so that - the status report contains timing indications. For highest - performance, set ExtendedStatus off (which is the - default).

- -

accept Serialization - multiple sockets

- -

This discusses a shortcoming in the Unix socket API. Suppose - your web server uses multiple Listen statements to - listen on either multiple ports or multiple addresses. In order - to test each socket to see if a connection is ready Apache uses - select(2). select(2) indicates that a - socket has zero or at least one connection - waiting on it. Apache's model includes multiple children, and - all the idle ones test for new connections at the same time. A - naive implementation looks something like this (these examples - do not match the code, they're contrived for pedagogical - purposes):

- -
-
-    for (;;) {
-    for (;;) {
-        fd_set accept_fds;
-
-        FD_ZERO (&accept_fds);
-        for (i = first_socket; i <= last_socket; ++i) {
-        FD_SET (i, &accept_fds);
-        }
-        rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL);
-        if (rc < 1) continue;
-        new_connection = -1;
-        for (i = first_socket; i <= last_socket; ++i) {
-        if (FD_ISSET (i, &accept_fds)) {
-            new_connection = accept (i, NULL, NULL);
-            if (new_connection != -1) break;
-        }
-        }
-        if (new_connection != -1) break;
-    }
-    process the new_connection;
-    }
-
-
- But this naive implementation has a serious starvation problem. - Recall that multiple children execute this loop at the same - time, and so multiple children will block at - select when they are in between requests. All - those blocked children will awaken and return from - select when a single request appears on any socket - (the number of children which awaken varies depending on the - operating system and timing issues). They will all then fall - down into the loop and try to accept the - connection. But only one will succeed (assuming there's still - only one connection ready), the rest will be blocked - in accept. This effectively locks those children - into serving requests from that one socket and no other - sockets, and they'll be stuck there until enough new requests - appear on that socket to wake them all up. This starvation - problem was first documented in PR#467. There - are at least two solutions. - -

One solution is to make the sockets non-blocking. In this - case the accept won't block the children, and they - will be allowed to continue immediately. But this wastes CPU - time. Suppose you have ten idle children in - select, and one connection arrives. Then nine of - those children will wake up, try to accept the - connection, fail, and loop back into select, - accomplishing nothing. Meanwhile none of those children are - servicing requests that occurred on other sockets until they - get back up to the select again. Overall this - solution does not seem very fruitful unless you have as many - idle CPUs (in a multiprocessor box) as you have idle children, - not a very likely situation.

- -

Another solution, the one used by Apache, is to serialize - entry into the inner loop. The loop looks like this - (differences highlighted):

- -
-
-    for (;;) {
-    accept_mutex_on ();
-    for (;;) {
-        fd_set accept_fds;
-
-        FD_ZERO (&accept_fds);
-        for (i = first_socket; i <= last_socket; ++i) {
-        FD_SET (i, &accept_fds);
-        }
-        rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL);
-        if (rc < 1) continue;
-        new_connection = -1;
-        for (i = first_socket; i <= last_socket; ++i) {
-        if (FD_ISSET (i, &accept_fds)) {
-            new_connection = accept (i, NULL, NULL);
-            if (new_connection != -1) break;
-        }
-        }
-        if (new_connection != -1) break;
-    }
-    accept_mutex_off ();
-    process the new_connection;
-    }
-
-
- The functions - accept_mutex_on and accept_mutex_off - implement a mutual exclusion semaphore. Only one child can have - the mutex at any time. There are several choices for - implementing these mutexes. The choice is defined in - src/conf.h (pre-1.3) or - src/include/ap_config.h (1.3 or later). Some - architectures do not have any locking choice made, on these - architectures it is unsafe to use multiple Listen - directives. - -
-
USE_FLOCK_SERIALIZED_ACCEPT
- -
This method uses the flock(2) system call to - lock a lock file (located by the LockFile - directive).
- -
USE_FCNTL_SERIALIZED_ACCEPT
- -
This method uses the fcntl(2) system call to - lock a lock file (located by the LockFile - directive).
- -
USE_SYSVSEM_SERIALIZED_ACCEPT
- -
(1.3 or later) This method uses SysV-style semaphores to - implement the mutex. Unfortunately SysV-style semaphores have - some bad side-effects. One is that it's possible Apache will - die without cleaning up the semaphore (see the - ipcs(8) man page). The other is that the - semaphore API allows for a denial of service attack by any - CGIs running under the same uid as the webserver - (i.e., all CGIs, unless you use something like - suexec or cgiwrapper). For these reasons this method is not - used on any architecture except IRIX (where the previous two - are prohibitively expensive on most IRIX boxes).
- -
USE_USLOCK_SERIALIZED_ACCEPT
- -
(1.3 or later) This method is only available on IRIX, and - uses usconfig(2) to create a mutex. While this - method avoids the hassles of SysV-style semaphores, it is not - the default for IRIX. This is because on single processor - IRIX boxes (5.3 or 6.2) the uslock code is two orders of - magnitude slower than the SysV-semaphore code. On - multi-processor IRIX boxes the uslock code is an order of - magnitude faster than the SysV-semaphore code. Kind of a - messed up situation. So if you're using a multiprocessor IRIX - box then you should rebuild your webserver with - -DUSE_USLOCK_SERIALIZED_ACCEPT on the - EXTRA_CFLAGS.
- -
USE_PTHREAD_SERIALIZED_ACCEPT
- -
(1.3 or later) This method uses POSIX mutexes and should - work on any architecture implementing the full POSIX threads - specification, however appears to only work on Solaris (2.5 - or later), and even then only in certain configurations. If - you experiment with this you should watch out for your server - hanging and not responding. Static content only servers may - work just fine.
-
- -

If your system has another method of serialization which - isn't in the above list then it may be worthwhile adding code - for it (and submitting a patch back to Apache).

- -

Another solution that has been considered but never - implemented is to partially serialize the loop -- that is, let - in a certain number of processes. This would only be of - interest on multiprocessor boxes where it's possible multiple - children could run simultaneously, and the serialization - actually doesn't take advantage of the full bandwidth. This is - a possible area of future investigation, but priority remains - low because highly parallel web servers are not the norm.

- -

Ideally you should run servers without multiple - Listen statements if you want the highest - performance. But read on.

- -

accept Serialization - single socket

- -

The above is fine and dandy for multiple socket servers, but - what about single socket servers? In theory they shouldn't - experience any of these same problems because all children can - just block in accept(2) until a connection - arrives, and no starvation results. In practice this hides - almost the same "spinning" behaviour discussed above in the - non-blocking solution. The way that most TCP stacks are - implemented, the kernel actually wakes up all processes blocked - in accept when a single connection arrives. One of - those processes gets the connection and returns to user-space, - the rest spin in the kernel and go back to sleep when they - discover there's no connection for them. This spinning is - hidden from the user-land code, but it's there nonetheless. - This can result in the same load-spiking wasteful behaviour - that a non-blocking solution to the multiple sockets case - can.

- -

For this reason we have found that many architectures behave - more "nicely" if we serialize even the single socket case. So - this is actually the default in almost all cases. Crude - experiments under Linux (2.0.30 on a dual Pentium pro 166 - w/128Mb RAM) have shown that the serialization of the single - socket case causes less than a 3% decrease in requests per - second over unserialized single-socket. But unserialized - single-socket showed an extra 100ms latency on each request. - This latency is probably a wash on long haul lines, and only an - issue on LANs. If you want to override the single socket - serialization you can define - SINGLE_LISTEN_UNSERIALIZED_ACCEPT and then - single-socket servers will not serialize at all.

- -

Lingering Close

- -

As discussed in - draft-ietf-http-connection-00.txt section 8, in order for - an HTTP server to reliably implement the - protocol it needs to shutdown each direction of the - communication independently (recall that a TCP connection is - bi-directional, each half is independent of the other). This - fact is often overlooked by other servers, but is correctly - implemented in Apache as of 1.2.

- -

When this feature was added to Apache it caused a flurry of - problems on various versions of Unix because of a - shortsightedness. The TCP specification does not state that the - FIN_WAIT_2 state has a timeout, but it doesn't prohibit it. On - systems without the timeout, Apache 1.2 induces many sockets - stuck forever in the FIN_WAIT_2 state. In many cases this can - be avoided by simply upgrading to the latest TCP/IP patches - supplied by the vendor. In cases where the vendor has never - released patches (i.e., SunOS4 -- although folks with - a source license can patch it themselves) we have decided to - disable this feature.

- -

There are two ways of accomplishing this. One is the socket - option SO_LINGER. But as fate would have it, this - has never been implemented properly in most TCP/IP stacks. Even - on those stacks with a proper implementation (i.e., - Linux 2.0.31) this method proves to be more expensive (cputime) - than the next solution.

- -

For the most part, Apache implements this in a function - called lingering_close (in - http_main.c). The function looks roughly like - this:

- -
-
-    void lingering_close (int s)
-    {
-    char junk_buffer[2048];
-
-    /* shutdown the sending side */
-    shutdown (s, 1);
-
-    signal (SIGALRM, lingering_death);
-    alarm (30);
-
-    for (;;) {
-        select (s for reading, 2 second timeout);
-        if (error) break;
-        if (s is ready for reading) {
-        if (read (s, junk_buffer, sizeof (junk_buffer)) <= 0) {
-            break;
-        }
-        /* just toss away whatever is here */
-        }
-    }
-
-    close (s);
-    }
-
-
- This naturally adds some expense at the end of a connection, - but it is required for a reliable implementation. As HTTP/1.1 - becomes more prevalent, and all connections are persistent, - this expense will be amortized over more requests. If you want - to play with fire and disable this feature you can define - NO_LINGCLOSE, but this is not recommended at all. - In particular, as HTTP/1.1 pipelined persistent connections - come into use lingering_close is an absolute - necessity (and - pipelined connections are faster, so you want to support - them). - -

Scoreboard File

- -

Apache's parent and children communicate with each other - through something called the scoreboard. Ideally this should be - implemented in shared memory. For those operating systems that - we either have access to, or have been given detailed ports - for, it typically is implemented using shared memory. The rest - default to using an on-disk file. The on-disk file is not only - slow, but it is unreliable (and less featured). Peruse the - src/main/conf.h file for your architecture and - look for either USE_MMAP_SCOREBOARD or - USE_SHMGET_SCOREBOARD. Defining one of those two - (as well as their companions HAVE_MMAP and - HAVE_SHMGET respectively) enables the supplied - shared memory code. If your system has another type of shared - memory, edit the file src/main/http_main.c and add - the hooks necessary to use it in Apache. (Send us back a patch - too please.)

- -

Historical note: The Linux port of Apache didn't start to - use shared memory until version 1.2 of Apache. This oversight - resulted in really poor and unreliable behaviour of earlier - versions of Apache on Linux.

- -

DYNAMIC_MODULE_LIMIT

- -

If you have no intention of using dynamically loaded modules - (you probably don't if you're reading this and tuning your - server for every last ounce of performance) then you should add - -DDYNAMIC_MODULE_LIMIT=0 when building your - server. This will save RAM that's allocated only for supporting - dynamically loaded modules.

-
- -

Appendix: Detailed Analysis of a - Trace

-

Here is a system call trace of Apache 2.0.38 with the worker MPM - on Solaris 8. This trace was collected using:

-
-truss -l -p httpd_child_pid. -
-

The -l option tells truss to log the ID of the - LWP (lightweight process--Solaris's form of kernel-level thread) - that invokes each system call.

- -

Other systems may have different system call tracing utilities - such as strace, ktrace, or par. - They all produce similar output.

- -

In this trace, a client has requested a 10KB static file - from the httpd. Traces of non-static requests or requests - with content negotiation look wildly different (and quite ugly - in some cases).

- -
-
-/67:    accept(3, 0x00200BEC, 0x00200C0C, 1) (sleeping...)
-/67:    accept(3, 0x00200BEC, 0x00200C0C, 1)            = 9
-
-
-
-

In this trace, the listener thread is running within LWP #67.

-

Note the lack of accept(2) serialization. On this particular -platform, the worker MPM uses an unserialized accept by default -unless it is listening on multiple ports.

-
-
-/65:    lwp_park(0x00000000, 0)                         = 0
-/67:    lwp_unpark(65, 1)                               = 0
-
-
-

Upon accepting the connection, the listener thread wakes up -a worker thread to do the request processing. In this trace, -the worker thread that handles the request is mapped to LWP #65.

-
-
-/65:    getsockname(9, 0x00200BA4, 0x00200BC4, 1)       = 0
-
-
-

In order to implement virtual hosts, Apache needs to know -the local socket address used to accept the connection. It -is possible to eliminate this call in many situations (such -as when there are no virtual hosts, or when Listen -directives are used which do not have wildcard addresses). But -no effort has yet been made to do these optimizations.

-
-
-/65:    brk(0x002170E8)                                 = 0
-/65:    brk(0x002190E8)                                 = 0
-
-
-

The brk(2) calls allocate memory from the heap. It is rare -to see these in a system call trace, because the httpd uses -custom memory allocators (apr_pool and -apr_bucket_alloc) for most request processing. -In this trace, the httpd has just been started, so it must -call malloc(3) to get the blocks of raw memory with which -to create the custom memory allocators.

-
-
-/65:    fcntl(9, F_GETFL, 0x00000000)                   = 2
-/65:    fstat64(9, 0xFAF7B818)                          = 0
-/65:    getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B910, 2190656) = 0
-/65:    fstat64(9, 0xFAF7B818)                          = 0
-/65:    getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B914, 2190656) = 0
-/65:    setsockopt(9, 65535, 8192, 0xFAF7B918, 4, 2190656) = 0
-/65:    fcntl(9, F_SETFL, 0x00000082)                   = 0
-
-
-

Next, the worker thread puts the connection to the client (file -descriptor 9) in non-blocking mode. The setsockopt(2) and getsockopt(2) -calls are a side-effect of how Solaris's libc handles fcntl(2) on sockets.

-
-
-/65:    read(9, " G E T   / 1 0 k . h t m".., 8000)     = 97
-
-
-

The worker thread reads the request from the client.

-
-
-/65:    stat("/var/httpd/apache/httpd-8999/htdocs/10k.html", 0xFAF7B978) = 0
-/65:    open("/var/httpd/apache/httpd-8999/htdocs/10k.html", O_RDONLY) = 10
-
-
-

This httpd has been configured with Options FollowSymLinks -and AllowOverride None. Thus it doesn't need to lstat(2) -each directory in the path leading up to the requested file, nor -check for .htaccess files. It simply calls stat(2) to -verify that the file: 1) exists, and 2) is a regular file, not a -directory.

-
-
-/65:    sendfilev(0, 9, 0x00200F90, 2, 0xFAF7B53C)      = 10269
-
-
-

In this example, the httpd is able to send the HTTP response -header and the requested file with a single sendfilev(2) system call. -Sendfile semantics vary among operating systems. On some other -systems, it is necessary to do a write(2) or writev(2) call to -send the headers before calling sendfile(2).

-
-
-/65:    write(4, " 1 2 7 . 0 . 0 . 1   -  ".., 78)      = 78
-
-
-

This write(2) call records the request in the access log. -Note that one thing missing from this trace is a time(2) call. -Unlike Apache 1.3, Apache 2.0 uses gettimeofday(3) to look up -the time. On some operating systems, like Linux or Solaris, -gettimeofday has an optimized implementation that doesn't require -as much overhead as a typical system call.

-
-
-/65:    shutdown(9, 1, 1)                               = 0
-/65:    poll(0xFAF7B980, 1, 2000)                       = 1
-/65:    read(9, 0xFAF7BC20, 512)                        = 0
-/65:    close(9)                                        = 0
-
-
-

The worker thread does a lingering close of the connection.

-
-
-/65:    close(10)                                       = 0
-/65:    lwp_park(0x00000000, 0)         (sleeping...)
-
-
-

Finally the worker thread closes the file that it has just delivered -and blocks until the listener assigns it another connection.

-
-
-/67:    accept(3, 0x001FEB74, 0x001FEB94, 1) (sleeping...)
-
-
-

Meanwhile, the listener thread is able to accept another connection -as soon as it has dispatched this connection to a worker thread (subject -to some flow-control logic in the worker MPM that throttles the listener -if all the available workers are busy). Though it isn't apparent from -this trace, the next accept(2) can (and usually does, under high load -conditions) occur in parallel with the worker thread's handling of the -just-accepted connection.

-
- - - - diff --git a/docs/manual/misc/perf-tuning.html.en b/docs/manual/misc/perf-tuning.html.en new file mode 100644 index 00000000000..08acc9f40a2 --- /dev/null +++ b/docs/manual/misc/perf-tuning.html.en @@ -0,0 +1,842 @@ + + +Apache Performance Notes - Apache HTTP Server
<-

Apache Performance Notes

+ +
Warning: + This document has not been fully updated + to take into account changes made in the 2.0 version of the + Apache HTTP Server. Some of the information may still be + relevant, but please use it with care.
+ +

Orignally written by Dean Gaudet.

+ +

Apache 2.0 is a general-purpose webserver, designed to + provide a balance of flexibility, portability, and performance. + Although it has not been designed specifically to set benchmark + records, Apache 2.0 is capable of high performance in many + real-world situations.

+ +

Compared to Apache 1.3, release 2.0 contains many additional + optimizations to increase throughput and scalability. Most of + these improvements are enabled by default. However, there are + compile-time and run-time configuration choices that can + significantly affect performance. This document describes the + options that a server administrator can configure to tune the + performance of an Apache 2.0 installation. Some of these + configuration options enable the httpd to better take advantage + of the capabilities of the hardware and OS, while others allow + the administrator to trade functionality for speed.

+ +
top

Hardware and Operating System Issues

+ + + +

The single biggest hardware issue affecting webserver + performance is RAM. A webserver should never ever have to swap, + swapping increases the latency of each request beyond a point + that users consider "fast enough". This causes users to hit + stop and reload, further increasing the load. You can, and + should, control the MaxClients setting so that your server + does not spawn so many children it starts swapping.

+ +

Beyond that the rest is mundane: get a fast enough CPU, a + fast enough network card, and fast enough disks, where "fast + enough" is something that needs to be determined by + experimentation.

+ +

Operating system choice is largely a matter of local + concerns. But some guidelines that have proven generally + useful are:

+ +
    +
  • +

    Run the latest stable release and patchlevel of the + operating system that you choose. Many OS suppliers have + introduced significant performance improvements to their + TCP stacks and thread libraries in recent years.

    +
  • + +
  • +

    If your OS supports a sendfile(2) system + call, make sure you install the release and/or patches + needed to enable it. (With Linux, for example, this means + using Linux 2.4 or later. For early releases of Solaris 8, + you may need to apply a patch.) On systems where it is + available, sendfile enables Apache 2 to deliver + static content faster and with lower CPU utilization.

    +
  • +
+ +
top

Run-Time Configuration Issues

+ + + + + +

HostnameLookups

+ + + +

Prior to Apache 1.3, HostnameLookups defaulted to On. + This adds latency to every request because it requires a + DNS lookup to complete before the request is finished. In + Apache 1.3 this setting defaults to Off. + However (1.3 or later), if you use any Allow from domain + or Deny from domain directives then you will pay for + a double reverse DNS lookup (a reverse, followed by a forward + to make sure that the reverse is not being spoofed). So for the + highest performance avoid using these directives (it's fine to + use IP addresses rather than domain names).

+ +

Note that it's possible to scope the directives, such as + within a <Location /server-status> section. + In this case the DNS lookups are only performed on requests + matching the criteria. Here's an example which disables lookups + except for .html and .cgi files:

+ +
+HostnameLookups off
+<Files ~ "\.(html|cgi)$">
+    HostnameLookups on
+</Files>
+
+ +

But even still, if you just need DNS names in some CGIs you + could consider doing the gethostbyname call in the + specific CGIs that need it.

+ +

Similarly, if you need to have hostname information in your + server logs in order to generate reports of this information, + you can postprocess your log file with logresolve, + so that these lookups can be done without making the client wait. + It is recommended that you do this postprocessing, and any other + statistical analysis of the log file, somewhere other than your + production web server machine, in order that this activity does + not adversely affect server performance.

+ + + +

FollowSymLinks and SymLinksIfOwnerMatch

+ + + +

Wherever in your URL-space you do not have an Options + FollowSymLinks, or you do have an Options + SymLinksIfOwnerMatch Apache will have to issue extra + system calls to check up on symlinks. One extra call per + filename component. For example, if you had:

+ +
+DocumentRoot /www/htdocs
+<Directory />
+    Options SymLinksIfOwnerMatch
+</Directory>
+
+ +

and a request is made for the URI /index.html. + Then Apache will perform lstat(2) on + /www, /www/htdocs, and + /www/htdocs/index.html. The results of these + lstats are never cached, so they will occur on + every single request. If you really desire the symlinks + security checking you can do something like this:

+ +
+DocumentRoot /www/htdocs
+<Directory />
+    Options FollowSymLinks
+</Directory>
+<Directory /www/htdocs>
+    Options -FollowSymLinks +SymLinksIfOwnerMatch
+</Directory>
+
+ +

This at least avoids the extra checks for the + DocumentRoot path. + Note that you'll need to add similar sections if you + have any Alias or + RewriteRule paths + outside of your document root. For highest performance, + and no symlink protection, set FollowSymLinks + everywhere, and never set SymLinksIfOwnerMatch.

+ + + +

AllowOverride

+ + + +

Wherever in your URL-space you allow overrides (typically + .htaccess files) Apache will attempt to open + .htaccess for each filename component. For + example,

+ +
+DocumentRoot /www/htdocs
+<Directory />
+    AllowOverride all
+</Directory>
+
+ +

and a request is made for the URI /index.html. + Then Apache will attempt to open /.htaccess, + /www/.htaccess, and + /www/htdocs/.htaccess. The solutions are similar + to the previous case of Options FollowSymLinks. + For highest performance use AllowOverride None + everywhere in your filesystem.

+ + + +

Negotiation

+ + + +

If at all possible, avoid content-negotiation if you're + really interested in every last ounce of performance. In + practice the benefits of negotiation outweigh the performance + penalties. There's one case where you can speed up the server. + Instead of using a wildcard such as:

+ +
+DirectoryIndex index
+
+ +

Use a complete list of options:

+ +
+DirectoryIndex index.cgi index.pl index.shtml index.html
+
+ +

where you list the most common choice first.

+ +

Also note that explicitly creating a type-map + file provides better performance than using + MultiViews, as the necessary information can be + determined by reading this single file, rather than having to + scan the directory for files.

+ + + +

Memory-mapping

+ + + +

In situations where Apache 2.0 needs to look at the contents + of a file being delivered--for example, when doing server-side-include + processing--it normally memory-maps the file if the OS supports + some form of mmap(2).

+ +

On some platforms, this memory-mapping improves performance. + However, there are cases where memory-mapping can hurt the performance + or even the stability of the httpd:

+ +
    +
  • +

    On some operating systems, mmap does not scale + as well as read(2) when the number of CPUs increases. + On multiprocessor Solaris servers, for example, Apache 2.0 sometimes + delivers server-parsed files faster when mmap is disabled.

    +
  • + +
  • +

    If you memory-map a file located on an NFS-mounted filesystem + and a process on another NFS client machine deletes or truncates + the file, your process may get a bus error the next time it tries + to access the mapped file content.

    +
  • +
+ +

For installations where either of these factors applies, you + should use EnableMMAP off to disable the memory-mapping + of delivered files. (Note: This directive can be overridden on + a per-directory basis.)

+ + + +

Process Creation

+ + + +

Prior to Apache 1.3 the MinSpareServers, MaxSpareServers, and StartServers settings all had drastic effects on + benchmark results. In particular, Apache required a "ramp-up" + period in order to reach a number of children sufficient to serve + the load being applied. After the initial spawning of + StartServers children, + only one child per second would be created to satisfy the + MinSpareServers + setting. So a server being accessed by 100 simultaneous + clients, using the default StartServers of 5 would take on + the order 95 seconds to spawn enough children to handle + the load. This works fine in practice on real-life servers, + because they aren't restarted frequently. But does really + poorly on benchmarks which might only run for ten minutes.

+ +

The one-per-second rule was implemented in an effort to + avoid swamping the machine with the startup of new children. If + the machine is busy spawning children it can't service + requests. But it has such a drastic effect on the perceived + performance of Apache that it had to be replaced. As of Apache + 1.3, the code will relax the one-per-second rule. It will spawn + one, wait a second, then spawn two, wait a second, then spawn + four, and it will continue exponentially until it is spawning + 32 children per second. It will stop whenever it satisfies the + MinSpareServers + setting.

+ +

This appears to be responsive enough that it's almost + unnecessary to twiddle the MinSpareServers, MaxSpareServers and StartServers knobs. When more than 4 children are + spawned per second, a message will be emitted to the + ErrorLog. If you + see a lot of these errors then consider tuning these settings. + Use the mod_status output as a guide.

+ +

Related to process creation is process death induced by the + MaxRequestsPerChild + setting. By default this is 0, + which means that there is no limit to the number of requests + handled per child. If your configuration currently has this set + to some very low number, such as 30, you may want to bump this + up significantly. If you are running SunOS or an old version of + Solaris, limit this to 10000 or so because of memory leaks.

+ +

When keep-alives are in use, children will be kept busy + doing nothing waiting for more requests on the already open + connection. The default KeepAliveTimeout of 15 + seconds attempts to minimize this effect. The tradeoff here is + between network bandwidth and server resources. In no event + should you raise this above about 60 seconds, as + most of the benefits are lost.

+ + + +
top

Compile-Time Configuration Issues

+ + + +

mod_status and ExtendedStatus On

+ + + +

If you include mod_status and you also set + ExtendedStatus On when building and running + Apache, then on every request Apache will perform two calls to + gettimeofday(2) (or times(2) + depending on your operating system), and (pre-1.3) several + extra calls to time(2). This is all done so that + the status report contains timing indications. For highest + performance, set ExtendedStatus off (which is the + default).

+ + + +

accept Serialization - multiple sockets

+ + + +

This discusses a shortcoming in the Unix socket API. Suppose + your web server uses multiple Listen statements to listen on either multiple + ports or multiple addresses. In order to test each socket + to see if a connection is ready Apache uses + select(2). select(2) indicates that a + socket has zero or at least one connection + waiting on it. Apache's model includes multiple children, and + all the idle ones test for new connections at the same time. A + naive implementation looks something like this (these examples + do not match the code, they're contrived for pedagogical + purposes):

+ +
+    for (;;) {
+    for (;;) {
+        fd_set accept_fds;
+
+        FD_ZERO (&accept_fds);
+        for (i = first_socket; i <= last_socket; ++i) {
+        FD_SET (i, &accept_fds);
+        }
+        rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL);
+        if (rc < 1) continue;
+        new_connection = -1;
+        for (i = first_socket; i <= last_socket; ++i) {
+        if (FD_ISSET (i, &accept_fds)) {
+            new_connection = accept (i, NULL, NULL);
+            if (new_connection != -1) break;
+        }
+        }
+        if (new_connection != -1) break;
+    }
+    process the new_connection;
+    }
+
+ +

But this naive implementation has a serious starvation problem. + Recall that multiple children execute this loop at the same + time, and so multiple children will block at + select when they are in between requests. All + those blocked children will awaken and return from + select when a single request appears on any socket + (the number of children which awaken varies depending on the + operating system and timing issues). They will all then fall + down into the loop and try to accept the + connection. But only one will succeed (assuming there's still + only one connection ready), the rest will be blocked + in accept. This effectively locks those children + into serving requests from that one socket and no other + sockets, and they'll be stuck there until enough new requests + appear on that socket to wake them all up. This starvation + problem was first documented in PR#467. There + are at least two solutions.

+ +

One solution is to make the sockets non-blocking. In this + case the accept won't block the children, and they + will be allowed to continue immediately. But this wastes CPU + time. Suppose you have ten idle children in + select, and one connection arrives. Then nine of + those children will wake up, try to accept the + connection, fail, and loop back into select, + accomplishing nothing. Meanwhile none of those children are + servicing requests that occurred on other sockets until they + get back up to the select again. Overall this + solution does not seem very fruitful unless you have as many + idle CPUs (in a multiprocessor box) as you have idle children, + not a very likely situation.

+ +

Another solution, the one used by Apache, is to serialize + entry into the inner loop. The loop looks like this + (differences highlighted):

+ +
+    for (;;) {
+    accept_mutex_on ();
+    for (;;) {
+        fd_set accept_fds;
+
+        FD_ZERO (&accept_fds);
+        for (i = first_socket; i <= last_socket; ++i) {
+        FD_SET (i, &accept_fds);
+        }
+        rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL);
+        if (rc < 1) continue;
+        new_connection = -1;
+        for (i = first_socket; i <= last_socket; ++i) {
+        if (FD_ISSET (i, &accept_fds)) {
+            new_connection = accept (i, NULL, NULL);
+            if (new_connection != -1) break;
+        }
+        }
+        if (new_connection != -1) break;
+    }
+    accept_mutex_off ();
+    process the new_connection;
+    }
+
+ +

The functions + accept_mutex_on and accept_mutex_off + implement a mutual exclusion semaphore. Only one child can have + the mutex at any time. There are several choices for + implementing these mutexes. The choice is defined in + src/conf.h (pre-1.3) or + src/include/ap_config.h (1.3 or later). Some + architectures do not have any locking choice made, on these + architectures it is unsafe to use multiple + Listen + directives.

+ +
+
USE_FLOCK_SERIALIZED_ACCEPT
+ +
+

This method uses the flock(2) system call to + lock a lock file (located by the LockFile directive).

+
+ +
USE_FCNTL_SERIALIZED_ACCEPT
+ +
+

This method uses the fcntl(2) system call to + lock a lock file (located by the LockFile directive).

+
+ +
USE_SYSVSEM_SERIALIZED_ACCEPT
+ +
+

(1.3 or later) This method uses SysV-style semaphores to + implement the mutex. Unfortunately SysV-style semaphores have + some bad side-effects. One is that it's possible Apache will + die without cleaning up the semaphore (see the + ipcs(8) man page). The other is that the + semaphore API allows for a denial of service attack by any + CGIs running under the same uid as the webserver + (i.e., all CGIs, unless you use something like + suexec or cgiwrapper). For these + reasons this method is not used on any architecture except + IRIX (where the previous two are prohibitively expensive + on most IRIX boxes).

+
+ +
USE_USLOCK_SERIALIZED_ACCEPT
+ +
+

(1.3 or later) This method is only available on IRIX, and + uses usconfig(2) to create a mutex. While this + method avoids the hassles of SysV-style semaphores, it is not + the default for IRIX. This is because on single processor + IRIX boxes (5.3 or 6.2) the uslock code is two orders of + magnitude slower than the SysV-semaphore code. On + multi-processor IRIX boxes the uslock code is an order of + magnitude faster than the SysV-semaphore code. Kind of a + messed up situation. So if you're using a multiprocessor IRIX + box then you should rebuild your webserver with + -DUSE_USLOCK_SERIALIZED_ACCEPT on the + EXTRA_CFLAGS.

+
+ +
USE_PTHREAD_SERIALIZED_ACCEPT
+ +
+

(1.3 or later) This method uses POSIX mutexes and should + work on any architecture implementing the full POSIX threads + specification, however appears to only work on Solaris (2.5 + or later), and even then only in certain configurations. If + you experiment with this you should watch out for your server + hanging and not responding. Static content only servers may + work just fine.

+
+
+ +

If your system has another method of serialization which + isn't in the above list then it may be worthwhile adding code + for it (and submitting a patch back to Apache).

+ +

Another solution that has been considered but never + implemented is to partially serialize the loop -- that is, let + in a certain number of processes. This would only be of + interest on multiprocessor boxes where it's possible multiple + children could run simultaneously, and the serialization + actually doesn't take advantage of the full bandwidth. This is + a possible area of future investigation, but priority remains + low because highly parallel web servers are not the norm.

+ +

Ideally you should run servers without multiple + Listen + statements if you want the highest performance. + But read on.

+ + + +

accept Serialization - single socket

+ + + +

The above is fine and dandy for multiple socket servers, but + what about single socket servers? In theory they shouldn't + experience any of these same problems because all children can + just block in accept(2) until a connection + arrives, and no starvation results. In practice this hides + almost the same "spinning" behaviour discussed above in the + non-blocking solution. The way that most TCP stacks are + implemented, the kernel actually wakes up all processes blocked + in accept when a single connection arrives. One of + those processes gets the connection and returns to user-space, + the rest spin in the kernel and go back to sleep when they + discover there's no connection for them. This spinning is + hidden from the user-land code, but it's there nonetheless. + This can result in the same load-spiking wasteful behaviour + that a non-blocking solution to the multiple sockets case + can.

+ +

For this reason we have found that many architectures behave + more "nicely" if we serialize even the single socket case. So + this is actually the default in almost all cases. Crude + experiments under Linux (2.0.30 on a dual Pentium pro 166 + w/128Mb RAM) have shown that the serialization of the single + socket case causes less than a 3% decrease in requests per + second over unserialized single-socket. But unserialized + single-socket showed an extra 100ms latency on each request. + This latency is probably a wash on long haul lines, and only an + issue on LANs. If you want to override the single socket + serialization you can define + SINGLE_LISTEN_UNSERIALIZED_ACCEPT and then + single-socket servers will not serialize at all.

+ + + +

Lingering Close

+ + + +

As discussed in + draft-ietf-http-connection-00.txt section 8, in order for + an HTTP server to reliably implement the + protocol it needs to shutdown each direction of the + communication independently (recall that a TCP connection is + bi-directional, each half is independent of the other). This + fact is often overlooked by other servers, but is correctly + implemented in Apache as of 1.2.

+ +

When this feature was added to Apache it caused a flurry of + problems on various versions of Unix because of a + shortsightedness. The TCP specification does not state that the + FIN_WAIT_2 state has a timeout, but it doesn't prohibit it. + On systems without the timeout, Apache 1.2 induces many sockets + stuck forever in the FIN_WAIT_2 state. In many cases this + can be avoided by simply upgrading to the latest TCP/IP patches + supplied by the vendor. In cases where the vendor has never + released patches (i.e., SunOS4 -- although folks with + a source license can patch it themselves) we have decided to + disable this feature.

+ +

There are two ways of accomplishing this. One is the socket + option SO_LINGER. But as fate would have it, this + has never been implemented properly in most TCP/IP stacks. Even + on those stacks with a proper implementation (i.e., + Linux 2.0.31) this method proves to be more expensive (cputime) + than the next solution.

+ +

For the most part, Apache implements this in a function + called lingering_close (in + http_main.c). The function looks roughly like + this:

+ +
+    void lingering_close (int s)
+    {
+    char junk_buffer[2048];
+
+    /* shutdown the sending side */
+    shutdown (s, 1);
+
+    signal (SIGALRM, lingering_death);
+    alarm (30);
+
+    for (;;) {
+        select (s for reading, 2 second timeout);
+        if (error) break;
+        if (s is ready for reading) {
+        if (read (s, junk_buffer, sizeof (junk_buffer)) <= 0) {
+            break;
+        }
+        /* just toss away whatever is here */
+        }
+    }
+
+    close (s);
+    }
+
+ +

This naturally adds some expense at the end of a connection, + but it is required for a reliable implementation. As HTTP/1.1 + becomes more prevalent, and all connections are persistent, + this expense will be amortized over more requests. If you want + to play with fire and disable this feature you can define + NO_LINGCLOSE, but this is not recommended at all. + In particular, as HTTP/1.1 pipelined persistent connections + come into use lingering_close is an absolute + necessity (and + pipelined connections are faster, so you want to support + them).

+ + + +

Scoreboard File

+ + + +

Apache's parent and children communicate with each other + through something called the scoreboard. Ideally this should be + implemented in shared memory. For those operating systems that + we either have access to, or have been given detailed ports + for, it typically is implemented using shared memory. The rest + default to using an on-disk file. The on-disk file is not only + slow, but it is unreliable (and less featured). Peruse the + src/main/conf.h file for your architecture and + look for either USE_MMAP_SCOREBOARD or + USE_SHMGET_SCOREBOARD. Defining one of those two + (as well as their companions HAVE_MMAP and + HAVE_SHMGET respectively) enables the supplied + shared memory code. If your system has another type of shared + memory, edit the file src/main/http_main.c and add + the hooks necessary to use it in Apache. (Send us back a patch + too please.)

+ +
Historical note: The Linux port of Apache didn't start to + use shared memory until version 1.2 of Apache. This oversight + resulted in really poor and unreliable behaviour of earlier + versions of Apache on Linux.
+ + + +

DYNAMIC_MODULE_LIMIT

+ + + +

If you have no intention of using dynamically loaded modules + (you probably don't if you're reading this and tuning your + server for every last ounce of performance) then you should add + -DDYNAMIC_MODULE_LIMIT=0 when building your + server. This will save RAM that's allocated only for supporting + dynamically loaded modules.

+ + + +
top

Appendix: Detailed Analysis of a Trace

+ + + +

Here is a system call trace of Apache 2.0.38 with the worker MPM + on Solaris 8. This trace was collected using:

+ +

+ truss -l -p httpd_child_pid. +

+ +

The -l option tells truss to log the ID of the + LWP (lightweight process--Solaris's form of kernel-level thread) + that invokes each system call.

+ +

Other systems may have different system call tracing utilities + such as strace, ktrace, or par. + They all produce similar output.

+ +

In this trace, a client has requested a 10KB static file + from the httpd. Traces of non-static requests or requests + with content negotiation look wildly different (and quite ugly + in some cases).

+ +
+/67:    accept(3, 0x00200BEC, 0x00200C0C, 1) (sleeping...)
+/67:    accept(3, 0x00200BEC, 0x00200C0C, 1)            = 9
+
+ +

In this trace, the listener thread is running within LWP #67.

+ +
Note the lack of accept(2) serialization. On this + particular platform, the worker MPM uses an unserialized accept by + default unless it is listening on multiple ports.
+ +
+/65:    lwp_park(0x00000000, 0)                         = 0
+/67:    lwp_unpark(65, 1)                               = 0
+
+ +

Upon accepting the connection, the listener thread wakes up + a worker thread to do the request processing. In this trace, + the worker thread that handles the request is mapped to LWP #65.

+ +
+/65:    getsockname(9, 0x00200BA4, 0x00200BC4, 1)       = 0
+
+ +

In order to implement virtual hosts, Apache needs to know + the local socket address used to accept the connection. It + is possible to eliminate this call in many situations (such + as when there are no virtual hosts, or when + Listen directives + are used which do not have wildcard addresses). But + no effort has yet been made to do these optimizations.

+ +
+/65:    brk(0x002170E8)                                 = 0
+/65:    brk(0x002190E8)                                 = 0
+
+ +

The brk(2) calls allocate memory from the heap. + It is rare to see these in a system call trace, because the httpd + uses custom memory allocators (apr_pool and + apr_bucket_alloc) for most request processing. + In this trace, the httpd has just been started, so it must + call malloc(3) to get the blocks of raw memory + with which to create the custom memory allocators.

+ +
+/65:    fcntl(9, F_GETFL, 0x00000000)                   = 2
+/65:    fstat64(9, 0xFAF7B818)                          = 0
+/65:    getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B910, 2190656) = 0
+/65:    fstat64(9, 0xFAF7B818)                          = 0
+/65:    getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B914, 2190656) = 0
+/65:    setsockopt(9, 65535, 8192, 0xFAF7B918, 4, 2190656) = 0
+/65:    fcntl(9, F_SETFL, 0x00000082)                   = 0
+
+ +

Next, the worker thread puts the connection to the client (file + descriptor 9) in non-blocking mode. The setsockopt(2) + and getsockopt(2) calls are a side-effect of how + Solaris's libc handles fcntl(2) on sockets.

+ +
+/65:    read(9, " G E T   / 1 0 k . h t m".., 8000)     = 97
+
+ +

The worker thread reads the request from the client.

+ +
+/65:    stat("/var/httpd/apache/httpd-8999/htdocs/10k.html", 0xFAF7B978) = 0
+/65:    open("/var/httpd/apache/httpd-8999/htdocs/10k.html", O_RDONLY) = 10
+
+ +

This httpd has been configured with Options FollowSymLinks + and AllowOverride None. Thus it doesn't need to + lstat(2) each directory in the path leading up to the + requested file, nor check for .htaccess files. + It simply calls stat(2) to verify that the file: + 1) exists, and 2) is a regular file, not a directory.

+ +
+/65:    sendfilev(0, 9, 0x00200F90, 2, 0xFAF7B53C)      = 10269
+
+ +

In this example, the httpd is able to send the HTTP response + header and the requested file with a single sendfilev(2) + system call. Sendfile semantics vary among operating systems. On some other + systems, it is necessary to do a write(2) or + writev(2) call to send the headers before calling + sendfile(2).

+ +
+/65:    write(4, " 1 2 7 . 0 . 0 . 1   -  ".., 78)      = 78
+
+ +

This write(2) call records the request in the + access log. Note that one thing missing from this trace is a + time(2) call. Unlike Apache 1.3, Apache 2.0 uses + gettimeofday(3) to look up the time. On some operating + systems, like Linux or Solaris, gettimeofday has an + optimized implementation that doesn't require as much overhead + as a typical system call.

+ +
+/65:    shutdown(9, 1, 1)                               = 0
+/65:    poll(0xFAF7B980, 1, 2000)                       = 1
+/65:    read(9, 0xFAF7BC20, 512)                        = 0
+/65:    close(9)                                        = 0
+
+ +

The worker thread does a lingering close of the connection.

+ +
+/65:    close(10)                                       = 0
+/65:    lwp_park(0x00000000, 0)         (sleeping...)
+
+ +

Finally the worker thread closes the file that it has just delivered + and blocks until the listener assigns it another connection.

+ +
+/67:    accept(3, 0x001FEB74, 0x001FEB94, 1) (sleeping...)
+
+ +

Meanwhile, the listener thread is able to accept another connection + as soon as it has dispatched this connection to a worker thread (subject + to some flow-control logic in the worker MPM that throttles the listener + if all the available workers are busy). Though it isn't apparent from + this trace, the next accept(2) can (and usually does, under + high load conditions) occur in parallel with the worker thread's handling + of the just-accepted connection.

+ +
\ No newline at end of file diff --git a/docs/manual/misc/perf-tuning.xml b/docs/manual/misc/perf-tuning.xml new file mode 100644 index 00000000000..ddb3420d217 --- /dev/null +++ b/docs/manual/misc/perf-tuning.xml @@ -0,0 +1,891 @@ + + + + + + + + Apache Performance Notes + + + + Warning: + This document has not been fully updated + to take into account changes made in the 2.0 version of the + Apache HTTP Server. Some of the information may still be + relevant, but please use it with care. + +

Orignally written by Dean Gaudet.

+ +

Apache 2.0 is a general-purpose webserver, designed to + provide a balance of flexibility, portability, and performance. + Although it has not been designed specifically to set benchmark + records, Apache 2.0 is capable of high performance in many + real-world situations.

+ +

Compared to Apache 1.3, release 2.0 contains many additional + optimizations to increase throughput and scalability. Most of + these improvements are enabled by default. However, there are + compile-time and run-time configuration choices that can + significantly affect performance. This document describes the + options that a server administrator can configure to tune the + performance of an Apache 2.0 installation. Some of these + configuration options enable the httpd to better take advantage + of the capabilities of the hardware and OS, while others allow + the administrator to trade functionality for speed.

+ +
+ +
+ + Hardware and Operating System Issues + +

The single biggest hardware issue affecting webserver + performance is RAM. A webserver should never ever have to swap, + swapping increases the latency of each request beyond a point + that users consider "fast enough". This causes users to hit + stop and reload, further increasing the load. You can, and + should, control the MaxClients setting so that your server + does not spawn so many children it starts swapping.

+ +

Beyond that the rest is mundane: get a fast enough CPU, a + fast enough network card, and fast enough disks, where "fast + enough" is something that needs to be determined by + experimentation.

+ +

Operating system choice is largely a matter of local + concerns. But some guidelines that have proven generally + useful are:

+ +
    +
  • +

    Run the latest stable release and patchlevel of the + operating system that you choose. Many OS suppliers have + introduced significant performance improvements to their + TCP stacks and thread libraries in recent years.

    +
  • + +
  • +

    If your OS supports a sendfile(2) system + call, make sure you install the release and/or patches + needed to enable it. (With Linux, for example, this means + using Linux 2.4 or later. For early releases of Solaris 8, + you may need to apply a patch.) On systems where it is + available, sendfile enables Apache 2 to deliver + static content faster and with lower CPU utilization.

    +
  • +
+ +
+ +
+ + Run-Time Configuration Issues + + + + mod_dir + mpm_common + mod_status + + + AllowOverride + DirectoryIndex + HostnameLookups + EnableMMAP + KeepAliveTimeout + MaxSpareServers + MinSpareServers + Options + StartServers + + + +
+ + <code>HostnameLookups</code> + +

Prior to Apache 1.3, HostnameLookups defaulted to On. + This adds latency to every request because it requires a + DNS lookup to complete before the request is finished. In + Apache 1.3 this setting defaults to Off. + However (1.3 or later), if you use any Allow from domain + or Deny from domain directives then you will pay for + a double reverse DNS lookup (a reverse, followed by a forward + to make sure that the reverse is not being spoofed). So for the + highest performance avoid using these directives (it's fine to + use IP addresses rather than domain names).

+ +

Note that it's possible to scope the directives, such as + within a <Location /server-status> section. + In this case the DNS lookups are only performed on requests + matching the criteria. Here's an example which disables lookups + except for .html and .cgi files:

+ +
+HostnameLookups off
+<Files ~ "\.(html|cgi)$">
+    HostnameLookups on
+</Files>
+
+ +

But even still, if you just need DNS names in some CGIs you + could consider doing the gethostbyname call in the + specific CGIs that need it.

+ +

Similarly, if you need to have hostname information in your + server logs in order to generate reports of this information, + you can postprocess your log file with logresolve, + so that these lookups can be done without making the client wait. + It is recommended that you do this postprocessing, and any other + statistical analysis of the log file, somewhere other than your + production web server machine, in order that this activity does + not adversely affect server performance.

+ +
+ +
+ + <code>FollowSymLinks</code> and <code>SymLinksIfOwnerMatch</code> + +

Wherever in your URL-space you do not have an Options + FollowSymLinks, or you do have an Options + SymLinksIfOwnerMatch Apache will have to issue extra + system calls to check up on symlinks. One extra call per + filename component. For example, if you had:

+ +
+DocumentRoot /www/htdocs
+<Directory />
+    Options SymLinksIfOwnerMatch
+</Directory>
+
+ +

and a request is made for the URI /index.html. + Then Apache will perform lstat(2) on + /www, /www/htdocs, and + /www/htdocs/index.html. The results of these + lstats are never cached, so they will occur on + every single request. If you really desire the symlinks + security checking you can do something like this:

+ +
+DocumentRoot /www/htdocs
+<Directory />
+    Options FollowSymLinks
+</Directory>
+<Directory /www/htdocs>
+    Options -FollowSymLinks +SymLinksIfOwnerMatch
+</Directory>
+
+ +

This at least avoids the extra checks for the + DocumentRoot path. + Note that you'll need to add similar sections if you + have any Alias or + RewriteRule paths + outside of your document root. For highest performance, + and no symlink protection, set FollowSymLinks + everywhere, and never set SymLinksIfOwnerMatch.

+ +
+ +
+ + <code>AllowOverride</code> + +

Wherever in your URL-space you allow overrides (typically + .htaccess files) Apache will attempt to open + .htaccess for each filename component. For + example,

+ +
+DocumentRoot /www/htdocs
+<Directory />
+    AllowOverride all
+</Directory>
+
+ +

and a request is made for the URI /index.html. + Then Apache will attempt to open /.htaccess, + /www/.htaccess, and + /www/htdocs/.htaccess. The solutions are similar + to the previous case of Options FollowSymLinks. + For highest performance use AllowOverride None + everywhere in your filesystem.

+ +
+ +
+ + Negotiation + +

If at all possible, avoid content-negotiation if you're + really interested in every last ounce of performance. In + practice the benefits of negotiation outweigh the performance + penalties. There's one case where you can speed up the server. + Instead of using a wildcard such as:

+ +
+DirectoryIndex index
+
+ +

Use a complete list of options:

+ +
+DirectoryIndex index.cgi index.pl index.shtml index.html
+
+ +

where you list the most common choice first.

+ +

Also note that explicitly creating a type-map + file provides better performance than using + MultiViews, as the necessary information can be + determined by reading this single file, rather than having to + scan the directory for files.

+ +
+ +
+ + Memory-mapping + +

In situations where Apache 2.0 needs to look at the contents + of a file being delivered--for example, when doing server-side-include + processing--it normally memory-maps the file if the OS supports + some form of mmap(2).

+ +

On some platforms, this memory-mapping improves performance. + However, there are cases where memory-mapping can hurt the performance + or even the stability of the httpd:

+ +
    +
  • +

    On some operating systems, mmap does not scale + as well as read(2) when the number of CPUs increases. + On multiprocessor Solaris servers, for example, Apache 2.0 sometimes + delivers server-parsed files faster when mmap is disabled.

    +
  • + +
  • +

    If you memory-map a file located on an NFS-mounted filesystem + and a process on another NFS client machine deletes or truncates + the file, your process may get a bus error the next time it tries + to access the mapped file content.

    +
  • +
+ +

For installations where either of these factors applies, you + should use EnableMMAP off to disable the memory-mapping + of delivered files. (Note: This directive can be overridden on + a per-directory basis.)

+ +
+ +
+ + Process Creation + +

Prior to Apache 1.3 the MinSpareServers, MaxSpareServers, and StartServers settings all had drastic effects on + benchmark results. In particular, Apache required a "ramp-up" + period in order to reach a number of children sufficient to serve + the load being applied. After the initial spawning of + StartServers children, + only one child per second would be created to satisfy the + MinSpareServers + setting. So a server being accessed by 100 simultaneous + clients, using the default StartServers of 5 would take on + the order 95 seconds to spawn enough children to handle + the load. This works fine in practice on real-life servers, + because they aren't restarted frequently. But does really + poorly on benchmarks which might only run for ten minutes.

+ +

The one-per-second rule was implemented in an effort to + avoid swamping the machine with the startup of new children. If + the machine is busy spawning children it can't service + requests. But it has such a drastic effect on the perceived + performance of Apache that it had to be replaced. As of Apache + 1.3, the code will relax the one-per-second rule. It will spawn + one, wait a second, then spawn two, wait a second, then spawn + four, and it will continue exponentially until it is spawning + 32 children per second. It will stop whenever it satisfies the + MinSpareServers + setting.

+ +

This appears to be responsive enough that it's almost + unnecessary to twiddle the MinSpareServers, MaxSpareServers and StartServers knobs. When more than 4 children are + spawned per second, a message will be emitted to the + ErrorLog. If you + see a lot of these errors then consider tuning these settings. + Use the mod_status output as a guide.

+ +

Related to process creation is process death induced by the + MaxRequestsPerChild + setting. By default this is 0, + which means that there is no limit to the number of requests + handled per child. If your configuration currently has this set + to some very low number, such as 30, you may want to bump this + up significantly. If you are running SunOS or an old version of + Solaris, limit this to 10000 or so because of memory leaks.

+ +

When keep-alives are in use, children will be kept busy + doing nothing waiting for more requests on the already open + connection. The default KeepAliveTimeout of 15 + seconds attempts to minimize this effect. The tradeoff here is + between network bandwidth and server resources. In no event + should you raise this above about 60 seconds, as + most of the benefits are lost.

+ +
+ +
+ +
+ + Compile-Time Configuration Issues + +
+ + mod_status and ExtendedStatus On + +

If you include mod_status and you also set + ExtendedStatus On when building and running + Apache, then on every request Apache will perform two calls to + gettimeofday(2) (or times(2) + depending on your operating system), and (pre-1.3) several + extra calls to time(2). This is all done so that + the status report contains timing indications. For highest + performance, set ExtendedStatus off (which is the + default).

+ +
+ +
+ + accept Serialization - multiple sockets + +

This discusses a shortcoming in the Unix socket API. Suppose + your web server uses multiple Listen statements to listen on either multiple + ports or multiple addresses. In order to test each socket + to see if a connection is ready Apache uses + select(2). select(2) indicates that a + socket has zero or at least one connection + waiting on it. Apache's model includes multiple children, and + all the idle ones test for new connections at the same time. A + naive implementation looks something like this (these examples + do not match the code, they're contrived for pedagogical + purposes):

+ +
+    for (;;) {
+    for (;;) {
+        fd_set accept_fds;
+
+        FD_ZERO (&accept_fds);
+        for (i = first_socket; i <= last_socket; ++i) {
+        FD_SET (i, &accept_fds);
+        }
+        rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL);
+        if (rc < 1) continue;
+        new_connection = -1;
+        for (i = first_socket; i <= last_socket; ++i) {
+        if (FD_ISSET (i, &accept_fds)) {
+            new_connection = accept (i, NULL, NULL);
+            if (new_connection != -1) break;
+        }
+        }
+        if (new_connection != -1) break;
+    }
+    process the new_connection;
+    }
+
+ +

But this naive implementation has a serious starvation problem. + Recall that multiple children execute this loop at the same + time, and so multiple children will block at + select when they are in between requests. All + those blocked children will awaken and return from + select when a single request appears on any socket + (the number of children which awaken varies depending on the + operating system and timing issues). They will all then fall + down into the loop and try to accept the + connection. But only one will succeed (assuming there's still + only one connection ready), the rest will be blocked + in accept. This effectively locks those children + into serving requests from that one socket and no other + sockets, and they'll be stuck there until enough new requests + appear on that socket to wake them all up. This starvation + problem was first documented in PR#467. There + are at least two solutions.

+ +

One solution is to make the sockets non-blocking. In this + case the accept won't block the children, and they + will be allowed to continue immediately. But this wastes CPU + time. Suppose you have ten idle children in + select, and one connection arrives. Then nine of + those children will wake up, try to accept the + connection, fail, and loop back into select, + accomplishing nothing. Meanwhile none of those children are + servicing requests that occurred on other sockets until they + get back up to the select again. Overall this + solution does not seem very fruitful unless you have as many + idle CPUs (in a multiprocessor box) as you have idle children, + not a very likely situation.

+ +

Another solution, the one used by Apache, is to serialize + entry into the inner loop. The loop looks like this + (differences highlighted):

+ +
+    for (;;) {
+    accept_mutex_on ();
+    for (;;) {
+        fd_set accept_fds;
+
+        FD_ZERO (&accept_fds);
+        for (i = first_socket; i <= last_socket; ++i) {
+        FD_SET (i, &accept_fds);
+        }
+        rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL);
+        if (rc < 1) continue;
+        new_connection = -1;
+        for (i = first_socket; i <= last_socket; ++i) {
+        if (FD_ISSET (i, &accept_fds)) {
+            new_connection = accept (i, NULL, NULL);
+            if (new_connection != -1) break;
+        }
+        }
+        if (new_connection != -1) break;
+    }
+    accept_mutex_off ();
+    process the new_connection;
+    }
+
+ +

The functions + accept_mutex_on and accept_mutex_off + implement a mutual exclusion semaphore. Only one child can have + the mutex at any time. There are several choices for + implementing these mutexes. The choice is defined in + src/conf.h (pre-1.3) or + src/include/ap_config.h (1.3 or later). Some + architectures do not have any locking choice made, on these + architectures it is unsafe to use multiple + Listen + directives.

+ +
+
USE_FLOCK_SERIALIZED_ACCEPT
+ +
+

This method uses the flock(2) system call to + lock a lock file (located by the LockFile directive).

+
+ +
USE_FCNTL_SERIALIZED_ACCEPT
+ +
+

This method uses the fcntl(2) system call to + lock a lock file (located by the LockFile directive).

+
+ +
USE_SYSVSEM_SERIALIZED_ACCEPT
+ +
+

(1.3 or later) This method uses SysV-style semaphores to + implement the mutex. Unfortunately SysV-style semaphores have + some bad side-effects. One is that it's possible Apache will + die without cleaning up the semaphore (see the + ipcs(8) man page). The other is that the + semaphore API allows for a denial of service attack by any + CGIs running under the same uid as the webserver + (i.e., all CGIs, unless you use something like + suexec or cgiwrapper). For these + reasons this method is not used on any architecture except + IRIX (where the previous two are prohibitively expensive + on most IRIX boxes).

+
+ +
USE_USLOCK_SERIALIZED_ACCEPT
+ +
+

(1.3 or later) This method is only available on IRIX, and + uses usconfig(2) to create a mutex. While this + method avoids the hassles of SysV-style semaphores, it is not + the default for IRIX. This is because on single processor + IRIX boxes (5.3 or 6.2) the uslock code is two orders of + magnitude slower than the SysV-semaphore code. On + multi-processor IRIX boxes the uslock code is an order of + magnitude faster than the SysV-semaphore code. Kind of a + messed up situation. So if you're using a multiprocessor IRIX + box then you should rebuild your webserver with + -DUSE_USLOCK_SERIALIZED_ACCEPT on the + EXTRA_CFLAGS.

+
+ +
USE_PTHREAD_SERIALIZED_ACCEPT
+ +
+

(1.3 or later) This method uses POSIX mutexes and should + work on any architecture implementing the full POSIX threads + specification, however appears to only work on Solaris (2.5 + or later), and even then only in certain configurations. If + you experiment with this you should watch out for your server + hanging and not responding. Static content only servers may + work just fine.

+
+
+ +

If your system has another method of serialization which + isn't in the above list then it may be worthwhile adding code + for it (and submitting a patch back to Apache).

+ +

Another solution that has been considered but never + implemented is to partially serialize the loop -- that is, let + in a certain number of processes. This would only be of + interest on multiprocessor boxes where it's possible multiple + children could run simultaneously, and the serialization + actually doesn't take advantage of the full bandwidth. This is + a possible area of future investigation, but priority remains + low because highly parallel web servers are not the norm.

+ +

Ideally you should run servers without multiple + Listen + statements if you want the highest performance. + But read on.

+ +
+ +
+ + accept Serialization - single socket + +

The above is fine and dandy for multiple socket servers, but + what about single socket servers? In theory they shouldn't + experience any of these same problems because all children can + just block in accept(2) until a connection + arrives, and no starvation results. In practice this hides + almost the same "spinning" behaviour discussed above in the + non-blocking solution. The way that most TCP stacks are + implemented, the kernel actually wakes up all processes blocked + in accept when a single connection arrives. One of + those processes gets the connection and returns to user-space, + the rest spin in the kernel and go back to sleep when they + discover there's no connection for them. This spinning is + hidden from the user-land code, but it's there nonetheless. + This can result in the same load-spiking wasteful behaviour + that a non-blocking solution to the multiple sockets case + can.

+ +

For this reason we have found that many architectures behave + more "nicely" if we serialize even the single socket case. So + this is actually the default in almost all cases. Crude + experiments under Linux (2.0.30 on a dual Pentium pro 166 + w/128Mb RAM) have shown that the serialization of the single + socket case causes less than a 3% decrease in requests per + second over unserialized single-socket. But unserialized + single-socket showed an extra 100ms latency on each request. + This latency is probably a wash on long haul lines, and only an + issue on LANs. If you want to override the single socket + serialization you can define + SINGLE_LISTEN_UNSERIALIZED_ACCEPT and then + single-socket servers will not serialize at all.

+ +
+ +
+ + Lingering Close + +

As discussed in + draft-ietf-http-connection-00.txt section 8, in order for + an HTTP server to reliably implement the + protocol it needs to shutdown each direction of the + communication independently (recall that a TCP connection is + bi-directional, each half is independent of the other). This + fact is often overlooked by other servers, but is correctly + implemented in Apache as of 1.2.

+ +

When this feature was added to Apache it caused a flurry of + problems on various versions of Unix because of a + shortsightedness. The TCP specification does not state that the + FIN_WAIT_2 state has a timeout, but it doesn't prohibit it. + On systems without the timeout, Apache 1.2 induces many sockets + stuck forever in the FIN_WAIT_2 state. In many cases this + can be avoided by simply upgrading to the latest TCP/IP patches + supplied by the vendor. In cases where the vendor has never + released patches (i.e., SunOS4 -- although folks with + a source license can patch it themselves) we have decided to + disable this feature.

+ +

There are two ways of accomplishing this. One is the socket + option SO_LINGER. But as fate would have it, this + has never been implemented properly in most TCP/IP stacks. Even + on those stacks with a proper implementation (i.e., + Linux 2.0.31) this method proves to be more expensive (cputime) + than the next solution.

+ +

For the most part, Apache implements this in a function + called lingering_close (in + http_main.c). The function looks roughly like + this:

+ +
+    void lingering_close (int s)
+    {
+    char junk_buffer[2048];
+
+    /* shutdown the sending side */
+    shutdown (s, 1);
+
+    signal (SIGALRM, lingering_death);
+    alarm (30);
+
+    for (;;) {
+        select (s for reading, 2 second timeout);
+        if (error) break;
+        if (s is ready for reading) {
+        if (read (s, junk_buffer, sizeof (junk_buffer)) <= 0) {
+            break;
+        }
+        /* just toss away whatever is here */
+        }
+    }
+
+    close (s);
+    }
+
+ +

This naturally adds some expense at the end of a connection, + but it is required for a reliable implementation. As HTTP/1.1 + becomes more prevalent, and all connections are persistent, + this expense will be amortized over more requests. If you want + to play with fire and disable this feature you can define + NO_LINGCLOSE, but this is not recommended at all. + In particular, as HTTP/1.1 pipelined persistent connections + come into use lingering_close is an absolute + necessity (and + pipelined connections are faster, so you want to support + them).

+ +
+ +
+ + Scoreboard File + +

Apache's parent and children communicate with each other + through something called the scoreboard. Ideally this should be + implemented in shared memory. For those operating systems that + we either have access to, or have been given detailed ports + for, it typically is implemented using shared memory. The rest + default to using an on-disk file. The on-disk file is not only + slow, but it is unreliable (and less featured). Peruse the + src/main/conf.h file for your architecture and + look for either USE_MMAP_SCOREBOARD or + USE_SHMGET_SCOREBOARD. Defining one of those two + (as well as their companions HAVE_MMAP and + HAVE_SHMGET respectively) enables the supplied + shared memory code. If your system has another type of shared + memory, edit the file src/main/http_main.c and add + the hooks necessary to use it in Apache. (Send us back a patch + too please.)

+ + Historical note: The Linux port of Apache didn't start to + use shared memory until version 1.2 of Apache. This oversight + resulted in really poor and unreliable behaviour of earlier + versions of Apache on Linux. + +
+ +
+ + <code>DYNAMIC_MODULE_LIMIT</code> + +

If you have no intention of using dynamically loaded modules + (you probably don't if you're reading this and tuning your + server for every last ounce of performance) then you should add + -DDYNAMIC_MODULE_LIMIT=0 when building your + server. This will save RAM that's allocated only for supporting + dynamically loaded modules.

+ +
+ +
+ +
+ + Appendix: Detailed Analysis of a Trace + +

Here is a system call trace of Apache 2.0.38 with the worker MPM + on Solaris 8. This trace was collected using:

+ + + truss -l -p httpd_child_pid. + + +

The -l option tells truss to log the ID of the + LWP (lightweight process--Solaris's form of kernel-level thread) + that invokes each system call.

+ +

Other systems may have different system call tracing utilities + such as strace, ktrace, or par. + They all produce similar output.

+ +

In this trace, a client has requested a 10KB static file + from the httpd. Traces of non-static requests or requests + with content negotiation look wildly different (and quite ugly + in some cases).

+ +
+/67:    accept(3, 0x00200BEC, 0x00200C0C, 1) (sleeping...)
+/67:    accept(3, 0x00200BEC, 0x00200C0C, 1)            = 9
+
+ +

In this trace, the listener thread is running within LWP #67.

+ + Note the lack of accept(2) serialization. On this + particular platform, the worker MPM uses an unserialized accept by + default unless it is listening on multiple ports. + +
+/65:    lwp_park(0x00000000, 0)                         = 0
+/67:    lwp_unpark(65, 1)                               = 0
+
+ +

Upon accepting the connection, the listener thread wakes up + a worker thread to do the request processing. In this trace, + the worker thread that handles the request is mapped to LWP #65.

+ +
+/65:    getsockname(9, 0x00200BA4, 0x00200BC4, 1)       = 0
+
+ +

In order to implement virtual hosts, Apache needs to know + the local socket address used to accept the connection. It + is possible to eliminate this call in many situations (such + as when there are no virtual hosts, or when + Listen directives + are used which do not have wildcard addresses). But + no effort has yet been made to do these optimizations.

+ +
+/65:    brk(0x002170E8)                                 = 0
+/65:    brk(0x002190E8)                                 = 0
+
+ +

The brk(2) calls allocate memory from the heap. + It is rare to see these in a system call trace, because the httpd + uses custom memory allocators (apr_pool and + apr_bucket_alloc) for most request processing. + In this trace, the httpd has just been started, so it must + call malloc(3) to get the blocks of raw memory + with which to create the custom memory allocators.

+ +
+/65:    fcntl(9, F_GETFL, 0x00000000)                   = 2
+/65:    fstat64(9, 0xFAF7B818)                          = 0
+/65:    getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B910, 2190656) = 0
+/65:    fstat64(9, 0xFAF7B818)                          = 0
+/65:    getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B914, 2190656) = 0
+/65:    setsockopt(9, 65535, 8192, 0xFAF7B918, 4, 2190656) = 0
+/65:    fcntl(9, F_SETFL, 0x00000082)                   = 0
+
+ +

Next, the worker thread puts the connection to the client (file + descriptor 9) in non-blocking mode. The setsockopt(2) + and getsockopt(2) calls are a side-effect of how + Solaris's libc handles fcntl(2) on sockets.

+ +
+/65:    read(9, " G E T   / 1 0 k . h t m".., 8000)     = 97
+
+ +

The worker thread reads the request from the client.

+ +
+/65:    stat("/var/httpd/apache/httpd-8999/htdocs/10k.html", 0xFAF7B978) = 0
+/65:    open("/var/httpd/apache/httpd-8999/htdocs/10k.html", O_RDONLY) = 10
+
+ +

This httpd has been configured with Options FollowSymLinks + and AllowOverride None. Thus it doesn't need to + lstat(2) each directory in the path leading up to the + requested file, nor check for .htaccess files. + It simply calls stat(2) to verify that the file: + 1) exists, and 2) is a regular file, not a directory.

+ +
+/65:    sendfilev(0, 9, 0x00200F90, 2, 0xFAF7B53C)      = 10269
+
+ +

In this example, the httpd is able to send the HTTP response + header and the requested file with a single sendfilev(2) + system call. Sendfile semantics vary among operating systems. On some other + systems, it is necessary to do a write(2) or + writev(2) call to send the headers before calling + sendfile(2).

+ +
+/65:    write(4, " 1 2 7 . 0 . 0 . 1   -  ".., 78)      = 78
+
+ +

This write(2) call records the request in the + access log. Note that one thing missing from this trace is a + time(2) call. Unlike Apache 1.3, Apache 2.0 uses + gettimeofday(3) to look up the time. On some operating + systems, like Linux or Solaris, gettimeofday has an + optimized implementation that doesn't require as much overhead + as a typical system call.

+ +
+/65:    shutdown(9, 1, 1)                               = 0
+/65:    poll(0xFAF7B980, 1, 2000)                       = 1
+/65:    read(9, 0xFAF7BC20, 512)                        = 0
+/65:    close(9)                                        = 0
+
+ +

The worker thread does a lingering close of the connection.

+ +
+/65:    close(10)                                       = 0
+/65:    lwp_park(0x00000000, 0)         (sleeping...)
+
+ +

Finally the worker thread closes the file that it has just delivered + and blocks until the listener assigns it another connection.

+ +
+/67:    accept(3, 0x001FEB74, 0x001FEB94, 1) (sleeping...)
+
+ +

Meanwhile, the listener thread is able to accept another connection + as soon as it has dispatched this connection to a worker thread (subject + to some flow-control logic in the worker MPM that throttles the listener + if all the available workers are busy). Though it isn't apparent from + this trace, the next accept(2) can (and usually does, under + high load conditions) occur in parallel with the worker thread's handling + of the just-accepted connection.

+ +
+ +
+ diff --git a/docs/manual/misc/rewriteguide.html.en b/docs/manual/misc/rewriteguide.html.en new file mode 100644 index 00000000000..19294a62cb7 --- /dev/null +++ b/docs/manual/misc/rewriteguide.html.en @@ -0,0 +1,2174 @@ + + +URL Rewriting Guide - Apache HTTP Server
<-

URL Rewriting Guide

+
+
Originally written by
+ Ralf S. Engelschall <rse@apache.org>
+ December 1997
+
+ +

This document supplements the mod_rewrite + reference documentation. + It describes how one can use Apache's mod_rewrite + to solve typical URL-based problems webmasters are usually confronted + with in practice. I give detailed descriptions on how to + solve each problem by configuring URL rewriting rulesets.

+ +
top

Introduction to mod_rewrite

+ + + +

The Apache module mod_rewrite is a killer + one, i.e. it is a really sophisticated module which provides + a powerful way to do URL manipulations. With it you can nearly + do all types of URL manipulations you ever dreamed about. + The price you have to pay is to accept complexity, because + mod_rewrite's major drawback is that it is + not easy to understand and use for the beginner. And even + Apache experts sometimes discover new aspects where + mod_rewrite can help.

+ +

In other words: With mod_rewrite you either + shoot yourself in the foot the first time and never use it again + or love it for the rest of your life because of its power. + This paper tries to give you a few initial success events to + avoid the first case by presenting already invented solutions + to you.

+ +
top

Practical Solutions

+ + + +

Here come a lot of practical solutions I've either invented + myself or collected from other peoples solutions in the past. + Feel free to learn the black magic of URL rewriting from + these examples.

+ +
ATTENTION: Depending on your server-configuration + it can be necessary to slightly change the examples for your + situation, e.g. adding the [PT] flag when + additionally using mod_alias and + mod_userdir, etc. Or rewriting a ruleset + to fit in .htaccess context instead + of per-server context. Always try to understand what a + particular ruleset really does before you use it. It + avoid problems.
+ +
top

URL Layout

+ + + +

Canonical URLs

+ + + +
+
Description:
+ +
+

On some webservers there are more than one URL for a + resource. Usually there are canonical URLs (which should be + actually used and distributed) and those which are just + shortcuts, internal ones, etc. Independent of which URL the + user supplied with the request he should finally see the + canonical one only.

+
+ +
Solution:
+ +
+

We do an external HTTP redirect for all non-canonical + URLs to fix them in the location view of the Browser and + for all subsequent requests. In the example ruleset below + we replace /~user by the canonical + /u/user and fix a missing trailing slash for + /u/user.

+ +
+RewriteRule   ^/~([^/]+)/?(.*)    /u/$1/$2  [R]
+RewriteRule   ^/([uge])/([^/]+)$  /$1/$2/   [R]
+
+
+
+ + + +

Canonical Hostnames

+ + + +
+
Description:
+ +
...
+ +
Solution:
+ +
+
+RewriteCond %{HTTP_HOST}   !^fully\.qualified\.domain\.name [NC]
+RewriteCond %{HTTP_HOST}   !^$
+RewriteCond %{SERVER_PORT} !^80$
+RewriteRule ^/(.*)         http://fully.qualified.domain.name:%{SERVER_PORT}/$1 [L,R]
+RewriteCond %{HTTP_HOST}   !^fully\.qualified\.domain\.name [NC]
+RewriteCond %{HTTP_HOST}   !^$
+RewriteRule ^/(.*)         http://fully.qualified.domain.name/$1 [L,R]
+
+
+
+ + + +

Moved DocumentRoot

+ + + +
+
Description:
+ +
+

Usually the DocumentRoot + of the webserver directly relates to the URL "/". + But often this data is not really of top-level priority, it is + perhaps just one entity of a lot of data pools. For instance at + our Intranet sites there are /e/www/ + (the homepage for WWW), /e/sww/ (the homepage for + the Intranet) etc. Now because the data of the DocumentRoot stays at /e/www/ we had + to make sure that all inlined images and other stuff inside this + data pool work for subsequent requests.

+
+ +
Solution:
+ +
+

We just redirect the URL / to + /e/www/. While is seems trivial it is + actually trivial with mod_rewrite, only. + Because the typical old mechanisms of URL Aliases + (as provides by mod_alias and friends) + only used prefix matching. With this you cannot + do such a redirection because the DocumentRoot is a prefix of all URLs. With + mod_rewrite it is really trivial:

+ +
+RewriteEngine on
+RewriteRule   ^/$  /e/www/  [R]
+
+
+
+ + + +

Trailing Slash Problem

+ + + +
+
Description:
+ +
+

Every webmaster can sing a song about the problem of + the trailing slash on URLs referencing directories. If they + are missing, the server dumps an error, because if you say + /~quux/foo instead of /~quux/foo/ + then the server searches for a file named + foo. And because this file is a directory it + complains. Actually it tries to fix it itself in most of + the cases, but sometimes this mechanism need to be emulated + by you. For instance after you have done a lot of + complicated URL rewritings to CGI scripts etc.

+
+ +
Solution:
+ +
+

The solution to this subtle problem is to let the server + add the trailing slash automatically. To do this + correctly we have to use an external redirect, so the + browser correctly requests subsequent images etc. If we + only did a internal rewrite, this would only work for the + directory page, but would go wrong when any images are + included into this page with relative URLs, because the + browser would request an in-lined object. For instance, a + request for image.gif in + /~quux/foo/index.html would become + /~quux/image.gif without the external + redirect!

+ +

So, to do this trick we write:

+ +
+RewriteEngine  on
+RewriteBase    /~quux/
+RewriteRule    ^foo$  foo/  [R]
+
+ +

The crazy and lazy can even do the following in the + top-level .htaccess file of their homedir. + But notice that this creates some processing + overhead.

+ +
+RewriteEngine  on
+RewriteBase    /~quux/
+RewriteCond    %{REQUEST_FILENAME}  -d
+RewriteRule    ^(.+[^/])$           $1/  [R]
+
+
+
+ + + +

Webcluster through Homogeneous URL Layout

+ + + +
+
Description:
+ +
+

We want to create a homogeneous and consistent URL + layout over all WWW servers on a Intranet webcluster, i.e. + all URLs (per definition server local and thus server + dependent!) become actually server independent! + What we want is to give the WWW namespace a consistent + server-independent layout: no URL should have to include + any physically correct target server. The cluster itself + should drive us automatically to the physical target + host.

+
+ +
Solution:
+ +
+

First, the knowledge of the target servers come from + (distributed) external maps which contain information + where our users, groups and entities stay. The have the + form

+ +
+user1  server_of_user1
+user2  server_of_user2
+:      :
+
+ +

We put them into files map.xxx-to-host. + Second we need to instruct all servers to redirect URLs + of the forms

+ +
+/u/user/anypath
+/g/group/anypath
+/e/entity/anypath
+
+ +

to

+ +
+http://physical-host/u/user/anypath
+http://physical-host/g/group/anypath
+http://physical-host/e/entity/anypath
+
+ +

when the URL is not locally valid to a server. The + following ruleset does this for us by the help of the map + files (assuming that server0 is a default server which + will be used if a user has no entry in the map):

+ +
+RewriteEngine on
+
+RewriteMap      user-to-host   txt:/path/to/map.user-to-host
+RewriteMap     group-to-host   txt:/path/to/map.group-to-host
+RewriteMap    entity-to-host   txt:/path/to/map.entity-to-host
+
+RewriteRule   ^/u/([^/]+)/?(.*)   http://${user-to-host:$1|server0}/u/$1/$2
+RewriteRule   ^/g/([^/]+)/?(.*)  http://${group-to-host:$1|server0}/g/$1/$2
+RewriteRule   ^/e/([^/]+)/?(.*) http://${entity-to-host:$1|server0}/e/$1/$2
+
+RewriteRule   ^/([uge])/([^/]+)/?$          /$1/$2/.www/
+RewriteRule   ^/([uge])/([^/]+)/([^.]+.+)   /$1/$2/.www/$3\
+
+
+
+ + + +

Move Homedirs to Different Webserver

+ + + +
+
Description:
+ +
+

Many webmasters have asked for a solution to the + following situation: They wanted to redirect just all + homedirs on a webserver to another webserver. They usually + need such things when establishing a newer webserver which + will replace the old one over time.

+
+ +
Solution:
+ +
+

The solution is trivial with mod_rewrite. + On the old webserver we just redirect all + /~user/anypath URLs to + http://newserver/~user/anypath.

+ +
+RewriteEngine on
+RewriteRule   ^/~(.+)  http://newserver/~$1  [R,L]
+
+
+
+ + + +

Structured Homedirs

+ + + +
+
Description:
+ +
+

Some sites with thousands of users usually use a + structured homedir layout, i.e. each homedir is in a + subdirectory which begins for instance with the first + character of the username. So, /~foo/anypath + is /home/f/foo/.www/anypath + while /~bar/anypath is + /home/b/bar/.www/anypath.

+
+ +
Solution:
+ +
+

We use the following ruleset to expand the tilde URLs + into exactly the above layout.

+ +
+RewriteEngine on
+RewriteRule   ^/~(([a-z])[a-z0-9]+)(.*)  /home/$2/$1/.www$3
+
+
+
+ + + +

Filesystem Reorganization

+ + + +
+
Description:
+ +
+

This really is a hardcore example: a killer application + which heavily uses per-directory + RewriteRules to get a smooth look and feel + on the Web while its data structure is never touched or + adjusted. Background: net.sw is + my archive of freely available Unix software packages, + which I started to collect in 1992. It is both my hobby + and job to to this, because while I'm studying computer + science I have also worked for many years as a system and + network administrator in my spare time. Every week I need + some sort of software so I created a deep hierarchy of + directories where I stored the packages:

+ +
+drwxrwxr-x   2 netsw  users    512 Aug  3 18:39 Audio/
+drwxrwxr-x   2 netsw  users    512 Jul  9 14:37 Benchmark/
+drwxrwxr-x  12 netsw  users    512 Jul  9 00:34 Crypto/
+drwxrwxr-x   5 netsw  users    512 Jul  9 00:41 Database/
+drwxrwxr-x   4 netsw  users    512 Jul 30 19:25 Dicts/
+drwxrwxr-x  10 netsw  users    512 Jul  9 01:54 Graphic/
+drwxrwxr-x   5 netsw  users    512 Jul  9 01:58 Hackers/
+drwxrwxr-x   8 netsw  users    512 Jul  9 03:19 InfoSys/
+drwxrwxr-x   3 netsw  users    512 Jul  9 03:21 Math/
+drwxrwxr-x   3 netsw  users    512 Jul  9 03:24 Misc/
+drwxrwxr-x   9 netsw  users    512 Aug  1 16:33 Network/
+drwxrwxr-x   2 netsw  users    512 Jul  9 05:53 Office/
+drwxrwxr-x   7 netsw  users    512 Jul  9 09:24 SoftEng/
+drwxrwxr-x   7 netsw  users    512 Jul  9 12:17 System/
+drwxrwxr-x  12 netsw  users    512 Aug  3 20:15 Typesetting/
+drwxrwxr-x  10 netsw  users    512 Jul  9 14:08 X11/
+
+ +

In July 1996 I decided to make this archive public to + the world via a nice Web interface. "Nice" means that I + wanted to offer an interface where you can browse + directly through the archive hierarchy. And "nice" means + that I didn't wanted to change anything inside this + hierarchy - not even by putting some CGI scripts at the + top of it. Why? Because the above structure should be + later accessible via FTP as well, and I didn't want any + Web or CGI stuff to be there.

+
+ +
Solution:
+ +
+

The solution has two parts: The first is a set of CGI + scripts which create all the pages at all directory + levels on-the-fly. I put them under + /e/netsw/.www/ as follows:

+ +
+-rw-r--r--   1 netsw  users    1318 Aug  1 18:10 .wwwacl
+drwxr-xr-x  18 netsw  users     512 Aug  5 15:51 DATA/
+-rw-rw-rw-   1 netsw  users  372982 Aug  5 16:35 LOGFILE
+-rw-r--r--   1 netsw  users     659 Aug  4 09:27 TODO
+-rw-r--r--   1 netsw  users    5697 Aug  1 18:01 netsw-about.html
+-rwxr-xr-x   1 netsw  users     579 Aug  2 10:33 netsw-access.pl
+-rwxr-xr-x   1 netsw  users    1532 Aug  1 17:35 netsw-changes.cgi
+-rwxr-xr-x   1 netsw  users    2866 Aug  5 14:49 netsw-home.cgi
+drwxr-xr-x   2 netsw  users     512 Jul  8 23:47 netsw-img/
+-rwxr-xr-x   1 netsw  users   24050 Aug  5 15:49 netsw-lsdir.cgi
+-rwxr-xr-x   1 netsw  users    1589 Aug  3 18:43 netsw-search.cgi
+-rwxr-xr-x   1 netsw  users    1885 Aug  1 17:41 netsw-tree.cgi
+-rw-r--r--   1 netsw  users     234 Jul 30 16:35 netsw-unlimit.lst
+
+ +

The DATA/ subdirectory holds the above + directory structure, i.e. the real + net.sw stuff and gets + automatically updated via rdist from time to + time. The second part of the problem remains: how to link + these two structures together into one smooth-looking URL + tree? We want to hide the DATA/ directory + from the user while running the appropriate CGI scripts + for the various URLs. Here is the solution: first I put + the following into the per-directory configuration file + in the DocumentRoot + of the server to rewrite the announced URL + /net.sw/ to the internal path + /e/netsw:

+ +
+RewriteRule  ^net.sw$       net.sw/        [R]
+RewriteRule  ^net.sw/(.*)$  e/netsw/$1
+
+ +

The first rule is for requests which miss the trailing + slash! The second rule does the real thing. And then + comes the killer configuration which stays in the + per-directory config file + /e/netsw/.www/.wwwacl:

+ +
+Options       ExecCGI FollowSymLinks Includes MultiViews
+
+RewriteEngine on
+
+#  we are reached via /net.sw/ prefix
+RewriteBase   /net.sw/
+
+#  first we rewrite the root dir to
+#  the handling cgi script
+RewriteRule   ^$                       netsw-home.cgi     [L]
+RewriteRule   ^index\.html$            netsw-home.cgi     [L]
+
+#  strip out the subdirs when
+#  the browser requests us from perdir pages
+RewriteRule   ^.+/(netsw-[^/]+/.+)$    $1                 [L]
+
+#  and now break the rewriting for local files
+RewriteRule   ^netsw-home\.cgi.*       -                  [L]
+RewriteRule   ^netsw-changes\.cgi.*    -                  [L]
+RewriteRule   ^netsw-search\.cgi.*     -                  [L]
+RewriteRule   ^netsw-tree\.cgi$        -                  [L]
+RewriteRule   ^netsw-about\.html$      -                  [L]
+RewriteRule   ^netsw-img/.*$           -                  [L]
+
+#  anything else is a subdir which gets handled
+#  by another cgi script
+RewriteRule   !^netsw-lsdir\.cgi.*     -                  [C]
+RewriteRule   (.*)                     netsw-lsdir.cgi/$1
+
+ +

Some hints for interpretation:

+ +
    +
  1. Notice the L (last) flag and no + substitution field ('-') in the forth part
  2. + +
  3. Notice the ! (not) character and + the C (chain) flag at the first rule + in the last part
  4. + +
  5. Notice the catch-all pattern in the last rule
  6. +
+
+
+ + + +

NCSA imagemap to Apache mod_imap

+ + + +
+
Description:
+ +
+

When switching from the NCSA webserver to the more + modern Apache webserver a lot of people want a smooth + transition. So they want pages which use their old NCSA + imagemap program to work under Apache with the + modern mod_imap. The problem is that there + are a lot of hyperlinks around which reference the + imagemap program via + /cgi-bin/imagemap/path/to/page.map. Under + Apache this has to read just + /path/to/page.map.

+
+ +
Solution:
+ +
+

We use a global rule to remove the prefix on-the-fly for + all requests:

+ +
+RewriteEngine  on
+RewriteRule    ^/cgi-bin/imagemap(.*)  $1  [PT]
+
+
+
+ + + +

Search pages in more than one directory

+ + + +
+
Description:
+ +
+

Sometimes it is necessary to let the webserver search + for pages in more than one directory. Here MultiViews or + other techniques cannot help.

+
+ +
Solution:
+ +
+

We program a explicit ruleset which searches for the + files in the directories.

+ +
+RewriteEngine on
+
+#   first try to find it in custom/...
+#   ...and if found stop and be happy:
+RewriteCond         /your/docroot/dir1/%{REQUEST_FILENAME}  -f
+RewriteRule  ^(.+)  /your/docroot/dir1/$1  [L]
+
+#   second try to find it in pub/...
+#   ...and if found stop and be happy:
+RewriteCond         /your/docroot/dir2/%{REQUEST_FILENAME}  -f
+RewriteRule  ^(.+)  /your/docroot/dir2/$1  [L]
+
+#   else go on for other Alias or ScriptAlias directives,
+#   etc.
+RewriteRule   ^(.+)  -  [PT]
+
+
+
+ + + +

Set Environment Variables According To URL Parts

+ + + +
+
Description:
+ +
+

Perhaps you want to keep status information between + requests and use the URL to encode it. But you don't want + to use a CGI wrapper for all pages just to strip out this + information.

+
+ +
Solution:
+ +
+

We use a rewrite rule to strip out the status information + and remember it via an environment variable which can be + later dereferenced from within XSSI or CGI. This way a + URL /foo/S=java/bar/ gets translated to + /foo/bar/ and the environment variable named + STATUS is set to the value "java".

+ +
+RewriteEngine on
+RewriteRule   ^(.*)/S=([^/]+)/(.*)    $1/$3 [E=STATUS:$2]
+
+
+
+ + + +

Virtual User Hosts

+ + + +
+
Description:
+ +
+

Assume that you want to provide + www.username.host.domain.com + for the homepage of username via just DNS A records to the + same machine and without any virtualhosts on this + machine.

+
+ +
Solution:
+ +
+

For HTTP/1.0 requests there is no solution, but for + HTTP/1.1 requests which contain a Host: HTTP header we + can use the following ruleset to rewrite + http://www.username.host.com/anypath + internally to /home/username/anypath:

+ +
+RewriteEngine on
+RewriteCond   %{HTTP_HOST}                 ^www\.[^.]+\.host\.com$
+RewriteRule   ^(.+)                        %{HTTP_HOST}$1          [C]
+RewriteRule   ^www\.([^.]+)\.host\.com(.*) /home/$1$2
+
+
+
+ + + +

Redirect Homedirs For Foreigners

+ + + +
+
Description:
+ +
+

We want to redirect homedir URLs to another webserver + www.somewhere.com when the requesting user + does not stay in the local domain + ourdomain.com. This is sometimes used in + virtual host contexts.

+
+ +
Solution:
+ +
+

Just a rewrite condition:

+ +
+RewriteEngine on
+RewriteCond   %{REMOTE_HOST}  !^.+\.ourdomain\.com$
+RewriteRule   ^(/~.+)         http://www.somewhere.com/$1 [R,L]
+
+
+
+ + + +

Redirect Failing URLs To Other Webserver

+ + + +
+
Description:
+ +
+

A typical FAQ about URL rewriting is how to redirect + failing requests on webserver A to webserver B. Usually + this is done via ErrorDocument CGI-scripts in Perl, but + there is also a mod_rewrite solution. + But notice that this performs more poorly than using an + ErrorDocument + CGI-script!

+
+ +
Solution:
+ +
+

The first solution has the best performance but less + flexibility, and is less error safe:

+ +
+RewriteEngine on
+RewriteCond   /your/docroot/%{REQUEST_FILENAME} !-f
+RewriteRule   ^(.+)                             http://webserverB.dom/$1
+
+ +

The problem here is that this will only work for pages + inside the DocumentRoot. While you can add more + Conditions (for instance to also handle homedirs, etc.) + there is better variant:

+ +
+RewriteEngine on
+RewriteCond   %{REQUEST_URI} !-U
+RewriteRule   ^(.+)          http://webserverB.dom/$1
+
+ +

This uses the URL look-ahead feature of mod_rewrite. + The result is that this will work for all types of URLs + and is a safe way. But it does a performance impact on + the webserver, because for every request there is one + more internal subrequest. So, if your webserver runs on a + powerful CPU, use this one. If it is a slow machine, use + the first approach or better a ErrorDocument CGI-script.

+
+
+ + + +

Extended Redirection

+ + + +
+
Description:
+ +
+

Sometimes we need more control (concerning the + character escaping mechanism) of URLs on redirects. + Usually the Apache kernels URL escape function also + escapes anchors, i.e. URLs like "url#anchor". + You cannot use this directly on redirects with + mod_rewrite because the + uri_escape() function of Apache + would also escape the hash character. + How can we redirect to such a URL?

+
+ +
Solution:
+ +
+

We have to use a kludge by the use of a NPH-CGI script + which does the redirect itself. Because here no escaping + is done (NPH=non-parseable headers). First we introduce a + new URL scheme xredirect: by the following + per-server config-line (should be one of the last rewrite + rules):

+ +
+RewriteRule ^xredirect:(.+) /path/to/nph-xredirect.cgi/$1 \
+            [T=application/x-httpd-cgi,L]
+
+ +

This forces all URLs prefixed with + xredirect: to be piped through the + nph-xredirect.cgi program. And this program + just looks like:

+ +
+#!/path/to/perl
+##
+##  nph-xredirect.cgi -- NPH/CGI script for extended redirects
+##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
+##
+
+$| = 1;
+$url = $ENV{'PATH_INFO'};
+
+print "HTTP/1.0 302 Moved Temporarily\n";
+print "Server: $ENV{'SERVER_SOFTWARE'}\n";
+print "Location: $url\n";
+print "Content-type: text/html\n";
+print "\n";
+print "<html>\n";
+print "<head>\n";
+print "<title>302 Moved Temporarily (EXTENDED)</title>\n";
+print "</head>\n";
+print "<body>\n";
+print "<h1>Moved Temporarily (EXTENDED)</h1>\n";
+print "The document has moved <a HREF=\"$url\">here</a>.<p>\n";
+print "</body>\n";
+print "</html>\n";
+
+##EOF##
+
+ +

This provides you with the functionality to do + redirects to all URL schemes, i.e. including the one + which are not directly accepted by mod_rewrite. + For instance you can now also redirect to + news:newsgroup via

+ +
+RewriteRule ^anyurl  xredirect:news:newsgroup
+
+ +
Notice: You have not to put [R] or + [R,L] to the above rule because the + xredirect: need to be expanded later + by our special "pipe through" rule above.
+
+
+ + + +

Archive Access Multiplexer

+ + + +
+
Description:
+ +
+

Do you know the great CPAN (Comprehensive Perl Archive + Network) under http://www.perl.com/CPAN? + This does a redirect to one of several FTP servers around + the world which carry a CPAN mirror and is approximately + near the location of the requesting client. Actually this + can be called an FTP access multiplexing service. While + CPAN runs via CGI scripts, how can a similar approach + implemented via mod_rewrite?

+
+ +
Solution:
+ +
+

First we notice that from version 3.0.0 + mod_rewrite can + also use the "ftp:" scheme on redirects. + And second, the location approximation can be done by a + RewriteMap + over the top-level domain of the client. + With a tricky chained ruleset we can use this top-level + domain as a key to our multiplexing map.

+ +
+RewriteEngine on
+RewriteMap    multiplex                txt:/path/to/map.cxan
+RewriteRule   ^/CxAN/(.*)              %{REMOTE_HOST}::$1                 [C]
+RewriteRule   ^.+\.([a-zA-Z]+)::(.*)$  ${multiplex:$1|ftp.default.dom}$2  [R,L]
+
+ +
+##
+##  map.cxan -- Multiplexing Map for CxAN
+##
+
+de        ftp://ftp.cxan.de/CxAN/
+uk        ftp://ftp.cxan.uk/CxAN/
+com       ftp://ftp.cxan.com/CxAN/
+ :
+##EOF##
+
+
+
+ + + +

Time-Dependent Rewriting

+ + + +
+
Description:
+ +
+

When tricks like time-dependent content should happen a + lot of webmasters still use CGI scripts which do for + instance redirects to specialized pages. How can it be done + via mod_rewrite?

+
+ +
Solution:
+ +
+

There are a lot of variables named TIME_xxx + for rewrite conditions. In conjunction with the special + lexicographic comparison patterns <STRING, + >STRING and =STRING we can + do time-dependent redirects:

+ +
+RewriteEngine on
+RewriteCond   %{TIME_HOUR}%{TIME_MIN} >0700
+RewriteCond   %{TIME_HOUR}%{TIME_MIN} <1900
+RewriteRule   ^foo\.html$             foo.day.html
+RewriteRule   ^foo\.html$             foo.night.html
+
+ +

This provides the content of foo.day.html + under the URL foo.html from + 07:00-19:00 and at the remaining time the + contents of foo.night.html. Just a nice + feature for a homepage...

+
+
+ + + +

Backward Compatibility for YYYY to XXXX migration

+ + + +
+
Description:
+ +
+

How can we make URLs backward compatible (still + existing virtually) after migrating document.YYYY + to document.XXXX, e.g. after translating a + bunch of .html files to .phtml?

+
+ +
Solution:
+ +
+

We just rewrite the name to its basename and test for + existence of the new extension. If it exists, we take + that name, else we rewrite the URL to its original state.

+ + +
+#   backward compatibility ruleset for
+#   rewriting document.html to document.phtml
+#   when and only when document.phtml exists
+#   but no longer document.html
+RewriteEngine on
+RewriteBase   /~quux/
+#   parse out basename, but remember the fact
+RewriteRule   ^(.*)\.html$              $1      [C,E=WasHTML:yes]
+#   rewrite to document.phtml if exists
+RewriteCond   %{REQUEST_FILENAME}.phtml -f
+RewriteRule   ^(.*)$ $1.phtml                   [S=1]
+#   else reverse the previous basename cutout
+RewriteCond   %{ENV:WasHTML}            ^yes$
+RewriteRule   ^(.*)$ $1.html
+
+
+
+ + + +
top

Content Handling

+ + + +

From Old to New (intern)

+ + + +
+
Description:
+ +
+

Assume we have recently renamed the page + bar.html to foo.html and now want + to provide the old URL for backward compatibility. Actually + we want that users of the old URL even not recognize that + the pages was renamed.

+
+ +
Solution:
+ +
+

We rewrite the old URL to the new one internally via the + following rule:

+ +
+RewriteEngine  on
+RewriteBase    /~quux/
+RewriteRule    ^foo\.html$  bar.html
+
+
+
+ + + +

From Old to New (extern)

+ + + +
+
Description:
+ +
+

Assume again that we have recently renamed the page + bar.html to foo.html and now want + to provide the old URL for backward compatibility. But this + time we want that the users of the old URL get hinted to + the new one, i.e. their browsers Location field should + change, too.

+
+ +
Solution:
+ +
+

We force a HTTP redirect to the new URL which leads to a + change of the browsers and thus the users view:

+ +
+RewriteEngine  on
+RewriteBase    /~quux/
+RewriteRule    ^foo\.html$  bar.html  [R]
+
+
+
+ + + +

Browser Dependent Content

+ + + +
+
Description:
+ +
+

At least for important top-level pages it is sometimes + necessary to provide the optimum of browser dependent + content, i.e. one has to provide a maximum version for the + latest Netscape variants, a minimum version for the Lynx + browsers and a average feature version for all others.

+
+ +
Solution:
+ +
+

We cannot use content negotiation because the browsers do + not provide their type in that form. Instead we have to + act on the HTTP header "User-Agent". The following condig + does the following: If the HTTP header "User-Agent" + begins with "Mozilla/3", the page foo.html + is rewritten to foo.NS.html and and the + rewriting stops. If the browser is "Lynx" or "Mozilla" of + version 1 or 2 the URL becomes foo.20.html. + All other browsers receive page foo.32.html. + This is done by the following ruleset:

+ +
+RewriteCond %{HTTP_USER_AGENT}  ^Mozilla/3.*
+RewriteRule ^foo\.html$         foo.NS.html          [L]
+
+RewriteCond %{HTTP_USER_AGENT}  ^Lynx/.*         [OR]
+RewriteCond %{HTTP_USER_AGENT}  ^Mozilla/[12].*
+RewriteRule ^foo\.html$         foo.20.html          [L]
+
+RewriteRule ^foo\.html$         foo.32.html          [L]
+
+
+
+ + + +

Dynamic Mirror

+ + + +
+
Description:
+ +
+

Assume there are nice webpages on remote hosts we want + to bring into our namespace. For FTP servers we would use + the mirror program which actually maintains an + explicit up-to-date copy of the remote data on the local + machine. For a webserver we could use the program + webcopy which acts similar via HTTP. But both + techniques have one major drawback: The local copy is + always just as up-to-date as often we run the program. It + would be much better if the mirror is not a static one we + have to establish explicitly. Instead we want a dynamic + mirror with data which gets updated automatically when + there is need (updated data on the remote host).

+
+ +
Solution:
+ +
+

To provide this feature we map the remote webpage or even + the complete remote webarea to our namespace by the use + of the Proxy Throughput feature + (flag [P]):

+ +
+RewriteEngine  on
+RewriteBase    /~quux/
+RewriteRule    ^hotsheet/(.*)$  http://www.tstimpreso.com/hotsheet/$1  [P]
+
+ +
+RewriteEngine  on
+RewriteBase    /~quux/
+RewriteRule    ^usa-news\.html$   http://www.quux-corp.com/news/index.html  [P]
+
+
+
+ + + +

Reverse Dynamic Mirror

+ + + +
+
Description:
+ +
...
+ +
Solution:
+ +
+
+RewriteEngine on
+RewriteCond   /mirror/of/remotesite/$1           -U
+RewriteRule   ^http://www\.remotesite\.com/(.*)$ /mirror/of/remotesite/$1
+
+
+
+ + + +

Retrieve Missing Data from Intranet

+ + + +
+
Description:
+ +
+

This is a tricky way of virtually running a corporate + (external) Internet webserver + (www.quux-corp.dom), while actually keeping + and maintaining its data on a (internal) Intranet webserver + (www2.quux-corp.dom) which is protected by a + firewall. The trick is that on the external webserver we + retrieve the requested data on-the-fly from the internal + one.

+
+ +
Solution:
+ +
+

First, we have to make sure that our firewall still + protects the internal webserver and that only the + external webserver is allowed to retrieve data from it. + For a packet-filtering firewall we could for instance + configure a firewall ruleset like the following:

+ +
+ALLOW Host www.quux-corp.dom Port >1024 --> Host www2.quux-corp.dom Port 80
+DENY  Host *                 Port *     --> Host www2.quux-corp.dom Port 80
+
+ +

Just adjust it to your actual configuration syntax. + Now we can establish the mod_rewrite + rules which request the missing data in the background + through the proxy throughput feature:

+ +
+RewriteRule ^/~([^/]+)/?(.*)          /home/$1/.www/$2
+RewriteCond %{REQUEST_FILENAME}       !-f
+RewriteCond %{REQUEST_FILENAME}       !-d
+RewriteRule ^/home/([^/]+)/.www/?(.*) http://www2.quux-corp.dom/~$1/pub/$2 [P]
+
+
+
+ + + +

Load Balancing

+ + + +
+
Description:
+ +
+

Suppose we want to load balance the traffic to + www.foo.com over www[0-5].foo.com + (a total of 6 servers). How can this be done?

+
+ +
Solution:
+ +
+

There are a lot of possible solutions for this problem. + We will discuss first a commonly known DNS-based variant + and then the special one with mod_rewrite:

+ +
    +
  1. + DNS Round-Robin + +

    The simplest method for load-balancing is to use + the DNS round-robin feature of BIND. + Here you just configure www[0-9].foo.com + as usual in your DNS with A(address) records, e.g.

    + +
    +www0   IN  A       1.2.3.1
    +www1   IN  A       1.2.3.2
    +www2   IN  A       1.2.3.3
    +www3   IN  A       1.2.3.4
    +www4   IN  A       1.2.3.5
    +www5   IN  A       1.2.3.6
    +
    + +

    Then you additionally add the following entry:

    + +
    +www    IN  CNAME   www0.foo.com.
    +       IN  CNAME   www1.foo.com.
    +       IN  CNAME   www2.foo.com.
    +       IN  CNAME   www3.foo.com.
    +       IN  CNAME   www4.foo.com.
    +       IN  CNAME   www5.foo.com.
    +       IN  CNAME   www6.foo.com.
    +
    + +

    Notice that this seems wrong, but is actually an + intended feature of BIND and can be used + in this way. However, now when www.foo.com gets + resolved, BIND gives out www0-www6 + - but in a slightly permutated/rotated order every time. + This way the clients are spread over the various + servers. But notice that this not a perfect load + balancing scheme, because DNS resolve information + gets cached by the other nameservers on the net, so + once a client has resolved www.foo.com + to a particular wwwN.foo.com, all + subsequent requests also go to this particular name + wwwN.foo.com. But the final result is + ok, because the total sum of the requests are really + spread over the various webservers.

    +
  2. + +
  3. + DNS Load-Balancing + +

    A sophisticated DNS-based method for + load-balancing is to use the program + lbnamed which can be found at + http://www.stanford.edu/~schemers/docs/lbnamed/lbnamed.html. + It is a Perl 5 program in conjunction with auxilliary + tools which provides a real load-balancing for + DNS.

    +
  4. + +
  5. + Proxy Throughput Round-Robin + +

    In this variant we use mod_rewrite + and its proxy throughput feature. First we dedicate + www0.foo.com to be actually + www.foo.com by using a single

    + +
    +www    IN  CNAME   www0.foo.com.
    +
    + +

    entry in the DNS. Then we convert + www0.foo.com to a proxy-only server, + i.e. we configure this machine so all arriving URLs + are just pushed through the internal proxy to one of + the 5 other servers (www1-www5). To + accomplish this we first establish a ruleset which + contacts a load balancing script lb.pl + for all URLs.

    + +
    +RewriteEngine on
    +RewriteMap    lb      prg:/path/to/lb.pl
    +RewriteRule   ^/(.+)$ ${lb:$1}           [P,L]
    +
    + +

    Then we write lb.pl:

    + +
    +#!/path/to/perl
    +##
    +##  lb.pl -- load balancing script
    +##
    +
    +$| = 1;
    +
    +$name   = "www";     # the hostname base
    +$first  = 1;         # the first server (not 0 here, because 0 is myself)
    +$last   = 5;         # the last server in the round-robin
    +$domain = "foo.dom"; # the domainname
    +
    +$cnt = 0;
    +while (<STDIN>) {
    +    $cnt = (($cnt+1) % ($last+1-$first));
    +    $server = sprintf("%s%d.%s", $name, $cnt+$first, $domain);
    +    print "http://$server/$_";
    +}
    +
    +##EOF##
    +
    + +
    A last notice: Why is this useful? Seems like + www0.foo.com still is overloaded? The + answer is yes, it is overloaded, but with plain proxy + throughput requests, only! All SSI, CGI, ePerl, etc. + processing is completely done on the other machines. + This is the essential point.
    +
  6. + +
  7. + Hardware/TCP Round-Robin + +

    There is a hardware solution available, too. Cisco + has a beast called LocalDirector which does a load + balancing at the TCP/IP level. Actually this is some + sort of a circuit level gateway in front of a + webcluster. If you have enough money and really need + a solution with high performance, use this one.

    +
  8. +
+
+
+ + + +

Reverse Proxy

+ + + +
+
Description:
+ +
...
+ +
Solution:
+ +
+
+##
+##  apache-rproxy.conf -- Apache configuration for Reverse Proxy Usage
+##
+
+#   server type
+ServerType           standalone
+Listen               8000
+MinSpareServers      16
+StartServers         16
+MaxSpareServers      16
+MaxClients           16
+MaxRequestsPerChild  100
+
+#   server operation parameters
+KeepAlive            on
+MaxKeepAliveRequests 100
+KeepAliveTimeout     15
+Timeout              400
+IdentityCheck        off
+HostnameLookups      off
+
+#   paths to runtime files
+PidFile              /path/to/apache-rproxy.pid
+LockFile             /path/to/apache-rproxy.lock
+ErrorLog             /path/to/apache-rproxy.elog
+CustomLog            /path/to/apache-rproxy.dlog "%{%v/%T}t %h -> %{SERVER}e URL: %U"
+
+#   unused paths
+ServerRoot           /tmp
+DocumentRoot         /tmp
+CacheRoot            /tmp
+RewriteLog           /dev/null
+TransferLog          /dev/null
+TypesConfig          /dev/null
+AccessConfig         /dev/null
+ResourceConfig       /dev/null
+
+#   speed up and secure processing
+<Directory />
+Options -FollowSymLinks -SymLinksIfOwnerMatch
+AllowOverride None
+</Directory>
+
+#   the status page for monitoring the reverse proxy
+<Location /apache-rproxy-status>
+SetHandler server-status
+</Location>
+
+#   enable the URL rewriting engine
+RewriteEngine        on
+RewriteLogLevel      0
+
+#   define a rewriting map with value-lists where
+#   mod_rewrite randomly chooses a particular value
+RewriteMap     server  rnd:/path/to/apache-rproxy.conf-servers
+
+#   make sure the status page is handled locally
+#   and make sure no one uses our proxy except ourself
+RewriteRule    ^/apache-rproxy-status.*  -  [L]
+RewriteRule    ^(http|ftp)://.*          -  [F]
+
+#   now choose the possible servers for particular URL types
+RewriteRule    ^/(.*\.(cgi|shtml))$  to://${server:dynamic}/$1  [S=1]
+RewriteRule    ^/(.*)$               to://${server:static}/$1
+
+#   and delegate the generated URL by passing it
+#   through the proxy module
+RewriteRule    ^to://([^/]+)/(.*)    http://$1/$2   [E=SERVER:$1,P,L]
+
+#   and make really sure all other stuff is forbidden
+#   when it should survive the above rules...
+RewriteRule    .*                    -              [F]
+
+#   enable the Proxy module without caching
+ProxyRequests        on
+NoCache              *
+
+#   setup URL reverse mapping for redirect reponses
+ProxyPassReverse  /  http://www1.foo.dom/
+ProxyPassReverse  /  http://www2.foo.dom/
+ProxyPassReverse  /  http://www3.foo.dom/
+ProxyPassReverse  /  http://www4.foo.dom/
+ProxyPassReverse  /  http://www5.foo.dom/
+ProxyPassReverse  /  http://www6.foo.dom/
+
+ +
+##
+##  apache-rproxy.conf-servers -- Apache/mod_rewrite selection table
+##
+
+#   list of backend servers which serve static
+#   pages (HTML files and Images, etc.)
+static    www1.foo.dom|www2.foo.dom|www3.foo.dom|www4.foo.dom
+
+#   list of backend servers which serve dynamically
+#   generated page (CGI programs or mod_perl scripts)
+dynamic   www5.foo.dom|www6.foo.dom
+
+
+
+ + + +

New MIME-type, New Service

+ + + +
+
Description:
+ +
+

On the net there are a lot of nifty CGI programs. But + their usage is usually boring, so a lot of webmaster + don't use them. Even Apache's Action handler feature for + MIME-types is only appropriate when the CGI programs + don't need special URLs (actually PATH_INFO + and QUERY_STRINGS) as their input. First, + let us configure a new file type with extension + .scgi (for secure CGI) which will be processed + by the popular cgiwrap program. The problem + here is that for instance we use a Homogeneous URL Layout + (see above) a file inside the user homedirs has the URL + /u/user/foo/bar.scgi. But + cgiwrap needs the URL in the form + /~user/foo/bar.scgi/. The following rule + solves the problem:

+ +
+RewriteRule ^/[uge]/([^/]+)/\.www/(.+)\.scgi(.*) ...
+... /internal/cgi/user/cgiwrap/~$1/$2.scgi$3  [NS,T=application/x-http-cgi]
+
+ +

Or assume we have some more nifty programs: + wwwlog (which displays the + access.log for a URL subtree and + wwwidx (which runs Glimpse on a URL + subtree). We have to provide the URL area to these + programs so they know on which area they have to act on. + But usually this ugly, because they are all the times + still requested from that areas, i.e. typically we would + run the swwidx program from within + /u/user/foo/ via hyperlink to

+ +
+/internal/cgi/user/swwidx?i=/u/user/foo/
+
+ +

which is ugly. Because we have to hard-code + both the location of the area + and the location of the CGI inside the + hyperlink. When we have to reorganize the area, we spend a + lot of time changing the various hyperlinks.

+
+ +
Solution:
+ +
+

The solution here is to provide a special new URL format + which automatically leads to the proper CGI invocation. + We configure the following:

+ +
+RewriteRule   ^/([uge])/([^/]+)(/?.*)/\*  /internal/cgi/user/wwwidx?i=/$1/$2$3/
+RewriteRule   ^/([uge])/([^/]+)(/?.*):log /internal/cgi/user/wwwlog?f=/$1/$2$3
+
+ +

Now the hyperlink to search at + /u/user/foo/ reads only

+ +
+HREF="*"
+
+ +

which internally gets automatically transformed to

+ +
+/internal/cgi/user/wwwidx?i=/u/user/foo/
+
+ +

The same approach leads to an invocation for the + access log CGI program when the hyperlink + :log gets used.

+
+
+ + + +

From Static to Dynamic

+ + + +
+
Description:
+ +
+

How can we transform a static page + foo.html into a dynamic variant + foo.cgi in a seamless way, i.e. without notice + by the browser/user.

+
+ +
Solution:
+ +
+

We just rewrite the URL to the CGI-script and force the + correct MIME-type so it gets really run as a CGI-script. + This way a request to /~quux/foo.html + internally leads to the invocation of + /~quux/foo.cgi.

+ +
+RewriteEngine  on
+RewriteBase    /~quux/
+RewriteRule    ^foo\.html$  foo.cgi  [T=application/x-httpd-cgi]
+
+
+
+ + + +

On-the-fly Content-Regeneration

+ + + +
+
Description:
+ +
+

Here comes a really esoteric feature: Dynamically + generated but statically served pages, i.e. pages should be + delivered as pure static pages (read from the filesystem + and just passed through), but they have to be generated + dynamically by the webserver if missing. This way you can + have CGI-generated pages which are statically served unless + one (or a cronjob) removes the static contents. Then the + contents gets refreshed.

+
+ +
Solution:
+ +
+ This is done via the following ruleset: + +
+RewriteCond %{REQUEST_FILENAME}   !-s
+RewriteRule ^page\.html$          page.cgi   [T=application/x-httpd-cgi,L]
+
+ +

Here a request to page.html leads to a + internal run of a corresponding page.cgi if + page.html is still missing or has filesize + null. The trick here is that page.cgi is a + usual CGI script which (additionally to its STDOUT) + writes its output to the file page.html. + Once it was run, the server sends out the data of + page.html. When the webmaster wants to force + a refresh the contents, he just removes + page.html (usually done by a cronjob).

+
+
+ + + +

Document With Autorefresh

+ + + +
+
Description:
+ +
+

Wouldn't it be nice while creating a complex webpage if + the webbrowser would automatically refresh the page every + time we write a new version from within our editor? + Impossible?

+
+ +
Solution:
+ +
+

No! We just combine the MIME multipart feature, the + webserver NPH feature and the URL manipulation power of + mod_rewrite. First, we establish a new + URL feature: Adding just :refresh to any + URL causes this to be refreshed every time it gets + updated on the filesystem.

+ +
+RewriteRule   ^(/[uge]/[^/]+/?.*):refresh  /internal/cgi/apache/nph-refresh?f=$1
+
+ +

Now when we reference the URL

+ +
+/u/foo/bar/page.html:refresh
+
+ +

this leads to the internal invocation of the URL

+ +
+/internal/cgi/apache/nph-refresh?f=/u/foo/bar/page.html
+
+ +

The only missing part is the NPH-CGI script. Although + one would usually say "left as an exercise to the reader" + ;-) I will provide this, too.

+ +
+#!/sw/bin/perl
+##
+##  nph-refresh -- NPH/CGI script for auto refreshing pages
+##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
+##
+$| = 1;
+
+#   split the QUERY_STRING variable
+@pairs = split(/&/, $ENV{'QUERY_STRING'});
+foreach $pair (@pairs) {
+    ($name, $value) = split(/=/, $pair);
+    $name =~ tr/A-Z/a-z/;
+    $name = 'QS_' . $name;
+    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
+    eval "\$$name = \"$value\"";
+}
+$QS_s = 1 if ($QS_s eq '');
+$QS_n = 3600 if ($QS_n eq '');
+if ($QS_f eq '') {
+    print "HTTP/1.0 200 OK\n";
+    print "Content-type: text/html\n\n";
+    print "&lt;b&gt;ERROR&lt;/b&gt;: No file given\n";
+    exit(0);
+}
+if (! -f $QS_f) {
+    print "HTTP/1.0 200 OK\n";
+    print "Content-type: text/html\n\n";
+    print "&lt;b&gt;ERROR&lt;/b&gt;: File $QS_f not found\n";
+    exit(0);
+}
+
+sub print_http_headers_multipart_begin {
+    print "HTTP/1.0 200 OK\n";
+    $bound = "ThisRandomString12345";
+    print "Content-type: multipart/x-mixed-replace;boundary=$bound\n";
+    &print_http_headers_multipart_next;
+}
+
+sub print_http_headers_multipart_next {
+    print "\n--$bound\n";
+}
+
+sub print_http_headers_multipart_end {
+    print "\n--$bound--\n";
+}
+
+sub displayhtml {
+    local($buffer) = @_;
+    $len = length($buffer);
+    print "Content-type: text/html\n";
+    print "Content-length: $len\n\n";
+    print $buffer;
+}
+
+sub readfile {
+    local($file) = @_;
+    local(*FP, $size, $buffer, $bytes);
+    ($x, $x, $x, $x, $x, $x, $x, $size) = stat($file);
+    $size = sprintf("%d", $size);
+    open(FP, "&lt;$file");
+    $bytes = sysread(FP, $buffer, $size);
+    close(FP);
+    return $buffer;
+}
+
+$buffer = &readfile($QS_f);
+&print_http_headers_multipart_begin;
+&displayhtml($buffer);
+
+sub mystat {
+    local($file) = $_[0];
+    local($time);
+
+    ($x, $x, $x, $x, $x, $x, $x, $x, $x, $mtime) = stat($file);
+    return $mtime;
+}
+
+$mtimeL = &mystat($QS_f);
+$mtime = $mtime;
+for ($n = 0; $n &lt; $QS_n; $n++) {
+    while (1) {
+        $mtime = &mystat($QS_f);
+        if ($mtime ne $mtimeL) {
+            $mtimeL = $mtime;
+            sleep(2);
+            $buffer = &readfile($QS_f);
+            &print_http_headers_multipart_next;
+            &displayhtml($buffer);
+            sleep(5);
+            $mtimeL = &mystat($QS_f);
+            last;
+        }
+        sleep($QS_s);
+    }
+}
+
+&print_http_headers_multipart_end;
+
+exit(0);
+
+##EOF##
+
+
+
+ + + +

Mass Virtual Hosting

+ + + +
+
Description:
+ +
+

The <VirtualHost> feature of Apache is nice + and works great when you just have a few dozens + virtual hosts. But when you are an ISP and have hundreds of + virtual hosts to provide this feature is not the best + choice.

+
+ +
Solution:
+ +
+

To provide this feature we map the remote webpage or even + the complete remote webarea to our namespace by the use + of the Proxy Throughput feature (flag [P]):

+ +
+##
+##  vhost.map
+##
+www.vhost1.dom:80  /path/to/docroot/vhost1
+www.vhost2.dom:80  /path/to/docroot/vhost2
+     :
+www.vhostN.dom:80  /path/to/docroot/vhostN
+
+ +
+##
+##  httpd.conf
+##
+    :
+#   use the canonical hostname on redirects, etc.
+UseCanonicalName on
+
+    :
+#   add the virtual host in front of the CLF-format
+CustomLog  /path/to/access_log  "%{VHOST}e %h %l %u %t \"%r\" %>s %b"
+    :
+
+#   enable the rewriting engine in the main server
+RewriteEngine on
+
+#   define two maps: one for fixing the URL and one which defines
+#   the available virtual hosts with their corresponding
+#   DocumentRoot.
+RewriteMap    lowercase    int:tolower
+RewriteMap    vhost        txt:/path/to/vhost.map
+
+#   Now do the actual virtual host mapping
+#   via a huge and complicated single rule:
+#
+#   1. make sure we don't map for common locations
+RewriteCond   %{REQUEST_URL}  !^/commonurl1/.*
+RewriteCond   %{REQUEST_URL}  !^/commonurl2/.*
+    :
+RewriteCond   %{REQUEST_URL}  !^/commonurlN/.*
+#
+#   2. make sure we have a Host header, because
+#      currently our approach only supports
+#      virtual hosting through this header
+RewriteCond   %{HTTP_HOST}  !^$
+#
+#   3. lowercase the hostname
+RewriteCond   ${lowercase:%{HTTP_HOST}|NONE}  ^(.+)$
+#
+#   4. lookup this hostname in vhost.map and
+#      remember it only when it is a path
+#      (and not "NONE" from above)
+RewriteCond   ${vhost:%1}  ^(/.*)$
+#
+#   5. finally we can map the URL to its docroot location
+#      and remember the virtual host for logging puposes
+RewriteRule   ^/(.*)$   %1/$1  [E=VHOST:${lowercase:%{HTTP_HOST}}]
+    :
+
+
+
+ + + +
top

Access Restriction

+ + + +

Blocking of Robots

+ + + +
+
Description:
+ +
+

How can we block a really annoying robot from + retrieving pages of a specific webarea? A + /robots.txt file containing entries of the + "Robot Exclusion Protocol" is typically not enough to get + rid of such a robot.

+
+ +
Solution:
+ +
+

We use a ruleset which forbids the URLs of the webarea + /~quux/foo/arc/ (perhaps a very deep + directory indexed area where the robot traversal would + create big server load). We have to make sure that we + forbid access only to the particular robot, i.e. just + forbidding the host where the robot runs is not enough. + This would block users from this host, too. We accomplish + this by also matching the User-Agent HTTP header + information.

+ +
+RewriteCond %{HTTP_USER_AGENT}   ^NameOfBadRobot.*
+RewriteCond %{REMOTE_ADDR}       ^123\.45\.67\.[8-9]$
+RewriteRule ^/~quux/foo/arc/.+   -   [F]
+
+
+
+ + + +

Blocked Inline-Images

+ + + +
+
Description:
+ +
+

Assume we have under http://www.quux-corp.de/~quux/ + some pages with inlined GIF graphics. These graphics are + nice, so others directly incorporate them via hyperlinks to + their pages. We don't like this practice because it adds + useless traffic to our server.

+
+ +
Solution:
+ +
+

While we cannot 100% protect the images from inclusion, + we can at least restrict the cases where the browser + sends a HTTP Referer header.

+ +
+RewriteCond %{HTTP_REFERER} !^$
+RewriteCond %{HTTP_REFERER} !^http://www.quux-corp.de/~quux/.*$ [NC]
+RewriteRule .*\.gif$        -                                    [F]
+
+ +
+RewriteCond %{HTTP_REFERER}         !^$
+RewriteCond %{HTTP_REFERER}         !.*/foo-with-gif\.html$
+RewriteRule ^inlined-in-foo\.gif$   -                        [F]
+
+
+
+ + + +

Host Deny

+ + + +
+
Description:
+ +
+

How can we forbid a list of externally configured hosts + from using our server?

+
+ +
Solution:
+ +
+

For Apache >= 1.3b6:

+ +
+RewriteEngine on
+RewriteMap    hosts-deny  txt:/path/to/hosts.deny
+RewriteCond   ${hosts-deny:%{REMOTE_HOST}|NOT-FOUND} !=NOT-FOUND [OR]
+RewriteCond   ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND} !=NOT-FOUND
+RewriteRule   ^/.*  -  [F]
+
+ +

For Apache <= 1.3b6:

+ +
+RewriteEngine on
+RewriteMap    hosts-deny  txt:/path/to/hosts.deny
+RewriteRule   ^/(.*)$ ${hosts-deny:%{REMOTE_HOST}|NOT-FOUND}/$1
+RewriteRule   !^NOT-FOUND/.* - [F]
+RewriteRule   ^NOT-FOUND/(.*)$ ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND}/$1
+RewriteRule   !^NOT-FOUND/.* - [F]
+RewriteRule   ^NOT-FOUND/(.*)$ /$1
+
+ +
+##
+##  hosts.deny
+##
+##  ATTENTION! This is a map, not a list, even when we treat it as such.
+##             mod_rewrite parses it for key/value pairs, so at least a
+##             dummy value "-" must be present for each entry.
+##
+
+193.102.180.41 -
+bsdti1.sdm.de  -
+192.76.162.40  -
+
+
+
+ + + +

Proxy Deny

+ + + +
+
Description:
+ +
+

How can we forbid a certain host or even a user of a + special host from using the Apache proxy?

+
+ +
Solution:
+ +
+

We first have to make sure mod_rewrite + is below(!) mod_proxy in the Configuration + file when compiling the Apache webserver. This way it gets + called before mod_proxy. Then we + configure the following for a host-dependent deny...

+ +
+RewriteCond %{REMOTE_HOST} ^badhost\.mydomain\.com$
+RewriteRule !^http://[^/.]\.mydomain.com.*  - [F]
+
+ +

...and this one for a user@host-dependent deny:

+ +
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST}  ^badguy@badhost\.mydomain\.com$
+RewriteRule !^http://[^/.]\.mydomain.com.*  - [F]
+
+
+
+ + + +

Special Authentication Variant

+ + + +
+
Description:
+ +
+

Sometimes a very special authentication is needed, for + instance a authentication which checks for a set of + explicitly configured users. Only these should receive + access and without explicit prompting (which would occur + when using the Basic Auth via mod_access).

+
+ +
Solution:
+ +
+

We use a list of rewrite conditions to exclude all except + our friends:

+ +
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend1@client1.quux-corp\.com$
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend2@client2.quux-corp\.com$
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend3@client3.quux-corp\.com$
+RewriteRule ^/~quux/only-for-friends/      -                                 [F]
+
+
+
+ + + +

Referer-based Deflector

+ + + +
+
Description:
+ +
+

How can we program a flexible URL Deflector which acts + on the "Referer" HTTP header and can be configured with as + many referring pages as we like?

+
+ +
Solution:
+ +
+

Use the following really tricky ruleset...

+ +
+RewriteMap  deflector txt:/path/to/deflector.map
+
+RewriteCond %{HTTP_REFERER} !=""
+RewriteCond ${deflector:%{HTTP_REFERER}} ^-$
+RewriteRule ^.* %{HTTP_REFERER} [R,L]
+
+RewriteCond %{HTTP_REFERER} !=""
+RewriteCond ${deflector:%{HTTP_REFERER}|NOT-FOUND} !=NOT-FOUND
+RewriteRule ^.* ${deflector:%{HTTP_REFERER}} [R,L]
+
+ +

... in conjunction with a corresponding rewrite + map:

+ +
+##
+##  deflector.map
+##
+
+http://www.badguys.com/bad/index.html    -
+http://www.badguys.com/bad/index2.html   -
+http://www.badguys.com/bad/index3.html   http://somewhere.com/
+
+ +

This automatically redirects the request back to the + referring page (when "-" is used as the value + in the map) or to a specific URL (when an URL is specified + in the map as the second argument).

+
+
+ + + +
top

Other

+ + + +

External Rewriting Engine

+ + + +
+
Description:
+ +
+

A FAQ: How can we solve the FOO/BAR/QUUX/etc. + problem? There seems no solution by the use of + mod_rewrite...

+
+ +
Solution:
+ +
+

Use an external RewriteMap, i.e. a program which acts + like a RewriteMap. It is run once on startup of Apache + receives the requested URLs on STDIN and has + to put the resulting (usually rewritten) URL on + STDOUT (same order!).

+ +
+RewriteEngine on
+RewriteMap    quux-map       prg:/path/to/map.quux.pl
+RewriteRule   ^/~quux/(.*)$  /~quux/${quux-map:$1}
+
+ +
+#!/path/to/perl
+
+#   disable buffered I/O which would lead
+#   to deadloops for the Apache server
+$| = 1;
+
+#   read URLs one per line from stdin and
+#   generate substitution URL on stdout
+while (<>) {
+    s|^foo/|bar/|;
+    print $_;
+}
+
+ +

This is a demonstration-only example and just rewrites + all URLs /~quux/foo/... to + /~quux/bar/.... Actually you can program + whatever you like. But notice that while such maps can be + used also by an average user, only the + system administrator can define it.

+
+
+ + + +
\ No newline at end of file diff --git a/docs/manual/misc/rewriteguide.html b/docs/manual/misc/rewriteguide.xml similarity index 53% rename from docs/manual/misc/rewriteguide.html rename to docs/manual/misc/rewriteguide.xml index 8079c2b88e8..4e320c44d58 100644 --- a/docs/manual/misc/rewriteguide.html +++ b/docs/manual/misc/rewriteguide.xml @@ -1,115 +1,114 @@ - - - - - - - Apache 1.3 URL Rewriting Guide - - - - -
- - -
-

Apache 1.3
- URL Rewriting Guide
-

- -
- Originally written by
- Ralf S. Engelschall <rse@apache.org>
- December 1997 -
-
- -

This document supplements the mod_rewrite reference documentation. - It describes how one can use Apache's mod_rewrite to solve - typical URL-based problems webmasters are usually confronted - with in practice. I give detailed descriptions on how to - solve each problem by configuring URL rewriting rulesets.

- -

Introduction to - mod_rewrite

- The Apache module mod_rewrite is a killer one, i.e. it is a - really sophisticated module which provides a powerful way to - do URL manipulations. With it you can nearly do all types of - URL manipulations you ever dreamed about. The price you have - to pay is to accept complexity, because mod_rewrite's major - drawback is that it is not easy to understand and use for the - beginner. And even Apache experts sometimes discover new - aspects where mod_rewrite can help. - -

In other words: With mod_rewrite you either shoot yourself - in the foot the first time and never use it again or love it - for the rest of your life because of its power. This paper - tries to give you a few initial success events to avoid the - first case by presenting already invented solutions to - you.

- -

Practical Solutions

- Here come a lot of practical solutions I've either invented - myself or collected from other peoples solutions in the past. - Feel free to learn the black magic of URL rewriting from - these examples. - - - - - -
ATTENTION: Depending on your server-configuration it - can be necessary to slightly change the examples for your - situation, e.g. adding the [PT] flag when additionally - using mod_alias and mod_userdir, etc. Or rewriting a - ruleset to fit in .htaccess context instead - of per-server context. Always try to understand what a - particular ruleset really does before you use it. It - avoid problems.
- -

URL Layout

- -

Canonical URLs

+ + + + + + + + URL Rewriting Guide + + + +
Originally written by
+ Ralf S. Engelschall <rse@apache.org>
+ December 1997
+
+ +

This document supplements the mod_rewrite + reference documentation. + It describes how one can use Apache's mod_rewrite + to solve typical URL-based problems webmasters are usually confronted + with in practice. I give detailed descriptions on how to + solve each problem by configuring URL rewriting rulesets.

+ +
+ +
+ + Introduction to <code>mod_rewrite</code> + +

The Apache module mod_rewrite is a killer + one, i.e. it is a really sophisticated module which provides + a powerful way to do URL manipulations. With it you can nearly + do all types of URL manipulations you ever dreamed about. + The price you have to pay is to accept complexity, because + mod_rewrite's major drawback is that it is + not easy to understand and use for the beginner. And even + Apache experts sometimes discover new aspects where + mod_rewrite can help.

+ +

In other words: With mod_rewrite you either + shoot yourself in the foot the first time and never use it again + or love it for the rest of your life because of its power. + This paper tries to give you a few initial success events to + avoid the first case by presenting already invented solutions + to you.

+ +
+ +
+ + Practical Solutions + +

Here come a lot of practical solutions I've either invented + myself or collected from other peoples solutions in the past. + Feel free to learn the black magic of URL rewriting from + these examples.

+ + ATTENTION: Depending on your server-configuration + it can be necessary to slightly change the examples for your + situation, e.g. adding the [PT] flag when + additionally using mod_alias and + mod_userdir, etc. Or rewriting a ruleset + to fit in .htaccess context instead + of per-server context. Always try to understand what a + particular ruleset really does before you use it. It + avoid problems. + +
+ +
+ + URL Layout + +
+ + Canonical URLs
Description:
-
On some webservers there are more than one URL for a - resource. Usually there are canonical URLs (which should be - actually used and distributed) and those which are just - shortcuts, internal ones, etc. Independent of which URL the - user supplied with the request he should finally see the - canonical one only.
+
+

On some webservers there are more than one URL for a + resource. Usually there are canonical URLs (which should be + actually used and distributed) and those which are just + shortcuts, internal ones, etc. Independent of which URL the + user supplied with the request he should finally see the + canonical one only.

+
Solution:
- We do an external HTTP redirect for all non-canonical +

We do an external HTTP redirect for all non-canonical URLs to fix them in the location view of the Browser and for all subsequent requests. In the example ruleset below we replace /~user by the canonical /u/user and fix a missing trailing slash for - /u/user. + /u/user.

- - - - -
-
+
 RewriteRule   ^/~([^/]+)/?(.*)    /u/$1/$2  [R]
 RewriteRule   ^/([uge])/([^/]+)$  /$1/$2/   [R]
-
-
+
-

Canonical Hostnames

+
+ +
+ + Canonical Hostnames
Description:
@@ -119,11 +118,7 @@ RewriteRule ^/([uge])/([^/]+)$ /$1/$2/ [<
Solution:
- - - - -
-
+
 RewriteCond %{HTTP_HOST}   !^fully\.qualified\.domain\.name [NC]
 RewriteCond %{HTTP_HOST}   !^$
 RewriteCond %{SERVER_PORT} !^80$
@@ -131,75 +126,78 @@ RewriteRule ^/(.*)         http://fully.qualified.domain.name:%{SERVER_PORT}/$1
 RewriteCond %{HTTP_HOST}   !^fully\.qualified\.domain\.name [NC]
 RewriteCond %{HTTP_HOST}   !^$
 RewriteRule ^/(.*)         http://fully.qualified.domain.name/$1 [L,R]
-
-
+
-

Moved DocumentRoot

+
+ +
+ + Moved <code>DocumentRoot</code>
Description:
-
Usually the DocumentRoot of the webserver directly - relates to the URL ``/''. But often this data - is not really of top-level priority, it is perhaps just one - entity of a lot of data pools. For instance at our Intranet - sites there are /e/www/ (the homepage for - WWW), /e/sww/ (the homepage for the Intranet) - etc. Now because the data of the DocumentRoot stays at - /e/www/ we had to make sure that all inlined - images and other stuff inside this data pool work for - subsequent requests.
+
+

Usually the DocumentRoot + of the webserver directly relates to the URL "/". + But often this data is not really of top-level priority, it is + perhaps just one entity of a lot of data pools. For instance at + our Intranet sites there are /e/www/ + (the homepage for WWW), /e/sww/ (the homepage for + the Intranet) etc. Now because the data of the DocumentRoot stays at /e/www/ we had + to make sure that all inlined images and other stuff inside this + data pool work for subsequent requests.

+
Solution:
- We just redirect the URL / to +

We just redirect the URL / to /e/www/. While is seems trivial it is - actually trivial with mod_rewrite, only. Because the - typical old mechanisms of URL Aliases (as - provides by mod_alias and friends) only used - prefix matching. With this you cannot do such a - redirection because the DocumentRoot is a prefix of all - URLs. With mod_rewrite it is really trivial: - - - - - -
-
+          actually trivial with mod_rewrite, only.
+          Because the typical old mechanisms of URL Aliases
+          (as provides by mod_alias and friends)
+          only used prefix matching. With this you cannot
+          do such a redirection because the DocumentRoot is a prefix of all URLs. With
+          mod_rewrite it is really trivial:

+ +
 RewriteEngine on
 RewriteRule   ^/$  /e/www/  [R]
-
-
+

-

Trailing Slash Problem

+
+ +
+ + Trailing Slash Problem
Description:
-
Every webmaster can sing a song about the problem of - the trailing slash on URLs referencing directories. If they - are missing, the server dumps an error, because if you say - /~quux/foo instead of /~quux/foo/ - then the server searches for a file named - foo. And because this file is a directory it - complains. Actually it tries to fix it itself in most of - the cases, but sometimes this mechanism need to be emulated - by you. For instance after you have done a lot of - complicated URL rewritings to CGI scripts etc.
+
+

Every webmaster can sing a song about the problem of + the trailing slash on URLs referencing directories. If they + are missing, the server dumps an error, because if you say + /~quux/foo instead of /~quux/foo/ + then the server searches for a file named + foo. And because this file is a directory it + complains. Actually it tries to fix it itself in most of + the cases, but sometimes this mechanism need to be emulated + by you. For instance after you have done a lot of + complicated URL rewritings to CGI scripts etc.

+
Solution:
- The solution to this subtle problem is to let the server +

The solution to this subtle problem is to let the server add the trailing slash automatically. To do this correctly we have to use an external redirect, so the browser correctly requests subsequent images etc. If we @@ -210,98 +208,89 @@ RewriteRule ^/$ /e/www/ [R] request for image.gif in /~quux/foo/index.html would become /~quux/image.gif without the external - redirect! + redirect!

So, to do this trick we write:

- - - - -
-
+
 RewriteEngine  on
 RewriteBase    /~quux/
 RewriteRule    ^foo$  foo/  [R]
-
-
+

The crazy and lazy can even do the following in the top-level .htaccess file of their homedir. But notice that this creates some processing overhead.

- - - - -
-
+
 RewriteEngine  on
 RewriteBase    /~quux/
 RewriteCond    %{REQUEST_FILENAME}  -d
 RewriteRule    ^(.+[^/])$           $1/  [R]
-
-
+
-

Webcluster through Homogeneous URL Layout

+
+ +
+ + Webcluster through Homogeneous URL Layout
Description:
-
We want to create a homogeneous and consistent URL - layout over all WWW servers on a Intranet webcluster, i.e. - all URLs (per definition server local and thus server - dependent!) become actually server independent! - What we want is to give the WWW namespace a consistent - server-independent layout: no URL should have to include - any physically correct target server. The cluster itself - should drive us automatically to the physical target - host.
+
+

We want to create a homogeneous and consistent URL + layout over all WWW servers on a Intranet webcluster, i.e. + all URLs (per definition server local and thus server + dependent!) become actually server independent! + What we want is to give the WWW namespace a consistent + server-independent layout: no URL should have to include + any physically correct target server. The cluster itself + should drive us automatically to the physical target + host.

+
Solution:
- First, the knowledge of the target servers come from +

First, the knowledge of the target servers come from (distributed) external maps which contain information where our users, groups and entities stay. The have the - form -

+          form

+ +
 user1  server_of_user1
 user2  server_of_user2
 :      :
-
+

We put them into files map.xxx-to-host. Second we need to instruct all servers to redirect URLs of the forms

-
+
+
 /u/user/anypath
 /g/group/anypath
 /e/entity/anypath
-
+

to

-
+
+
 http://physical-host/u/user/anypath
 http://physical-host/g/group/anypath
 http://physical-host/e/entity/anypath
-
+

when the URL is not locally valid to a server. The following ruleset does this for us by the help of the map files (assuming that server0 is a default server which will be used if a user has no entry in the map):

- - - - -
-
+
 RewriteEngine on
 
 RewriteMap      user-to-host   txt:/path/to/map.user-to-host
@@ -314,86 +303,85 @@ RewriteRule   ^/e/([^/]+)/?(.*) http://${entity-to-host
 
 RewriteRule   ^/([uge])/([^/]+)/?$          /$1/$2/.www/
 RewriteRule   ^/([uge])/([^/]+)/([^.]+.+)   /$1/$2/.www/$3\
-
-
+
-

Move Homedirs to Different Webserver

+
+ +
+ + Move Homedirs to Different Webserver
Description:
-
Many webmasters have asked for a solution to the - following situation: They wanted to redirect just all - homedirs on a webserver to another webserver. They usually - need such things when establishing a newer webserver which - will replace the old one over time.
+
+

Many webmasters have asked for a solution to the + following situation: They wanted to redirect just all + homedirs on a webserver to another webserver. They usually + need such things when establishing a newer webserver which + will replace the old one over time.

+
Solution:
- The solution is trivial with mod_rewrite. On the old - webserver we just redirect all +

The solution is trivial with mod_rewrite. + On the old webserver we just redirect all /~user/anypath URLs to - http://newserver/~user/anypath. + http://newserver/~user/anypath.

- - - - -
-
+
 RewriteEngine on
 RewriteRule   ^/~(.+)  http://newserver/~$1  [R,L]
-
-
+
-

Structured Homedirs

+
+ +
+ + Structured Homedirs
Description:
-
Some sites with thousands of users usually use a - structured homedir layout, i.e. each homedir is in a - subdirectory which begins for instance with the first - character of the username. So, /~foo/anypath - is /home/f/foo/.www/anypath - while /~bar/anypath is - /home/b/bar/.www/anypath.
+
+

Some sites with thousands of users usually use a + structured homedir layout, i.e. each homedir is in a + subdirectory which begins for instance with the first + character of the username. So, /~foo/anypath + is /home/f/foo/.www/anypath + while /~bar/anypath is + /home/b/bar/.www/anypath.

+
Solution:
- We use the following ruleset to expand the tilde URLs - into exactly the above layout. +

We use the following ruleset to expand the tilde URLs + into exactly the above layout.

- - - - -
-
+
 RewriteEngine on
 RewriteRule   ^/~(([a-z])[a-z0-9]+)(.*)  /home/$2/$1/.www$3
-
-
+
-

Filesystem Reorganization

+
+ +
+ + Filesystem Reorganization
Description:
- This really is a hardcore example: a killer application +

This really is a hardcore example: a killer application which heavily uses per-directory RewriteRules to get a smooth look and feel on the Web while its data structure is never touched or @@ -404,8 +392,9 @@ RewriteRule ^/~(([a-z])[a-z0-9]+)(.*) /home/$2 + directories where I stored the packages:

+ +
 drwxrwxr-x   2 netsw  users    512 Aug  3 18:39 Audio/
 drwxrwxr-x   2 netsw  users    512 Jul  9 14:37 Benchmark/
 drwxrwxr-x  12 netsw  users    512 Jul  9 00:34 Crypto/
@@ -422,7 +411,7 @@ drwxrwxr-x   7 netsw  users    512 Jul  9 09:24 SoftEng/
 drwxrwxr-x   7 netsw  users    512 Jul  9 12:17 System/
 drwxrwxr-x  12 netsw  users    512 Aug  3 20:15 Typesetting/
 drwxrwxr-x  10 netsw  users    512 Jul  9 14:08 X11/
-
+

In July 1996 I decided to make this archive public to the world via a nice Web interface. "Nice" means that I @@ -438,11 +427,12 @@ drwxrwxr-x 10 netsw users 512 Jul 9 14:08 X11/

Solution:
- The solution has two parts: The first is a set of CGI +

The solution has two parts: The first is a set of CGI scripts which create all the pages at all directory levels on-the-fly. I put them under - /e/netsw/.www/ as follows: -

+          /e/netsw/.www/ as follows:

+ +
 -rw-r--r--   1 netsw  users    1318 Aug  1 18:10 .wwwacl
 drwxr-xr-x  18 netsw  users     512 Aug  5 15:51 DATA/
 -rw-rw-rw-   1 netsw  users  372982 Aug  5 16:35 LOGFILE
@@ -456,7 +446,7 @@ drwxr-xr-x   2 netsw  users     512 Jul  8 23:47 netsw-img/
 -rwxr-xr-x   1 netsw  users    1589 Aug  3 18:43 netsw-search.cgi
 -rwxr-xr-x   1 netsw  users    1885 Aug  1 17:41 netsw-tree.cgi
 -rw-r--r--   1 netsw  users     234 Jul 30 16:35 netsw-unlimit.lst
-
+

The DATA/ subdirectory holds the above directory structure, i.e. the real @@ -468,21 +458,15 @@ drwxr-xr-x 2 netsw users 512 Jul 8 23:47 netsw-img/ from the user while running the appropriate CGI scripts for the various URLs. Here is the solution: first I put the following into the per-directory configuration file - in the Document Root of the server to rewrite the - announced URL /net.sw/ to the internal path + in the DocumentRoot + of the server to rewrite the announced URL + /net.sw/ to the internal path /e/netsw:

- - - - -
-
+
 RewriteRule  ^net.sw$       net.sw/        [R]
 RewriteRule  ^net.sw/(.*)$  e/netsw/$1
-
-
+

The first rule is for requests which miss the trailing slash! The second rule does the real thing. And then @@ -490,19 +474,15 @@ RewriteRule ^net.sw/(.*)$ e/netsw/$1 per-directory config file /e/netsw/.www/.wwwacl:

- - - - -
-
-Options       ExecCGI FollowSymLinks Includes MultiViews 
+
+Options       ExecCGI FollowSymLinks Includes MultiViews
 
 RewriteEngine on
 
 #  we are reached via /net.sw/ prefix
 RewriteBase   /net.sw/
 
-#  first we rewrite the root dir to 
+#  first we rewrite the root dir to
 #  the handling cgi script
 RewriteRule   ^$                       netsw-home.cgi     [L]
 RewriteRule   ^index\.html$            netsw-home.cgi     [L]
@@ -523,81 +503,80 @@ RewriteRule   ^netsw-img/.*$           -                  [L]
 #  by another cgi script
 RewriteRule   !^netsw-lsdir\.cgi.*     -                  [C]
 RewriteRule   (.*)                     netsw-lsdir.cgi/$1
-
-
+

Some hints for interpretation:

    -
  1. Notice the L (last) flag and no substitution field - ('-') in the forth part
  2. +
  3. Notice the L (last) flag and no + substitution field ('-') in the forth part
  4. -
  5. Notice the ! (not) character and the C (chain) flag - at the first rule in the last part
  6. +
  7. Notice the ! (not) character and + the C (chain) flag at the first rule + in the last part
  8. Notice the catch-all pattern in the last rule
-

NCSA imagemap to Apache mod_imap

+
+ +
+ + NCSA imagemap to Apache <code>mod_imap</code>
Description:
-
When switching from the NCSA webserver to the more - modern Apache webserver a lot of people want a smooth - transition. So they want pages which use their old NCSA - imagemap program to work under Apache with the - modern mod_imap. The problem is that there are - a lot of hyperlinks around which reference the - imagemap program via - /cgi-bin/imagemap/path/to/page.map. Under - Apache this has to read just - /path/to/page.map.
+
+

When switching from the NCSA webserver to the more + modern Apache webserver a lot of people want a smooth + transition. So they want pages which use their old NCSA + imagemap program to work under Apache with the + modern mod_imap. The problem is that there + are a lot of hyperlinks around which reference the + imagemap program via + /cgi-bin/imagemap/path/to/page.map. Under + Apache this has to read just + /path/to/page.map.

+
Solution:
- We use a global rule to remove the prefix on-the-fly for - all requests: +

We use a global rule to remove the prefix on-the-fly for + all requests:

- - - - -
-
+
 RewriteEngine  on
 RewriteRule    ^/cgi-bin/imagemap(.*)  $1  [PT]
-
-
+
-

Search pages in more than one directory

+
+ +
+ + Search pages in more than one directory
Description:
-
Sometimes it is necessary to let the webserver search - for pages in more than one directory. Here MultiViews or - other techniques cannot help.
+
+

Sometimes it is necessary to let the webserver search + for pages in more than one directory. Here MultiViews or + other techniques cannot help.

+
Solution:
- We program a explicit ruleset which searches for the - files in the directories. +

We program a explicit ruleset which searches for the + files in the directories.

- - - - -
-
+
 RewriteEngine on
 
 #   first try to find it in custom/...
@@ -613,223 +592,208 @@ RewriteRule  ^(.+)  /your/docroot/dir2/$1  [L]
 #   else go on for other Alias or ScriptAlias directives,
 #   etc.
 RewriteRule   ^(.+)  -  [PT]
-
-
+
-

Set Environment Variables According To URL Parts

+
+ +
+ + Set Environment Variables According To URL Parts
Description:
-
Perhaps you want to keep status information between - requests and use the URL to encode it. But you don't want - to use a CGI wrapper for all pages just to strip out this - information.
+
+

Perhaps you want to keep status information between + requests and use the URL to encode it. But you don't want + to use a CGI wrapper for all pages just to strip out this + information.

+
Solution:
- We use a rewrite rule to strip out the status information +

We use a rewrite rule to strip out the status information and remember it via an environment variable which can be later dereferenced from within XSSI or CGI. This way a URL /foo/S=java/bar/ gets translated to /foo/bar/ and the environment variable named - STATUS is set to the value "java". + STATUS is set to the value "java".

- - - - -
-
+
 RewriteEngine on
 RewriteRule   ^(.*)/S=([^/]+)/(.*)    $1/$3 [E=STATUS:$2]
-
-
+
-

Virtual User Hosts

+
+ +
+ + Virtual User Hosts
Description:
-
Assume that you want to provide - www.username.host.domain.com - for the homepage of username via just DNS A records to the - same machine and without any virtualhosts on this - machine.
+
+

Assume that you want to provide + www.username.host.domain.com + for the homepage of username via just DNS A records to the + same machine and without any virtualhosts on this + machine.

+
Solution:
- For HTTP/1.0 requests there is no solution, but for +

For HTTP/1.0 requests there is no solution, but for HTTP/1.1 requests which contain a Host: HTTP header we can use the following ruleset to rewrite http://www.username.host.com/anypath - internally to /home/username/anypath: + internally to /home/username/anypath:

- - - - -
-
+
 RewriteEngine on
 RewriteCond   %{HTTP_HOST}                 ^www\.[^.]+\.host\.com$
 RewriteRule   ^(.+)                        %{HTTP_HOST}$1          [C]
 RewriteRule   ^www\.([^.]+)\.host\.com(.*) /home/$1$2
-
-
+
-

Redirect Homedirs For Foreigners

+
+ +
+ + Redirect Homedirs For Foreigners
Description:
-
We want to redirect homedir URLs to another webserver - www.somewhere.com when the requesting user - does not stay in the local domain - ourdomain.com. This is sometimes used in - virtual host contexts.
+
+

We want to redirect homedir URLs to another webserver + www.somewhere.com when the requesting user + does not stay in the local domain + ourdomain.com. This is sometimes used in + virtual host contexts.

+
Solution:
- Just a rewrite condition: +

Just a rewrite condition:

- - - - -
-
+
 RewriteEngine on
 RewriteCond   %{REMOTE_HOST}  !^.+\.ourdomain\.com$
 RewriteRule   ^(/~.+)         http://www.somewhere.com/$1 [R,L]
-
-
+
-

Redirect Failing URLs To Other Webserver

+
+ +
+ + Redirect Failing URLs To Other Webserver
Description:
-
A typical FAQ about URL rewriting is how to redirect - failing requests on webserver A to webserver B. Usually - this is done via ErrorDocument CGI-scripts in Perl, but - there is also a mod_rewrite solution. But notice that this - performs more poorly than using an ErrorDocument - CGI-script!
+
+

A typical FAQ about URL rewriting is how to redirect + failing requests on webserver A to webserver B. Usually + this is done via ErrorDocument CGI-scripts in Perl, but + there is also a mod_rewrite solution. + But notice that this performs more poorly than using an + ErrorDocument + CGI-script!

+
Solution:
- The first solution has the best performance but less - flexibility, and is less error safe: +

The first solution has the best performance but less + flexibility, and is less error safe:

- - - - -
-
+
 RewriteEngine on
 RewriteCond   /your/docroot/%{REQUEST_FILENAME} !-f
 RewriteRule   ^(.+)                             http://webserverB.dom/$1
-
-
+

The problem here is that this will only work for pages - inside the DocumentRoot. While you can add more + inside the DocumentRoot. While you can add more Conditions (for instance to also handle homedirs, etc.) there is better variant:

- - - - -
-
+
 RewriteEngine on
 RewriteCond   %{REQUEST_URI} !-U
 RewriteRule   ^(.+)          http://webserverB.dom/$1
-
-
+ -

This uses the URL look-ahead feature of mod_rewrite. +

This uses the URL look-ahead feature of mod_rewrite. The result is that this will work for all types of URLs and is a safe way. But it does a performance impact on the webserver, because for every request there is one more internal subrequest. So, if your webserver runs on a powerful CPU, use this one. If it is a slow machine, use - the first approach or better a ErrorDocument - CGI-script.

+ the first approach or better a ErrorDocument CGI-script.

-

Extended Redirection

+
+ +
+ + Extended Redirection
Description:
-
Sometimes we need more control (concerning the - character escaping mechanism) of URLs on redirects. Usually - the Apache kernels URL escape function also escapes - anchors, i.e. URLs like "url#anchor". You cannot use this - directly on redirects with mod_rewrite because the - uri_escape() function of Apache would also escape the hash - character. How can we redirect to such a URL?
+
+

Sometimes we need more control (concerning the + character escaping mechanism) of URLs on redirects. + Usually the Apache kernels URL escape function also + escapes anchors, i.e. URLs like "url#anchor". + You cannot use this directly on redirects with + mod_rewrite because the + uri_escape() function of Apache + would also escape the hash character. + How can we redirect to such a URL?

+
Solution:
- We have to use a kludge by the use of a NPH-CGI script +

We have to use a kludge by the use of a NPH-CGI script which does the redirect itself. Because here no escaping is done (NPH=non-parseable headers). First we introduce a new URL scheme xredirect: by the following per-server config-line (should be one of the last rewrite - rules): + rules):

- - - - -
-
+
 RewriteRule ^xredirect:(.+) /path/to/nph-xredirect.cgi/$1 \
             [T=application/x-httpd-cgi,L]
-
-
+

This forces all URLs prefixed with xredirect: to be piped through the nph-xredirect.cgi program. And this program just looks like:

- - - - -
-
+
 #!/path/to/perl
 ##
 ##  nph-xredirect.cgi -- NPH/CGI script for extended redirects
-##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved. 
+##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
 ##
 
 $| = 1;
@@ -851,79 +815,66 @@ print "</body>\n";
 print "</html>\n";
 
 ##EOF##
-
-
+

This provides you with the functionality to do redirects to all URL schemes, i.e. including the one - which are not directly accepted by mod_rewrite. For - instance you can now also redirect to + which are not directly accepted by mod_rewrite. + For instance you can now also redirect to news:newsgroup via

- - - - -
-
+
 RewriteRule ^anyurl  xredirect:news:newsgroup
-
-
+ -

Notice: You have not to put [R] or [R,L] to the above - rule because the xredirect: need to be - expanded later by our special "pipe through" rule - above.

+ Notice: You have not to put [R] or + [R,L] to the above rule because the + xredirect: need to be expanded later + by our special "pipe through" rule above.
-

Archive Access Multiplexer

+
+ +
+ + Archive Access Multiplexer
Description:
-
Do you know the great CPAN (Comprehensive Perl Archive - Network) under http://www.perl.com/CPAN? - This does a redirect to one of several FTP servers around - the world which carry a CPAN mirror and is approximately - near the location of the requesting client. Actually this - can be called an FTP access multiplexing service. While - CPAN runs via CGI scripts, how can a similar approach - implemented via mod_rewrite?
+
+

Do you know the great CPAN (Comprehensive Perl Archive + Network) under http://www.perl.com/CPAN? + This does a redirect to one of several FTP servers around + the world which carry a CPAN mirror and is approximately + near the location of the requesting client. Actually this + can be called an FTP access multiplexing service. While + CPAN runs via CGI scripts, how can a similar approach + implemented via mod_rewrite?

+
Solution:
- First we notice that from version 3.0.0 mod_rewrite can - also use the "ftp:" scheme on redirects. And second, the - location approximation can be done by a rewritemap over - the top-level domain of the client. With a tricky chained - ruleset we can use this top-level domain as a key to our - multiplexing map. - - - - - -
-
+          

First we notice that from version 3.0.0 + mod_rewrite can + also use the "ftp:" scheme on redirects. + And second, the location approximation can be done by a + RewriteMap + over the top-level domain of the client. + With a tricky chained ruleset we can use this top-level + domain as a key to our multiplexing map.

+ +
 RewriteEngine on
 RewriteMap    multiplex                txt:/path/to/map.cxan
 RewriteRule   ^/CxAN/(.*)              %{REMOTE_HOST}::$1                 [C]
 RewriteRule   ^.+\.([a-zA-Z]+)::(.*)$  ${multiplex:$1|ftp.default.dom}$2  [R,L]
-
-
- - - - - -
-
+
+ +
 ##
 ##  map.cxan -- Multiplexing Map for CxAN
 ##
@@ -933,78 +884,77 @@ uk        ftp://ftp.cxan.uk/CxAN/
 com       ftp://ftp.cxan.com/CxAN/
  :
 ##EOF##
-
-
+
-

Time-Dependent Rewriting

+
+ +
+ + Time-Dependent Rewriting
Description:
-
When tricks like time-dependent content should happen a - lot of webmasters still use CGI scripts which do for - instance redirects to specialized pages. How can it be done - via mod_rewrite?
+
+

When tricks like time-dependent content should happen a + lot of webmasters still use CGI scripts which do for + instance redirects to specialized pages. How can it be done + via mod_rewrite?

+
Solution:
- There are a lot of variables named TIME_xxx +

There are a lot of variables named TIME_xxx for rewrite conditions. In conjunction with the special - lexicographic comparison patterns <STRING, >STRING - and =STRING we can do time-dependent redirects: - - - - - -
-
+          lexicographic comparison patterns <STRING,
+          >STRING and =STRING we can
+          do time-dependent redirects:

+ +
 RewriteEngine on
 RewriteCond   %{TIME_HOUR}%{TIME_MIN} >0700
 RewriteCond   %{TIME_HOUR}%{TIME_MIN} <1900
 RewriteRule   ^foo\.html$             foo.day.html
 RewriteRule   ^foo\.html$             foo.night.html
-
-
+

This provides the content of foo.day.html - under the URL foo.html from 07:00-19:00 and - at the remaining time the contents of - foo.night.html. Just a nice feature for a - homepage...

+ under the URL foo.html from + 07:00-19:00 and at the remaining time the + contents of foo.night.html. Just a nice + feature for a homepage...

-

Backward Compatibility for YYYY to XXXX migration

+
+ +
+ + Backward Compatibility for YYYY to XXXX migration
Description:
-
How can we make URLs backward compatible (still - existing virtually) after migrating document.YYYY to - document.XXXX, e.g. after translating a bunch of .html - files to .phtml?
+
+

How can we make URLs backward compatible (still + existing virtually) after migrating document.YYYY + to document.XXXX, e.g. after translating a + bunch of .html files to .phtml?

+
Solution:
- We just rewrite the name to its basename and test for +

We just rewrite the name to its basename and test for existence of the new extension. If it exists, we take - that name, else we rewrite the URL to its original state. - - - - - - -
-
-#   backward compatibility ruleset for 
+          that name, else we rewrite the URL to its original state.

+ + +
+#   backward compatibility ruleset for
 #   rewriting document.html to document.phtml
 #   when and only when document.phtml exists
 #   but no longer document.html
@@ -1018,95 +968,100 @@ RewriteRule   ^(.*)$ $1.phtml                   [S=1]
 #   else reverse the previous basename cutout
 RewriteCond   %{ENV:WasHTML}            ^yes$
 RewriteRule   ^(.*)$ $1.html
-
-
+

-

Content Handling

+
+ +
+ +
-

From Old to New (intern)

+ Content Handling + +
+ + From Old to New (intern)
Description:
-
Assume we have recently renamed the page - bar.html to foo.html and now want - to provide the old URL for backward compatibility. Actually - we want that users of the old URL even not recognize that - the pages was renamed.
+
+

Assume we have recently renamed the page + bar.html to foo.html and now want + to provide the old URL for backward compatibility. Actually + we want that users of the old URL even not recognize that + the pages was renamed.

+
Solution:
- We rewrite the old URL to the new one internally via the - following rule: +

We rewrite the old URL to the new one internally via the + following rule:

- - - - -
-
+
 RewriteEngine  on
 RewriteBase    /~quux/
 RewriteRule    ^foo\.html$  bar.html
-
-
+
-

From Old to New (extern)

+
+ +
+ + From Old to New (extern)
Description:
-
Assume again that we have recently renamed the page - bar.html to foo.html and now want - to provide the old URL for backward compatibility. But this - time we want that the users of the old URL get hinted to - the new one, i.e. their browsers Location field should - change, too.
+
+

Assume again that we have recently renamed the page + bar.html to foo.html and now want + to provide the old URL for backward compatibility. But this + time we want that the users of the old URL get hinted to + the new one, i.e. their browsers Location field should + change, too.

+
Solution:
- We force a HTTP redirect to the new URL which leads to a - change of the browsers and thus the users view: +

We force a HTTP redirect to the new URL which leads to a + change of the browsers and thus the users view:

- - - - -
-
+
 RewriteEngine  on
 RewriteBase    /~quux/
 RewriteRule    ^foo\.html$  bar.html  [R]
-
-
+
-

Browser Dependent Content

+
+ +
+ + Browser Dependent Content
Description:
-
At least for important top-level pages it is sometimes - necessary to provide the optimum of browser dependent - content, i.e. one has to provide a maximum version for the - latest Netscape variants, a minimum version for the Lynx - browsers and a average feature version for all others.
+
+

At least for important top-level pages it is sometimes + necessary to provide the optimum of browser dependent + content, i.e. one has to provide a maximum version for the + latest Netscape variants, a minimum version for the Lynx + browsers and a average feature version for all others.

+
Solution:
- We cannot use content negotiation because the browsers do +

We cannot use content negotiation because the browsers do not provide their type in that form. Instead we have to act on the HTTP header "User-Agent". The following condig does the following: If the HTTP header "User-Agent" @@ -1115,13 +1070,9 @@ RewriteRule ^foo\.html$ bar.html [foo.20.html. All other browsers receive page foo.32.html. - This is done by the following ruleset: + This is done by the following ruleset:

- - - - -
-
+
 RewriteCond %{HTTP_USER_AGENT}  ^Mozilla/3.*
 RewriteRule ^foo\.html$         foo.NS.html          [L]
 
@@ -1130,67 +1081,61 @@ RewriteCond %{HTTP_USER_AGENT}  ^Mozilla/[12].*
 RewriteRule ^foo\.html$         foo.20.html          [L]
 
 RewriteRule ^foo\.html$         foo.32.html          [L]
-
-
+
-

Dynamic Mirror

+
+ +
+ + Dynamic Mirror
Description:
-
Assume there are nice webpages on remote hosts we want - to bring into our namespace. For FTP servers we would use - the mirror program which actually maintains an - explicit up-to-date copy of the remote data on the local - machine. For a webserver we could use the program - webcopy which acts similar via HTTP. But both - techniques have one major drawback: The local copy is - always just as up-to-date as often we run the program. It - would be much better if the mirror is not a static one we - have to establish explicitly. Instead we want a dynamic - mirror with data which gets updated automatically when - there is need (updated data on the remote host).
+
+

Assume there are nice webpages on remote hosts we want + to bring into our namespace. For FTP servers we would use + the mirror program which actually maintains an + explicit up-to-date copy of the remote data on the local + machine. For a webserver we could use the program + webcopy which acts similar via HTTP. But both + techniques have one major drawback: The local copy is + always just as up-to-date as often we run the program. It + would be much better if the mirror is not a static one we + have to establish explicitly. Instead we want a dynamic + mirror with data which gets updated automatically when + there is need (updated data on the remote host).

+
Solution:
- To provide this feature we map the remote webpage or even +

To provide this feature we map the remote webpage or even the complete remote webarea to our namespace by the use - of the Proxy Throughput feature (flag [P]): + of the Proxy Throughput feature + (flag [P]):

- - - - -
-
+
 RewriteEngine  on
 RewriteBase    /~quux/
 RewriteRule    ^hotsheet/(.*)$  http://www.tstimpreso.com/hotsheet/$1  [P]
-
-
- - - - - -
-
+
+ +
 RewriteEngine  on
 RewriteBase    /~quux/
 RewriteRule    ^usa-news\.html$   http://www.quux-corp.com/news/index.html  [P]
-
-
+
-

Reverse Dynamic Mirror

+
+ +
+ + Reverse Dynamic Mirror
Description:
@@ -1200,125 +1145,105 @@ RewriteRule ^usa-news\.html$ http://www.quux-corp.
Solution:
- - - - -
-
+
 RewriteEngine on
-RewriteCond   /mirror/of/remotesite/$1           -U 
+RewriteCond   /mirror/of/remotesite/$1           -U
 RewriteRule   ^http://www\.remotesite\.com/(.*)$ /mirror/of/remotesite/$1
-
-
+
-

Retrieve Missing Data from Intranet

+
+ +
+ + Retrieve Missing Data from Intranet
Description:
-
This is a tricky way of virtually running a corporate - (external) Internet webserver - (www.quux-corp.dom), while actually keeping - and maintaining its data on a (internal) Intranet webserver - (www2.quux-corp.dom) which is protected by a - firewall. The trick is that on the external webserver we - retrieve the requested data on-the-fly from the internal - one.
+
+

This is a tricky way of virtually running a corporate + (external) Internet webserver + (www.quux-corp.dom), while actually keeping + and maintaining its data on a (internal) Intranet webserver + (www2.quux-corp.dom) which is protected by a + firewall. The trick is that on the external webserver we + retrieve the requested data on-the-fly from the internal + one.

+
Solution:
- First, we have to make sure that our firewall still +

First, we have to make sure that our firewall still protects the internal webserver and that only the external webserver is allowed to retrieve data from it. For a packet-filtering firewall we could for instance - configure a firewall ruleset like the following: - - - - - -
-
-ALLOW Host www.quux-corp.dom Port >1024 --> Host www2.quux-corp.dom Port 80  
+          configure a firewall ruleset like the following:

+ +
+ALLOW Host www.quux-corp.dom Port >1024 --> Host www2.quux-corp.dom Port 80
 DENY  Host *                 Port *     --> Host www2.quux-corp.dom Port 80
-
-
+

Just adjust it to your actual configuration syntax. - Now we can establish the mod_rewrite rules which request - the missing data in the background through the proxy - throughput feature:

- - - - - -
-
+          Now we can establish the mod_rewrite
+          rules which request the missing data in the background
+          through the proxy throughput feature:

+ +
 RewriteRule ^/~([^/]+)/?(.*)          /home/$1/.www/$2
 RewriteCond %{REQUEST_FILENAME}       !-f
 RewriteCond %{REQUEST_FILENAME}       !-d
 RewriteRule ^/home/([^/]+)/.www/?(.*) http://www2.quux-corp.dom/~$1/pub/$2 [P]
-
-
+
-

Load Balancing

+
+ +
+ + Load Balancing
Description:
-
Suppose we want to load balance the traffic to - www.foo.com over www[0-5].foo.com - (a total of 6 servers). How can this be done?
+
+

Suppose we want to load balance the traffic to + www.foo.com over www[0-5].foo.com + (a total of 6 servers). How can this be done?

+
Solution:
- There are a lot of possible solutions for this problem. +

There are a lot of possible solutions for this problem. We will discuss first a commonly known DNS-based variant - and then the special one with mod_rewrite: + and then the special one with mod_rewrite:

  1. - DNS Round-Robin + DNS Round-Robin

    The simplest method for load-balancing is to use - the DNS round-robin feature of BIND. Here you just - configure www[0-9].foo.com as usual in - your DNS with A(address) records, e.g.

    - - - - - -
    -
    +              the DNS round-robin feature of BIND.
    +              Here you just configure www[0-9].foo.com
    +              as usual in your DNS with A(address) records, e.g.

    + +
     www0   IN  A       1.2.3.1
     www1   IN  A       1.2.3.2
     www2   IN  A       1.2.3.3
     www3   IN  A       1.2.3.4
     www4   IN  A       1.2.3.5
     www5   IN  A       1.2.3.6
    -
    -
    +

    Then you additionally add the following entry:

    - - - - -
    -
    +
     www    IN  CNAME   www0.foo.com.
            IN  CNAME   www1.foo.com.
            IN  CNAME   www2.foo.com.
    @@ -1326,16 +1251,13 @@ www    IN  CNAME   www0.foo.com.
            IN  CNAME   www4.foo.com.
            IN  CNAME   www5.foo.com.
            IN  CNAME   www6.foo.com.
    -
    -
    +

    Notice that this seems wrong, but is actually an - intended feature of BIND and can be used in this way. - However, now when www.foo.com gets - resolved, BIND gives out www0-www6 - but - in a slightly permutated/rotated order every time. + intended feature of BIND and can be used + in this way. However, now when www.foo.com gets + resolved, BIND gives out www0-www6 + - but in a slightly permutated/rotated order every time. This way the clients are spread over the various servers. But notice that this not a perfect load balancing scheme, because DNS resolve information @@ -1349,7 +1271,7 @@ www IN CNAME www0.foo.com.

  2. - DNS Load-Balancing + DNS Load-Balancing

    A sophisticated DNS-based method for load-balancing is to use the program @@ -1362,23 +1284,16 @@ www IN CNAME www0.foo.com.

  3. - Proxy Throughput Round-Robin + Proxy Throughput Round-Robin -

    In this variant we use mod_rewrite and its proxy - throughput feature. First we dedicate +

    In this variant we use mod_rewrite + and its proxy throughput feature. First we dedicate www0.foo.com to be actually www.foo.com by using a single

    - - - - -
    -
    +
     www    IN  CNAME   www0.foo.com.
    -
    -
    +

    entry in the DNS. Then we convert www0.foo.com to a proxy-only server, @@ -1389,26 +1304,15 @@ www IN CNAME www0.foo.com. contacts a load balancing script lb.pl for all URLs.

    - - - - -
    -
    +
     RewriteEngine on
     RewriteMap    lb      prg:/path/to/lb.pl
     RewriteRule   ^/(.+)$ ${lb:$1}           [P,L]
    -
    -
    +

    Then we write lb.pl:

    - - - - -
    -
    +
     #!/path/to/perl
     ##
     ##  lb.pl -- load balancing script
    @@ -1417,7 +1321,7 @@ RewriteRule   ^/(.+)$ ${lb:$1}           [P,L]
     $| = 1;
     
     $name   = "www";     # the hostname base
    -$first  = 1;         # the first server (not 0 here, because 0 is myself) 
    +$first  = 1;         # the first server (not 0 here, because 0 is myself)
     $last   = 5;         # the last server in the round-robin
     $domain = "foo.dom"; # the domainname
     
    @@ -1429,21 +1333,18 @@ while (<STDIN>) {
     }
     
     ##EOF##
    -
    -
    + -

    A last notice: Why is this useful? Seems like + A last notice: Why is this useful? Seems like www0.foo.com still is overloaded? The answer is yes, it is overloaded, but with plain proxy throughput requests, only! All SSI, CGI, ePerl, etc. processing is completely done on the other machines. - This is the essential point.

    + This is the essential point.
  4. - Hardware/TCP Round-Robin + Hardware/TCP Round-Robin

    There is a hardware solution available, too. Cisco has a beast called LocalDirector which does a load @@ -1456,7 +1357,11 @@ while (<STDIN>) {

-

Reverse Proxy

+
+ +
+ + Reverse Proxy
Description:
@@ -1466,11 +1371,7 @@ while (<STDIN>) {
Solution:
- - - - -
-
+
 ##
 ##  apache-rproxy.conf -- Apache configuration for Reverse Proxy Usage
 ##
@@ -1534,13 +1435,13 @@ RewriteRule    ^(http|ftp)://.*          -  [F]
 
 #   now choose the possible servers for particular URL types
 RewriteRule    ^/(.*\.(cgi|shtml))$  to://${server:dynamic}/$1  [S=1]
-RewriteRule    ^/(.*)$               to://${server:static}/$1  
+RewriteRule    ^/(.*)$               to://${server:static}/$1
 
-#   and delegate the generated URL by passing it 
+#   and delegate the generated URL by passing it
 #   through the proxy module
 RewriteRule    ^to://([^/]+)/(.*)    http://$1/$2   [E=SERVER:$1,P,L]
 
-#   and make really sure all other stuff is forbidden 
+#   and make really sure all other stuff is forbidden
 #   when it should survive the above rules...
 RewriteRule    .*                    -              [F]
 
@@ -1555,16 +1456,9 @@ ProxyPassReverse  /  http://www3.foo.dom/
 ProxyPassReverse  /  http://www4.foo.dom/
 ProxyPassReverse  /  http://www5.foo.dom/
 ProxyPassReverse  /  http://www6.foo.dom/
-
-
- - - - - -
-
+
+ +
 ##
 ##  apache-rproxy.conf-servers -- Apache/mod_rewrite selection table
 ##
@@ -1573,49 +1467,43 @@ ProxyPassReverse  /  http://www6.foo.dom/
 #   pages (HTML files and Images, etc.)
 static    www1.foo.dom|www2.foo.dom|www3.foo.dom|www4.foo.dom
 
-#   list of backend servers which serve dynamically 
+#   list of backend servers which serve dynamically
 #   generated page (CGI programs or mod_perl scripts)
 dynamic   www5.foo.dom|www6.foo.dom
-
-
+
-

New MIME-type, New Service

+
+ +
+ + New MIME-type, New Service
Description:
- On the net there are a lot of nifty CGI programs. But +

On the net there are a lot of nifty CGI programs. But their usage is usually boring, so a lot of webmaster don't use them. Even Apache's Action handler feature for MIME-types is only appropriate when the CGI programs - don't need special URLs (actually PATH_INFO and - QUERY_STRINGS) as their input. First, let us configure a - new file type with extension .scgi (for - secure CGI) which will be processed by the popular - cgiwrap program. The problem here is that - for instance we use a Homogeneous URL Layout (see above) - a file inside the user homedirs has the URL + don't need special URLs (actually PATH_INFO + and QUERY_STRINGS) as their input. First, + let us configure a new file type with extension + .scgi (for secure CGI) which will be processed + by the popular cgiwrap program. The problem + here is that for instance we use a Homogeneous URL Layout + (see above) a file inside the user homedirs has the URL /u/user/foo/bar.scgi. But cgiwrap needs the URL in the form /~user/foo/bar.scgi/. The following rule - solves the problem: + solves the problem:

- - - - -
-
+
 RewriteRule ^/[uge]/([^/]+)/\.www/(.+)\.scgi(.*) ...
 ... /internal/cgi/user/cgiwrap/~$1/$2.scgi$3  [NS,T=application/x-http-cgi]
-
-
+

Or assume we have some more nifty programs: wwwlog (which displays the @@ -1627,9 +1515,10 @@ RewriteRule ^/[uge]/([^/]+)/\.www/(.+)\.scgi(.*) ... still requested from that areas, i.e. typically we would run the swwidx program from within /u/user/foo/ via hyperlink to

-
+
+
 /internal/cgi/user/swwidx?i=/u/user/foo/
-
+

which is ugly. Because we have to hard-code both the location of the area @@ -1641,32 +1530,27 @@ RewriteRule ^/[uge]/([^/]+)/\.www/(.+)\.scgi(.*) ...

Solution:
- The solution here is to provide a special new URL format +

The solution here is to provide a special new URL format which automatically leads to the proper CGI invocation. - We configure the following: + We configure the following:

- - - - -
-
+
 RewriteRule   ^/([uge])/([^/]+)(/?.*)/\*  /internal/cgi/user/wwwidx?i=/$1/$2$3/
 RewriteRule   ^/([uge])/([^/]+)(/?.*):log /internal/cgi/user/wwwlog?f=/$1/$2$3
-
-
+

Now the hyperlink to search at /u/user/foo/ reads only

-
+
+
 HREF="*"
-
+

which internally gets automatically transformed to

-
+
+
 /internal/cgi/user/wwwidx?i=/u/user/foo/
-
+

The same approach leads to an invocation for the access log CGI program when the hyperlink @@ -1674,76 +1558,74 @@ HREF="*"

-

From Static to Dynamic

+
+ +
+ + From Static to Dynamic
Description:
-
How can we transform a static page - foo.html into a dynamic variant - foo.cgi in a seamless way, i.e. without notice - by the browser/user.
+
+

How can we transform a static page + foo.html into a dynamic variant + foo.cgi in a seamless way, i.e. without notice + by the browser/user.

+
Solution:
- We just rewrite the URL to the CGI-script and force the +

We just rewrite the URL to the CGI-script and force the correct MIME-type so it gets really run as a CGI-script. This way a request to /~quux/foo.html internally leads to the invocation of - /~quux/foo.cgi. + /~quux/foo.cgi.

- - - - -
-
+
 RewriteEngine  on
 RewriteBase    /~quux/
 RewriteRule    ^foo\.html$  foo.cgi  [T=application/x-httpd-cgi]
-
-
+
-

On-the-fly Content-Regeneration

+
+ +
+ + On-the-fly Content-Regeneration
Description:
-
Here comes a really esoteric feature: Dynamically - generated but statically served pages, i.e. pages should be - delivered as pure static pages (read from the filesystem - and just passed through), but they have to be generated - dynamically by the webserver if missing. This way you can - have CGI-generated pages which are statically served unless - one (or a cronjob) removes the static contents. Then the - contents gets refreshed.
+
+

Here comes a really esoteric feature: Dynamically + generated but statically served pages, i.e. pages should be + delivered as pure static pages (read from the filesystem + and just passed through), but they have to be generated + dynamically by the webserver if missing. This way you can + have CGI-generated pages which are statically served unless + one (or a cronjob) removes the static contents. Then the + contents gets refreshed.

+
Solution:
- This is done via the following ruleset: + This is done via the following ruleset: - - - - -
-
+
 RewriteCond %{REQUEST_FILENAME}   !-s
 RewriteRule ^page\.html$          page.cgi   [T=application/x-httpd-cgi,L]
-
-
+

Here a request to page.html leads to a internal run of a corresponding page.cgi if page.html is still missing or has filesize null. The trick here is that page.cgi is a - usual CGI script which (additionally to its STDOUT) + usual CGI script which (additionally to its STDOUT) writes its output to the file page.html. Once it was run, the server sends out the data of page.html. When the webmaster wants to force @@ -1752,55 +1634,57 @@ RewriteRule ^page\.html$ page.cgi [

-

Document With Autorefresh

+
+ +
+ + Document With Autorefresh
Description:
-
Wouldn't it be nice while creating a complex webpage if - the webbrowser would automatically refresh the page every - time we write a new version from within our editor? - Impossible?
+
+

Wouldn't it be nice while creating a complex webpage if + the webbrowser would automatically refresh the page every + time we write a new version from within our editor? + Impossible?

+
Solution:
- No! We just combine the MIME multipart feature, the +

No! We just combine the MIME multipart feature, the webserver NPH feature and the URL manipulation power of - mod_rewrite. First, we establish a new URL feature: - Adding just :refresh to any URL causes this - to be refreshed every time it gets updated on the - filesystem. - - - - - -
-
+          mod_rewrite. First, we establish a new
+          URL feature: Adding just :refresh to any
+          URL causes this to be refreshed every time it gets
+          updated on the filesystem.

+ +
 RewriteRule   ^(/[uge]/[^/]+/?.*):refresh  /internal/cgi/apache/nph-refresh?f=$1
-
-
+

Now when we reference the URL

-
+
+
 /u/foo/bar/page.html:refresh
-
+

this leads to the internal invocation of the URL

-
+
+
 /internal/cgi/apache/nph-refresh?f=/u/foo/bar/page.html
-
+

The only missing part is the NPH-CGI script. Although one would usually say "left as an exercise to the reader" ;-) I will provide this, too.

-
+
+
 #!/sw/bin/perl
 ##
 ##  nph-refresh -- NPH/CGI script for auto refreshing pages
-##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved. 
+##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
 ##
 $| = 1;
 
@@ -1898,50 +1782,46 @@ for ($n = 0; $n &lt; $QS_n; $n++) {
 exit(0);
 
 ##EOF##
-
+
-

Mass Virtual Hosting

+
+ +
+ + Mass Virtual Hosting
Description:
-
The <VirtualHost> feature of Apache - is nice and works great when you just have a few dozens - virtual hosts. But when you are an ISP and have hundreds of - virtual hosts to provide this feature is not the best - choice.
+
+

The VirtualHost feature of Apache is nice + and works great when you just have a few dozens + virtual hosts. But when you are an ISP and have hundreds of + virtual hosts to provide this feature is not the best + choice.

+
Solution:
- To provide this feature we map the remote webpage or even +

To provide this feature we map the remote webpage or even the complete remote webarea to our namespace by the use - of the Proxy Throughput feature (flag [P]): + of the Proxy Throughput feature (flag [P]):

- - - - -
-
+
+##
+##  vhost.map
 ##
-##  vhost.map 
-## 
 www.vhost1.dom:80  /path/to/docroot/vhost1
 www.vhost2.dom:80  /path/to/docroot/vhost2
      :
 www.vhostN.dom:80  /path/to/docroot/vhostN
-
-
- - - - - -
-
+
+ +
 ##
 ##  httpd.conf
 ##
@@ -1973,7 +1853,7 @@ RewriteCond   %{REQUEST_URL}  !^/commonurl2/.*
 RewriteCond   %{REQUEST_URL}  !^/commonurlN/.*
 #
 #   2. make sure we have a Host header, because
-#      currently our approach only supports 
+#      currently our approach only supports
 #      virtual hosting through this header
 RewriteCond   %{HTTP_HOST}  !^$
 #
@@ -1981,38 +1861,45 @@ RewriteCond   %{HTTP_HOST}  !^$
 RewriteCond   ${lowercase:%{HTTP_HOST}|NONE}  ^(.+)$
 #
 #   4. lookup this hostname in vhost.map and
-#      remember it only when it is a path 
+#      remember it only when it is a path
 #      (and not "NONE" from above)
 RewriteCond   ${vhost:%1}  ^(/.*)$
 #
-#   5. finally we can map the URL to its docroot location 
+#   5. finally we can map the URL to its docroot location
 #      and remember the virtual host for logging puposes
 RewriteRule   ^/(.*)$   %1/$1  [E=VHOST:${lowercase:%{HTTP_HOST}}]
-    : 
-
-
+ : +
-

Access Restriction

+
+ +
+ +
-

Blocking of Robots

+ Access Restriction + +
+ + Blocking of Robots
Description:
-
How can we block a really annoying robot from - retrieving pages of a specific webarea? A - /robots.txt file containing entries of the - "Robot Exclusion Protocol" is typically not enough to get - rid of such a robot.
+
+

How can we block a really annoying robot from + retrieving pages of a specific webarea? A + /robots.txt file containing entries of the + "Robot Exclusion Protocol" is typically not enough to get + rid of such a robot.

+
Solution:
- We use a ruleset which forbids the URLs of the webarea +

We use a ruleset which forbids the URLs of the webarea /~quux/foo/arc/ (perhaps a very deep directory indexed area where the robot traversal would create big server load). We have to make sure that we @@ -2020,123 +1907,96 @@ RewriteRule ^/(.*)$ %1/$1 [E=VHOST:${lowercase:%{HTTP_HOST}}] forbidding the host where the robot runs is not enough. This would block users from this host, too. We accomplish this by also matching the User-Agent HTTP header - information. - - - - - -
-
-RewriteCond %{HTTP_USER_AGENT}   ^NameOfBadRobot.*      
+          information.

+ +
+RewriteCond %{HTTP_USER_AGENT}   ^NameOfBadRobot.*
 RewriteCond %{REMOTE_ADDR}       ^123\.45\.67\.[8-9]$
 RewriteRule ^/~quux/foo/arc/.+   -   [F]
-
-
+

-

Blocked Inline-Images

+
+ +
+ + Blocked Inline-Images
Description:
-
Assume we have under http://www.quux-corp.de/~quux/ - some pages with inlined GIF graphics. These graphics are - nice, so others directly incorporate them via hyperlinks to - their pages. We don't like this practice because it adds - useless traffic to our server.
+
+

Assume we have under http://www.quux-corp.de/~quux/ + some pages with inlined GIF graphics. These graphics are + nice, so others directly incorporate them via hyperlinks to + their pages. We don't like this practice because it adds + useless traffic to our server.

+
Solution:
- While we cannot 100% protect the images from inclusion, +

While we cannot 100% protect the images from inclusion, we can at least restrict the cases where the browser - sends a HTTP Referer header. - - - - - -
-
-RewriteCond %{HTTP_REFERER} !^$                                  
+          sends a HTTP Referer header.

+ +
+RewriteCond %{HTTP_REFERER} !^$
 RewriteCond %{HTTP_REFERER} !^http://www.quux-corp.de/~quux/.*$ [NC]
 RewriteRule .*\.gif$        -                                    [F]
-
-
- - - - - -
-
-RewriteCond %{HTTP_REFERER}         !^$                                  
+
+ +
+RewriteCond %{HTTP_REFERER}         !^$
 RewriteCond %{HTTP_REFERER}         !.*/foo-with-gif\.html$
 RewriteRule ^inlined-in-foo\.gif$   -                        [F]
-
-
+

-

Host Deny

+
+ +
+ + Host Deny
Description:
-
How can we forbid a list of externally configured hosts - from using our server?
+
+

How can we forbid a list of externally configured hosts + from using our server?

+
Solution:
- For Apache >= 1.3b6: +

For Apache >= 1.3b6:

- - - - -
-
+
 RewriteEngine on
 RewriteMap    hosts-deny  txt:/path/to/hosts.deny
 RewriteCond   ${hosts-deny:%{REMOTE_HOST}|NOT-FOUND} !=NOT-FOUND [OR]
 RewriteCond   ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND} !=NOT-FOUND
 RewriteRule   ^/.*  -  [F]
-
-
+

For Apache <= 1.3b6:

- - - - -
-
+
 RewriteEngine on
 RewriteMap    hosts-deny  txt:/path/to/hosts.deny
 RewriteRule   ^/(.*)$ ${hosts-deny:%{REMOTE_HOST}|NOT-FOUND}/$1
 RewriteRule   !^NOT-FOUND/.* - [F]
-RewriteRule   ^NOT-FOUND/(.*)$ ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND}/$1 
+RewriteRule   ^NOT-FOUND/(.*)$ ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND}/$1
 RewriteRule   !^NOT-FOUND/.* - [F]
 RewriteRule   ^NOT-FOUND/(.*)$ /$1
-
-
- - - - - -
-
+
+ +
 ##
-##  hosts.deny 
+##  hosts.deny
 ##
 ##  ATTENTION! This is a map, not a list, even when we treat it as such.
 ##             mod_rewrite parses it for key/value pairs, so at least a
@@ -2146,110 +2006,100 @@ RewriteRule   ^NOT-FOUND/(.*)$ /$1
 193.102.180.41 -
 bsdti1.sdm.de  -
 192.76.162.40  -
-
-
+
-

Proxy Deny

+
+ +
+ + Proxy Deny
Description:
-
How can we forbid a certain host or even a user of a - special host from using the Apache proxy?
+
+

How can we forbid a certain host or even a user of a + special host from using the Apache proxy?

+
Solution:
- We first have to make sure mod_rewrite is below(!) - mod_proxy in the Configuration file when - compiling the Apache webserver. This way it gets called - _before_ mod_proxy. Then we configure the following for a - host-dependent deny... - - - - - -
-
-RewriteCond %{REMOTE_HOST} ^badhost\.mydomain\.com$ 
+          

We first have to make sure mod_rewrite + is below(!) mod_proxy in the Configuration + file when compiling the Apache webserver. This way it gets + called before mod_proxy. Then we + configure the following for a host-dependent deny...

+ +
+RewriteCond %{REMOTE_HOST} ^badhost\.mydomain\.com$
 RewriteRule !^http://[^/.]\.mydomain.com.*  - [F]
-
-
+

...and this one for a user@host-dependent deny:

- - - - -
-
+
 RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST}  ^badguy@badhost\.mydomain\.com$
 RewriteRule !^http://[^/.]\.mydomain.com.*  - [F]
-
-
+
-

Special Authentication Variant

+
+ +
+ + Special Authentication Variant
Description:
-
Sometimes a very special authentication is needed, for - instance a authentication which checks for a set of - explicitly configured users. Only these should receive - access and without explicit prompting (which would occur - when using the Basic Auth via mod_access).
+
+

Sometimes a very special authentication is needed, for + instance a authentication which checks for a set of + explicitly configured users. Only these should receive + access and without explicit prompting (which would occur + when using the Basic Auth via mod_access).

+
Solution:
- We use a list of rewrite conditions to exclude all except - our friends: +

We use a list of rewrite conditions to exclude all except + our friends:

- - - - -
-
-RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend1@client1.quux-corp\.com$ 
-RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend2@client2.quux-corp\.com$ 
-RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend3@client3.quux-corp\.com$ 
+
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend1@client1.quux-corp\.com$
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend2@client2.quux-corp\.com$
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend3@client3.quux-corp\.com$
 RewriteRule ^/~quux/only-for-friends/      -                                 [F]
-
-
+
-

Referer-based Deflector

+
+ +
+ + Referer-based Deflector
Description:
-
How can we program a flexible URL Deflector which acts - on the "Referer" HTTP header and can be configured with as - many referring pages as we like?
+
+

How can we program a flexible URL Deflector which acts + on the "Referer" HTTP header and can be configured with as + many referring pages as we like?

+
Solution:
- Use the following really tricky ruleset... +

Use the following really tricky ruleset...

- - - - -
-
+
 RewriteMap  deflector txt:/path/to/deflector.map
 
 RewriteCond %{HTTP_REFERER} !=""
@@ -2259,19 +2109,12 @@ RewriteRule ^.* %{HTTP_REFERER} [R,L]
 RewriteCond %{HTTP_REFERER} !=""
 RewriteCond ${deflector:%{HTTP_REFERER}|NOT-FOUND} !=NOT-FOUND
 RewriteRule ^.* ${deflector:%{HTTP_REFERER}} [R,L]
-
-
+

... in conjunction with a corresponding rewrite map:

- - - - -
-
+
 ##
 ##  deflector.map
 ##
@@ -2279,58 +2122,57 @@ RewriteRule ^.* ${deflector:%{HTTP_REFERER}} [R,L]
 http://www.badguys.com/bad/index.html    -
 http://www.badguys.com/bad/index2.html   -
 http://www.badguys.com/bad/index3.html   http://somewhere.com/
-
-
+

This automatically redirects the request back to the - referring page (when "-" is used as the value in the map) - or to a specific URL (when an URL is specified in the map - as the second argument).

+ referring page (when "-" is used as the value + in the map) or to a specific URL (when an URL is specified + in the map as the second argument).

-

Other

+
+ +
+ +
-

External Rewriting Engine

+ Other + +
+ + External Rewriting Engine
Description:
-
A FAQ: How can we solve the FOO/BAR/QUUX/etc. problem? - There seems no solution by the use of mod_rewrite...
+
+

A FAQ: How can we solve the FOO/BAR/QUUX/etc. + problem? There seems no solution by the use of + mod_rewrite...

+
Solution:
- Use an external rewrite map, i.e. a program which acts - like a rewrite map. It is run once on startup of Apache - receives the requested URLs on STDIN and has to put the - resulting (usually rewritten) URL on STDOUT (same - order!). - - - - - -
-
+          

Use an external RewriteMap, i.e. a program which acts + like a RewriteMap. It is run once on startup of Apache + receives the requested URLs on STDIN and has + to put the resulting (usually rewritten) URL on + STDOUT (same order!).

+ +
 RewriteEngine on
 RewriteMap    quux-map       prg:/path/to/map.quux.pl
 RewriteRule   ^/~quux/(.*)$  /~quux/${quux-map:$1}
-
-
- - - - - -
-
+
+ +
 #!/path/to/perl
 
-#   disable buffered I/O which would lead 
+#   disable buffered I/O which would lead
 #   to deadloops for the Apache server
 $| = 1;
 
@@ -2340,10 +2182,7 @@ while (<>) {
     s|^foo/|bar/|;
     print $_;
 }
-
-
+

This is a demonstration-only example and just rewrites all URLs /~quux/foo/... to @@ -2353,8 +2192,10 @@ while (<>) { system administrator can define it.

- -
- - + + + + + +