Sealyu

--- 博客已迁移至: http://www.sealyu.com/blog

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  618 随笔 :: 87 文章 :: 225 评论 :: 0 Trackbacks

Apache HowTo

Printer Friendly Version
print-friendly
version
Introduction

This document explains how to connect Tomcat to the popular open source web server, Apache. There is actually three versions of Apache, 1.3, 2.0 and 2.2 and all can be used with mod_jk, the Tomcat redirector module.

It is recommended that you also read the Workers HowTo document to learn how to setup the working entities between your web server and Tomcat Engines. For more detailed configuration information consult the Reference Guide for workers.properties, uriworkermap and Apache.

Waring: If Apache httpd and Tomcat are configured to serve content from the same filing system location then care must be taken to ensure that httpd is not able to serve inappropriate content such as the contents of the WEB-INF directory or JSP source code. This could occur if the httpd DocumentRoot overlaps with a Tomcat Host's appBase or the docBase of any Context. It could also occur when using the httpd Alias directive with a Tomcat Host's appBase or the docBase of any Context.

This document was originally part of Tomcat: A Minimalistic User's Guide written by Gal Shachor, but has been split off for organizational reasons.

Document Conventions and Assumptions

${tomcat_home} is the root directory of tomcat. Your Tomcat installation should have the following subdirectories:

  • ${tomcat_home}"conf - Where you can place various configuration files
  • ${tomcat_home}"webapps - Containing example applications
  • ${tomcat_home}"bin - Where you place web server plugins

In all the examples in this document ${tomcat_home} will be /var/tomcat3. A worker is defined to be a tomcat process that accepts work from the Apache server.

Supported Configuration

The mod_jk module was developed and tested on:

  • Linux, FreeBSD, AIX, HP-UX, MacOS X, Solaris and should works on major Unixes platforms supporting Apache 1.3 and/or 2.0/2.2
  • WinNT4.0-i386 SP4/SP5/SP6a (should be able to work with other service packs), Win2K and WinXP and Win98
  • Cygwin (until you have an apache server and autoconf/automake support tools)
  • Netware
  • i5/OS V5R4 (System I) with Apache 2.0.58. Be sure to have the latest Apache PTF installed.
  • Tomcat 3.2.x, Tomcat 3.3.x, Tomcat 4.0.x, Tomcat 4.1.x, Tomcat 5.0.x, Tomcat 5.5.x and Tomcat 6.

The redirector uses ajp12 and ajp13 to send requests to the Tomcat containers. There is also an option to use Tomcat in process, more about the in-process mode can be found in the in process howto.

Who support ajp protocols ?

The ajp12 protocol is only available in Tomcat 3.2.x and 3.3.x.

The ajp12 has been deprecated with Tomcat 3.3.x and you should use instead ajp13 which is the only ajp protocol known by Tomcat 4.x, 5 and 5.5 and Tomcat 6.

Of course Tomcat 3.2.x and 3.3.x also support ajp13 protocol.

Others servlet engines such as jetty have support for ajp13 protocol

How does it work ?

In a nutshell a web server is waiting for client HTTP requests. When these requests arrive the server does whatever is needed to serve the requests by providing the necessary content.

Adding a servlet container may somewhat change this behavior. Now the web server needs also to perform the following:

  • Load the servlet container adapter library and initialize it (prior to serving requests).
  • When a request arrives, it needs to check and see if a certain request belongs to a servlet, if so it needs to let the adapter take the request and handle it.

The adapter on the other hand needs to know what requests it is going to serve, usually based on some pattern in the request URL, and to where to direct these requests.

Things are even more complex when the user wants to set a configuration that uses virtual hosts, or when they want multiple developers to work on the same web server but on different servlet container JVMs. We will cover these two cases in the advanced sections.

Obtaining mod_jk

mod_jk can be obtained in two formats - binary and source. Depending on the platform you are running your web server on, a binary version of mod_jk may be available.

It is recommended to use the binary version if one is available. If the binary is not available, follow the instructions for building mod_jk from source. The mod_jk source can be downloaded from a mirror here

The binaries for mod_jk are now available for several platforms. The binaries are located in subdirectories by platform.

For some platforms, such as Windows, this is the typical way of obtaining mod_jk since most Windows systems do not have C compilers.

For others, the binary distribution of mod_jk offers simpler installation.

For example JK 1.2.x can be downloaded from a mirror here (look for JK 1.2 Binary Releases). The "JK 1.2 Binary Releases" link contains binary version for a variety of operating systems for both Apache 1.3 and Apache 2.

Installation

mod_jk requires two entities:

  • mod_jk.xxx - The Apache module, depending on your operating system, it will be mod_jk.so, mod_jk.nlm or or MOD_JK.SRVPGM (see the build section).
  • workers.properties - A file that describes the host(s) and port(s) used by the workers (Tomcat processes). A sample workers.properties can be found under the conf directory in the source download.

Also as with other Apache modules, mod_jk should be first installed on the modules directory of your Apache webserver, ie : /usr/lib/apache and you should update your httpd.conf file.

Disabling old mod_jserv

If you've previously configured Apache to use mod_jserv, remove any ApJServMount directives from your httpd.conf.

If you're including tomcat-apache.conf or tomcat.conf, you'll want to remove them as well - they are specific to mod_jserv.

The mod_jserv configuration directives are not compatible with mod_jk !

Using Tomcat auto-configure

The auto-configure works only for a single Tomcat running on the same machine where Apache (httpd) is running. The simplest way to configure Apache to use mod_jk is to turn on the Apache auto-configure setting in Tomcat and put the following include directive at the end of your Apache httpd.conf file (make sure you replace $TOMCAT_HOME with the correct path for your Tomcat installation:

    #To be added at the end of your httpd.conf
Include $TOMCAT_HOME/conf/jk/mod_jk.conf-auto

Note: this file may also be generated as $TOMCAT_HOME/conf/auto/mod_jk.conf

This will tell Apache to use directives in the mod_jk.conf-auto file in the Apache configuration. This file is created by enabling the Apache auto-configuration by creating your workers.properties file at $TOMCAT_HOME/conf/jk/workers.properties and adding the listener to the Engine element in the server.xml file as per the following example. Please note that this example is specific to Tomcat 5.x, unlike other sections of this document which also apply to previous Tomcat branches.

  ...
<Engine ...>
...
<Listener className="org.apache.jk.config.ApacheConfig" modJk="/path/to/mod_jk.so" />
...
</Engine>
...

Then restart Tomcat and mod_jk.conf should be generated. For more information on this topic, please refer to the API documentation at the Tomcat docs website.

Custom mod_jk configuration

You should use custom configuration when :

  • You couldn't use mod_jk.conf-auto since Tomcat engine isn't on the same machine that your Apache web server, ie when you have an Apache in front of a Tomcat Farm.
  • Another case for custom configuration is when your Apache is in front of many differents Tomcat engines, each one having it's own configuration, a general case in ISP hosting
  • Also all Apache webmaster will retain custom configuration to be able to tune the settings to their real needs.
Simple configuration example

Here is a simple configuration:

    # Load mod_jk module
LoadModule jk_module libexec/mod_jk.so
# Declare the module for <IfModule directive> (remove this line on Apache 2.0.x)
AddModule mod_jk.c
# Where to find workers.properties
JkWorkersFile /etc/httpd/conf/workers.properties
# Where to put jk shared memory
JkShmFile /var/log/httpd/mod_jk.shm
# Where to put jk logs
JkLogFile /var/log/httpd/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel info
# Select the timestamp log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
# Send servlet for context /examples to worker named worker1
JkMount /examples/servlet/* worker1
# Send JSPs for context /examples to worker named worker1
JkMount /examples/*.jsp worker1
mod_jk Directives

We'll discuss here the mod_jk directives and details behind them

Define workers

JkWorkersFile specify the location where mod_jk will find the workers definitions.

  JkWorkersFile     /etc/httpd/conf/workers.properties


Logging

JkLogFile specify the location where mod_jk is going to place its log file.

  JkLogFile     /var/log/httpd/mod_jk.log

Since JK 1.2.3 for Apache 2.0/2.2 and JK 1.2.16 for Apache 1.3 this can also be used for piped logging:

  JkLogFile     "|/usr/bin/rotatelogs /var/log/httpd/mod_jk.log 86400"

JkLogLevel set the log level between :

  • info log will contains standard mod_jk activity (default).
  • error log will contains also error reports.
  • debug log will contains all informations on mod_jk activity
  JkLogLevel    info

info should be your default selection for normal operations.

JkLogStampFormat will configure the date/time format found on mod_jk logfile. Using the strftime() format string it's set by default to "[%a %b %d %H:%M:%S %Y]"

  JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "



JkRequestLogFormat will configure the format of mod_jk individual request logging. Request logging is configured and enabled on a per virtual host basis. To enable request logging for a virtual host just add a JkRequestLogFormat config. The syntax of the format string is similiar to the Apache LogFormat command, here is a list of the available request log format options:

OptionsDescription
%b Bytes sent, excluding HTTP headers (CLF format)
%B Bytes sent, excluding HTTP headers
%H The request protocol
%m The request method
%p The canonical Port of the server serving the request
%q The query string (prepended with a ? if a query string exists, otherwise an empty string)
%r First line of request
%s Request HTTP status code
%T Request duration, elapsed time to handle request in seconds '.' micro seconds
%U The URL path requested, not including any query string.
%v The canonical ServerName of the server serving the request
%V The server name according to the UseCanonicalName setting
%w Tomcat worker name
%R Session route name (available with 1.2.19 and up)

  JkRequestLogFormat     "%w %V %T"


Forwarding

The directive JkOptions allow you to set many forwarding options which will enable (+) or disable (-) following option. Without any leading signs, options will be enabled.

The four following options +ForwardURIxxx are mutually exclusive. Exactly one of them is required, a negative sign prefix is not allowed with them. The default value is "ForwardURIProxy" since version 1.2.24. It was "ForwardURICompatUnparsed" in version 1.2.23 and "ForwardURICompat" until version 1.2.22. You can turn the default off by switching on one of the other two options. You should leave this at it's default value, unless you have a very good reason to change it.

All options are inherited from the global server to virtual hosts. Options that support enabling (plus options) and disabling (minus options), are inherited in the following way:

options(vhost) = plus_options(global) - minus_options(global) + plus_options(vhost) - minus_options(vhost)

Using JkOptions ForwardURIProxy, the forwarded URI will be partially reencoded after processing inside Apache httpd and before forwarding to Tomcat. This will be compatible with local URL manipulation by mod_rewrite and with URL encoded session ids.

  JkOptions     +ForwardURIProxy


Using JkOptions ForwardURICompatUnparsed, the forwarded URI will be unparsed. It's spec compliant and secure. It will always forward the original request URI, so rewriting URIs with mod_rewrite and then forwarding the rewritten URI will not work.

  JkOptions     +ForwardURICompatUnparsed


Using JkOptions ForwardURICompat, the forwarded URI will be decoded by Apache httpd. Encoded characters will be decoded and explicit path components like ".." will already be resolved. This is less spec compliant and is not safe if you are using prefix JkMount. This option will allow to rewrite URIs with mod_rewrite before forwarding.

  JkOptions     +ForwardURICompat


Using JkOptions ForwardURIEscaped, the forwarded URI will be the encoded form of the URI used by ForwardURICompat. Explicit path components like ".." will already be resolved. This will not work in combination with URL encoded session IDs, but it will allow to rewrite URIs with mod_rewrite before forwarding.

  JkOptions     +ForwardURIEscaped


JkOptions RejectUnsafeURI will block all URLs, which contain percent signs '%' or backslashes '"' after decoding.

Most web apps do not use such URLs. Using the option RejectUnsafeURI, you can block several well known URL encoding attacks. By default, this option is not set.

You can also realize such a check with mod_rewrite, which is more powerful but also slightly more complicated.

  JkOptions     +RejectUnsafeURI


JkOptions ForwardDirectories is used in conjunction with DirectoryIndex directive of Apache web server. As such mod_dir should be available to Apache, statically or dynamically (DSO)

When DirectoryIndex is configured, Apache will create sub-requests for each of the local-url's specified in the directive, to determine if there is a local file that matches (this is done by stat-ing the file).

If ForwardDirectories is set to false (default) and Apache doesn't find any files that match, Apache will serve the content of the directory (if directive Options specifies Indexes for that directory) or a 403 Forbidden response (if directive Options doesn't specify Indexes for that directory).

If ForwarDirectories is set to true and Apache doesn't find any files that match, the request will be forwarded to Tomcat for resolution. This is used in cases when Apache cannot see the index files on the file system for various reasons: Tomcat is running on a different machine, the JSP file has been precompiled etc.

Note that locally visible files will take precedence over the ones visible only to Tomcat (i.e. if Apache can see the file, that's the one that's going to get served). This is important if there is more then one type of file that Tomcat normally serves - for instance Velocity pages and JSP pages.

  JkOptions     +ForwardDirectories


JkOptions ForwardLocalAddress, you ask mod_jk to send the local address, of the Apache web server instead remote client address. This can be used by Tomcat remote address valve for allowing connections only from registered Apache web servers.

  JkOptions     +ForwardLocalAddress


JkOptions FlushPackets, you ask mod_jk to flush Apache's connection buffer after each AJP packet chunk received from Tomcat. This option can have a strong performance penalty for Apache and Tomcat as writes are performed more often than would normally be required (ie: at the end of each response).

  JkOptions     +FlushPackets


JkOptions FlushHeader, you ask mod_jk to flush Apache's connection buffer after the response headers have been received from Tomcat.

  JkOptions     +FlushHeader


JkOptions DisableReuse, you ask mod_jk to close connections immediately after their use. Normally mod_jk uses persistent connections and pools idle connections to reuse them, when new requests have to be sent to Tomcat.

Using this option will have a strong performance penalty for Apache and Tomcat. Use this only as a last resort in case of unfixable network problems. If a firewall between Apache and Tomcat silently kills idle connections, try to use the worker attribute socket_keepalive in combination with an appropriate TCP keepalive value in your OS.

  JkOptions     +DisableReuse


JkOptions ForwardKeySize, you ask mod_jk, when using ajp13, to forward also the SSL Key Size as required by Servlet API 2.3. This flag shouldn't be set when servlet engine is Tomcat 3.2.x (off by default).

  JkOptions     +ForwardKeySize


JkOptions ForwardSSLCertChain, you ask mod_jk, when using ajp13, to forward SSL certificate chain (off by default). Mod_jk only passes the SSL_CLIENT_CERT to the AJP connector. This is not a problem with self-signed certificates or certificates directly signed by the root CA certificate. However, there's a large number of certificates signed by an intermediate CA certificate, where this is a significant problem: A servlet will not have the possibility to validate the client certificate on its own. The bug would be fixed by passing on the SSL_CLIENT_CERT_CHAIN to Tomcat via the AJP connector.
This directive exists only since version 1.2.22.

  JkOptions     +ForwardSSLCertChain


The directive JkEnvVar allows you to forward environment variables from Apache server to Tomcat engine. The variables can be retrieved on the Tomcat side as request attributes. You can add a default value as a second parameter to the directive. If the default value is not given explicitely, the variable will only be send, if it is set during runtime.

The variables are inherited from the global server to virtual hosts.

  JkEnvVar     SSL_CLIENT_V_START     undefined


Assigning URLs to Tomcat

If you have created a custom or local version of mod_jk.conf-local as noted above, you can change settings such as the workers or URL prefix.

JkMount directive assign specific URLs to Tomcat. In general the structure of a JkMount directive is:

  JkMount [URL prefix] [Worker name]
  # send all requests ending in .jsp to worker1
JkMount /*.jsp worker1
# send all requests ending /servlet to worker1
JkMount /*/servlet/ worker1
# send all requests jsp requests to files located in /otherworker will go worker2
JkMount /otherworker/*.jsp worker2

You can use the JkMount directive at the top level or inside <VirtualHost> sections of your httpd.conf file.

Configuring Apache to serve static web application files

If the Tomcat Host appBase (webapps) directory is accessible by the Apache web server, Apache can be configured to serve web application context directory static files instead of passing the request to Tomcat.

Caution: For security reasons is is strongly recommended that JkMount is used to pass all requests to Tomcat by default and JkUnMount is used to explicitly exclude static content to be served by httpd. It should also be noted that content served by httpd will bypass any security constraints defined in the application's web.xml.

Use Apache's Alias directive to map a single web application context directory into Apache's document space for a VirtualHost:

  # Static files in the examples webapp are served by apache
Alias /examples /vat/tomcat3/webapps/examples
# All requests go to worker1 by default
JkMount /* worker1
# Serve html, jpg and gif using httpd
JkUnMount /*.html worker1
JkUnMount /*.jpg worker1
JkUnMount /*.gif worker1

Starting with mod_jk 1.2.6 for Apache 2.0/2.2 and 1.2.19 for Apache 1.3, it's possible to exclude some URL/URI from jk processing by setting the env var no-jk, for example with the SetEnvIf Directive.

You could use no-jk env var to fix problem with mod_alias or mod_userdir directive when jk and alias/userdir URLs matches.

  # All URL goes to tomcat except the one containing /home
<VirtualHost *:80>
ServerName testxxx.mysys
DocumentRoot /www/testxxx/htdocs

# Use SetEnvIf to st no-jk when /home/ is encountered
SetEnvIf Request_URI "/home/*" no-jk

# Now /home will goes to /home/dataxxx/
Alias /home /home/dataxxx/

<Directory "/home/dataxxx">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>

JkMount /* myssys-xxx

</VirtualHost>

Use the mod_jk JkAutoAlias directive to map all web application context directories into Apache's document space.

Attempts to access the WEB-INF or META-INF directories within a web application context or a Web Archive *.war within the Tomcat Host appBase (webapps) directory will fail with an HTTP 403, Access Forbidden

  # Static files in all Tomcat webapp context directories are served by apache
JkAutoAlias /var/tomcat3/webapps

# All requests go to worker1 by default
JkMount /* ajp13
# Serve html, jpg and gif using httpd
JkUnMount /*.html ajp13
JkUnMount /*.jpg ajp13
JkUnMount /*.gif ajp13

If you encoded all your URLs to contain the session id (;jsessionid=...), and you later decide, you want to move part of the content to Apache httpd, you can tell mod_jk to strip off all session ids from URLs for those requests, that do not get forwarded via mod_jk.

You enable this feature by setting JkStripSession to On. It can be enabled individually for virtual servers. The default value is Off.

Building mod_jk on Unix

The mod_jk build use the widely used configure system.

Prepare your mod_jk configure from subversion
In case you get source from subversion, ie without an existing configure script, you should have autoconf for configuration and installation.

To create tomcat-connectors's autoconf script, you will need libtool 1.5.2 or higher, and autoconf 2.59 or newer.

Those tools will not be required if you are just using a package downloaded from apache.org, they are only required for developers.

To create the configure script just type :

[user@host] ~ $ ./buildconf.sh
Using configure to build mod_jk

Here's how to use configure to prepare mod_jk for building, just type:

posted on 2008-07-17 16:51 seal 阅读(1510) 评论(0)  编辑  收藏 所属分类: web服务器

只有注册用户登录后才能发表评论。


网站导航: