These mappingsare important because Apache sends them the MIME types to Web clients,which use the information to determine how to display the associated content.Files with a MIME type of
Trang 1The DirectoryIndex lines specifies the files Apache looks for whenpassed a URL that does not specify a filename, that is, when the URL specifies
a directory, such as http://www.example.com/products/, instead of afile, such as http://www.example.com/products/prodlist.html.Apache searches for the files in the order listed and the first match wins In thehttpd.conffile shipped, the order is:
1 index.php
2 index.html
3 index.html.varThe TypesConfig, DefaultType, and MIMEMagicFile directives worktogether to help Apache determine file types TypesConfig tells Apachewhere to find a list or database of MIME types (/etc/mime.types in thiscase) This file maps MIME types to filename extensions Consider the follow-ing two entries from /etc/mime.types, for example:
text/html html htm video/mpeg mpeg mpg mpe
The first line means that files ending with the extensions html and htm(rather, html and htm) should be considered to be standard HTML files.Similarly, the second line indicates that files having the filename extensions.mpeg, mpg, and mpe have the MIME type video/mpeg These mappingsare important because Apache sends them the MIME types to Web clients,which use the information to determine how to display the associated content.Files with a MIME type of text/html will ordinarily be displayed as a nor-mal Web page, while Web browsers might start an MPEG player to displayfiles that have a MIME type of video/mpeg
DefaultType text/plain provides a default MIME type (plain text) for any file that Apache serves for which a MIME type is not defined.MIMEMagicFilesupplements the MIME typing system, making it possiblefor Apache to determine a file’s MIME type by examining the contents of a file.The logging directives control the level and format of Apache’s log output.The directive ErrorLog logs/error_log specifies the error log Apache uses.The four LogFormat directives define log formats named combined, common,referer, and agent (yes, referer is misspelled) These format names canthen be used in other log-related directives to identify the output format Forexample, the directive CustomLog lobs/access_log combined uses thecombinedformat defined The CustomLog directive indicates the file used
to log all requests sent to the server Access log entries might resemble the following:
Trang 2127.0.0.1 - - [26/Mar/2005:09:47:33 -0500] “GET /manual/images/up.gif HT\
The long series of AddIconByEncoding, AddIconByType, and AddIcondirectives define the various icons displayed next to files with a given icon.The directive AddIcon /icons/binary.gif bin exe, for example, indi-cates that files ending with bin and exe should have the image /icons/binary.gifdisplayed next to them Note that the directory /icons/ wasaliased to /var/www/icons/ using the Alias directive Alias /icons/
“/var/www/icons/”earlier in the httpd.conf file, so the file system path
to binary.gif is expanded to /var/www/icons/binary.gif As a back measure, the directive DefaultIcon /icons/unknown.gif definesthe default icon Apache displays if it cannot determine the file type of a givenfile based on the definitions given by the TypesConfig and MIMEModMagicdirectives and additional types appended to the MIME type listing usingAddTypedirectives
fall-To handle non-HTML document types (MIME types), Apache uses theAddTypeand AddHandler directives AddType is used for MIME types thatare not specified in MIME configuration files (as set with the MIMEMagicFiledirective) or for predefined MIME types that you want to override It works byassociating filename extensions with specific content handlers Its general syntax is:
AddType mimetype extension [ ]
This directive associates one or more filename endings specified by extension with the MIME type specified by mimetype For example, thefollowing directive assigns the MIME type text/html (a normal HTML file)with files whose filename extension is shtml:
Trang 3AddHandler’s purpose is to define a content handler for specific MIMEtypes Its syntax is comparable to AddType’s:
AddHandler handler extension [ ]
This directive associates any file that has the extension extension with thecontent handler named by handler The following statement, for instance,instructs Apache to use the image map handler imap-file with files whosename ends with map:
AddHandler imap-file map
The AddLanguage directives map filenames to language encodings So, forexample, files ending with en are treated as English documents, and filesending with en.gz or en.tgz are treated as gzip compressed English doc-uments The LanguagePriority directive, similarly, determines which filethe server returns if the browser does not indicate a preference For example, ifthe files index.en.html and index.fr.html both exist and a client doesnot specify a preferred content language, the server returns index.en.html.AddDefaultCharset and AddCharset load Apache’s support for vari-ous character sets AddDefaultCharset specifies the default character setApache uses to serve content if a browser does not specifically request one.The default character set in Fedora Core and RHEL is UTF-8
The BrowserMatch directives set environment variables that can be used
in CGI scripts and SSI based on the information in the User-Agent HTTPrequest header field The first argument is the text to match from the requestheader The second and subsequent arguments name the variables to set andthe value or values to which to set the variables The variable assignments cantake one of the following forms:
■■ varname— Sets varname to 1
■■ !varname— Removes (unsets) varname if it was already set
■■ varname=value— Assigns value to varname
If a User-Agent header matches multiple BrowserMatch strings, Apachemerges the matching strings Entries are processed in the order in which theyappear, and later entries can override earlier ones
T I P If you do not know or cannot be sure of the case of the request header you want to match, you can use the BrowserMatchNoCase directive, which matches regardless of case.
Trang 4Configuring Virtual Servers
Virtual servers (also referred to as virtual hosts) are primarily used to run Web
servers for multiple domains on a single physical system Virtual servers canalso be used to allow multiple workgroups or departments that share the samenetwork or subnet to maintain independent Web pages without requiringindividual dedicated departmental servers Virtual hosts fall into two cate-gories: IP-based virtual hosts and name-based virtual hosts
IP-based virtual hosts refer to Web servers that have different IP addresses
In some cases, the different IP addresses correspond to different Ethernet faces, such as eth0 and eth1 (machines that have multiple Ethernet interfaces
inter-are called multihomed hosts) In other cases, a single Ethernet interface is
assigned multiple IP addresses using aliases In this configuration, a systemmight have a single Ethernet interface, say, eth0, and a single primary IPaddresses, for example, 192.168.0.1 The aliases have IP addresses of the form
192.168.0.1:n, where n is a digit such as 1, 2, or 3 Regardless of the method you
use to implement virtual hosts, end users will not realize that the Web sitesthey are viewing reside on the same physical server Table 23-3 shows theApache configuration directives that control the configuration and behavior ofvirtual servers
Table 23-3 Virtual Server Configuration Directives
<VirtualHost ipaddr[:port]> Defines a virtual host whose IP address is directives addr (listening on port, if specified);
</VirtualHost> directives are one or more of the
directives listed previously and override the directives listed for the default server.
NameVirtualHost ipaddr[:port] Defines the IP address addr (listening on
port , if specified) for a name-based virtual host.
ServerAlias altname Enables the virtual server to respond to
one or more alternate hostnames altname when used with name-based virtual hosts A single VirtualHost directive can have multiple ServerAlias statements.
ServerName fqdn Sets the name of the virtual server to the
FQDN fqdn.
Trang 5A bare-bones set of name-based virtual server definitions might resemblethe following:
Listen 80 [ ]
NameVirtualHost *:80
<VirtualHost *:80>
ServerName webbeast.example.com DocumentRoot /var/www/webbeast
# other directives
</VirtualHost>
<VirtualHost *:80>
ServerName www.mydomain.com DocumentRoot /var/www/mydomain
# other directives
</VirtualHost>
<VirtualHost *:80>
ServerName www.yourdomain.org DocumentRoot /var/www/yourdomain
# other directives
</VirtualHost>
This example shows three virtual hosts, webbeast.example.com, www.mydomain.com, and www.yourdomain.org, all of which have the same IPaddress For the purpose of this example, the actual IP address doesn’t matterbecause the asterisks match all IP addresses, but suppose that the address is192.168.0.2 One of the side effects of using the asterisk is that the main serverwon’t answer any requests Apache will pass all requests to the appropriatevirtual host, depending on the name specified in the request Furthermore, thevirtual host webbeast.example.com is the default or primary serverbecause it is the first listed host As a result, it will answer any request that isn’tanswered by one of the other virtual hosts
As stated earlier in the chapter, configuration directives for the defaultserver also apply to virtual servers unless specifically overridden in a
<VirtualHost>block Therefore, if your virtual hosts require special uration needs not provided or explicitly disabled or disallowed in the defaultserver, you must specify these custom configuration directives inside theappropriate <VirtualHost> block
config-If you add a name-based virtual host to an existing Web server, you mustalso add a virtual host for the existing Web server Moreover, the directives inthe virtual host you create for the original, single-site server must match thoseyou specified for the original single-site server In addition, the virtual host
Trang 6you create for the existing server should appear before any other virtual hosts
so that it will act as the default server If you fail to add a virtual host for theexisting server, requests that should be answered by the existing Web serverwill be answered by the added virtual host Why? When a request comes in,Apache first looks to see if the requested name matches an address specifiedfor a NameVirtualHost Because all of the IP addresses in a name-based vir-
tual host are the same, Apache routes the request to the first matching virtual host, bypassing the default server.
Starting and Stopping Apache
To start and stop Apache, the preferred method is to use the httpd tion script and the service utility, as shown in the following examples:
to test configuration changes without causing havoc for yourself or users ofyour Web site
(NOT) USING THE APACHE CONFIGURATION TOOL
If you prefer graphical configuration tools, you can configure Apache’s basic functionality using HTTP Configuration Tool HTTP Configuration Tool enables you to edit the /etc/httpd/conf/httpd.conf configuration file for the Apache HTTP server Using the graphical interface, you can configure directives such as virtual hosts, logging attributes, and server control parameters To start HTTP Configuration Tool, type system-config-httpd at a command prompt
or select Red Hat ➪ System Settings ➪ Server Settings ➪ HTTP Server However,
we do not recommend using HTTP Configuration Tool on your systems because
it has the annoying habit of overwriting changes made outside of the tool and
it does not recognize manually installed Web servers that don’t store their configuration information in in /etc/httpd/conf or /etc/httpd/conf.d.
Trang 7on Web pages SSI content doesn’t have to be dynamic For simple sites, it’s agreat alternative to PHP, Perl, and other fuller-featured approaches for includ-ing headers, footers, style sheets, and so forth in Web pages.
The stock Fedora Core and RHEL configuration includes support for SSIusing the statements:
AddType text/html shtml AddOutputFilter INCLUDES shtml
The first line adds the file extension shtml to the text/html MIME type.The AddOutputFilter directive tells Apache that files with an shtmlextension should be processed using mod_include, the module that providesApache’s SSI support (the default Red Hat httpd.conf file should containthese directives)
T I P If, for some reason, you have to add the AddType text/html shtml and AddOutputFilter INCLUDES shtml directives to the httpd.conf file, the server must be restarted to make them take effect You can use one of the following commands to force Apache to reread its configuration file:
# service httpd restart
# service httpd reload
The first command stops and restarts the server The second one sends Apache the SIGHUP signal, which causes it to reread httpd.conf The effect is the same regardless of which command you use.
However, you need to tell Apache which directories contain content itshould parse for SSI content To do so, add the Includes argument to theOptions statement for the directory in which you want SSI to work Forexample, suppose that you create a directory name /var/www/html/testsand want to enable SSI for this directory Add a file named tests.conf to/etc/httpd/conf.dthat contains the following <Directory> block:
Trang 8<Directory “/var/www/html/tests”>
Options Indexes FollowSymLinks Includes AllowOverride None
Order allow,deny Allow from all
</Directory>
The Options Includes directive instructs Apache to parse files it servesfrom this directory for SSI directives Next, create the Web page shown in Listing23-3, naming it ssitest.shtml and placing it in /var/www/html/tests:
<html>
<head>
<title>SSI Test Page</title>
<link rel=”stylesheet” type=”text/css” href=”rhlnsa3.css”>
Listing 23-3 An SSI test page.
SSI directives look like HTML comments They take the following generalform:
<! #element attribute=value >
Because SSI directives look like comments, if SSI is improperly configured onthe server, the browser ignores the contents Otherwise, the server creates prop-erly formatted HTML output that Web browsers render properly In Listing 23-3,the first SSI directive is <! #exec cmd=”ls -lh /var/www” >, whichuses the built-in exec command to execute ls -lh /var/www, embedding theoutput of this command in <pre></pre> tags to maintain the appropriate for-matting The second SSI directive, include virtual=/includes/footer.html, includes a standard footer file Finally, open the document in your
Trang 9Web browser, using the URL http://localhost/tests/ssitest.shtml
if accessing the server locally or http://your.server.name/tests/ssitest.shtml if accessing the server remotely, replacing your.server.namewith the name of your Web server Figure 23-2 shows how thepage appears in the Firefox Web browser
As you can see in Figure 23-2, the SSI statement shows output of the ls -lhcommand For comparison purposes, ls -lh executed in a terminal windowmight resemble the following:
$ ls -lh /var/www
total 28K drwxr-xr-x 2 root root 33 May 19 02:07 cgi-bin drwxr-xr-x 3 root root 4.0K May 19 01:05 error drwxr-xr-x 4 root root 33 May 22 00:04 html drwxr-xr-x 3 root root 8.0K May 19 01:47 icons drwxr-xr-x 14 root root 8.0K May 19 01:05 manual drwxr-xr-x 2 root root 162 May 19 01:52 mrtg drwxr-xr-x 2 root root 61 May 19 02:09 nut-cgi-bin drwxr-xr-x 2 webalizer root 43 May 19 01:05 usage
After confirming that SSI is properly configured using the test page, the SSIconfiguration is complete
Figure 23-2 Viewing ssitest.html in Firefox.
Trang 10to create a user interface on a Web page, and, within limits, in any situation inwhich a Web-based interface is used to execute programs and display theresults in a near real-time environment This section briefly explains Apacheconfiguration directives and procedures that enable CGI.
As you might suspect by this point, your first task is to ensure that Apache’sconfiguration permits CGI script execution The ScriptAlias directive asso-ciates a directory name with a file system path, which means that Apachetreats every file in that directory as a script If not present, add the followingdirective to httpd.conf:
ScriptAlias /cgi-bin/ “/var/www/cgi-bin”
This directive tells Apache that any URL beginning with /cgi-bin/should be served from /var/www/cgi-bin Thus, given a URL of http://localhost/cgi-bin/cgiscript.plor http://your.server.name/cgi-bin/cgiscript.pl, Apache reads and executes the script /var/www/cgi-bin/cgiscript.pl If necessary, modify the configuration file toinclude the ScriptAlias directive shown, and restart Apache as explainedpreviously Then use the script in Listing 23-4 to test the configuration
#!/usr/bin/perl
print ‘Content-type: text/html\r\n\r\n’;
print ‘<html>\n’;
print ‘<head>\n’;
print ‘<title>CGI Test Page</title>\n’;
print ‘<link rel=”stylesheet” type=”text/css” \
href=”/tests/rhlnsa3.css”>\n’;
Listing 23-4 A CGI test script (continued)
Trang 11print ‘</head>\n’;
print ‘<body>\n’;
print ‘<h1>CGI Test Page</h1>\n’;
print ‘<div id=’content’>\n’;
system ‘ls -lh /var/www’;
print ‘</div> <! content >\n’;
print ‘<div id=’footer’>\n’;
system ‘cat /var/www/html/tests/footer.html’;
print ‘</div> <! footer >\n’;
or http://your.server.name/cgi-bin/cgitest.pl if accessing theserver remotely, replacing your.server.name with the name of your Webserver Figure 23-3 shows sample output from the CGI test script
If you see similar output, your server’s CGI configuration works If youenable CGI execution for other directories, make sure to test those configura-tion options as well before putting the server into production
Figure 23-3 Viewing the CGI test script in the Epiphany Web browser.
Trang 12Enabling PHP
PHP is an extremely popular and capable HTML scripting language Asshipped in Fedora Core and RHEL, PHP is enabled and ready to run, so thissection simply presents a short PHP script you can use to make sure that PHP
is working properly Create the PHP script shown in Listing 23-5, and save it
as /var/www/html/tests/phptest.php
<html>
<head>
<title>PHP Test Page</title>
<link rel=”stylesheet” type=”text/css” href=”rhlnsa3.css”>
Listing 23-5 A PHP test script.
Open the document in your Web browser, using the URL http://localhost/tests/phptest.shtml if accessing the server locally orhttp://your.server.name/tests/phptest.phpif accessing the serverremotely, replacing your.server.name with the name of your Web server.Figure 23-4 shows how the page appears in the Konqueror Web browser
If you see comparable output, PHP is working correctly By way of tion, the PHP script uses the system() function to invoke ls -lh /var/www,which in turn displays the file listing shown in Figure 23-4
Trang 13explana-Figure 23-4 Viewing the PHP test script in the Konqueror Web browser.
Creating a Secure Server with SSL
Lamentably, the Internet is a much less secure place than it used to be If theWeb site you administer will be used for electronic commerce or for exchang-ing any type of information that needs to kept private, these transactions need
to be secure SSL-enabled Web sites use a different URL prefix, https, to cate that HTTP protocol request and document transfers are encrypted You’veprobably visited SSL-enabled Web sites yourself This section describes how tocreate a secure Web server using the Secure Sockets Layer (SSL) to encryptcommunications between your Web server and Web clients It gives anoverview of SSL, describes how digital certificates fit into the security picture,and how to create a self-signed certificate A final section discusses obtaining adigital certificate from a recognized certificate authority and lists a number ofcertificate authorities from which you can obtain a valid certificate
indi-For more information about SSL and certificate creation, the followingonline resources will prove helpful:
■■ Building a Secure RedHat Apache Server HOWTO (www.tldp.org/HOWTO/SSL-RedHat-HOWTO.html)
■■ SSL Certificates HOWTO Certificates-HOWTO/index.html)
(www.tldp.org/HOWTO/SSL-■■ OpenSSL Web site (www.openssl.org)
Trang 14Understanding SSL and Server Certificates
It isn’t necessary to go into the gory details of SSL encryption to understandhow SSL and server certificates work together to create a secure Web server.SSL uses key pairs to encrypt and decrypt data One key is public, accessible toeveryone; the other key is private, so only you or another authorized personcan access it Either key can be used to encrypt or decrypt data The public key
is part of the certificate, which is how the certificate is used to verify data sent
to and received from the server
If a key is public, if (theoretically) everyone knows the public key, how can
it be used for secure communication? The idea is remarkably simple Dataencrypted with the public key can be decrypted only with the private key,which only you know So, anyone can send you data encrypted with the pub-lic key but only you will be able to decrypt it because only you know the pri-vate key Likewise, data encrypted with your private key can be decryptedonly by the public key If only you know the private key, recipients ofencrypted data can be confident that a message or other data has come fromyou and not from someone impersonating you
Digital certificates work on two simple principles, encryption and trust:
1 SSL encrypts the communication between a Web server and a Webclient to ensure that the data exchange has not been altered duringtransmission and to make it more difficult to steal sensitive data if thedata exchange is intercepted Encryption increases the difficulty of deci-phering a captured data stream A message digest created from the con-tents of the data stream serves as a fingerprint, verifying that the datastream hasn’t been accidentally or deliberately altered while in transitbetween the server and the client
2 Digital certificates provide a certain level of assurance, or trust, that theidentities behind a Web server and a Web client are genuine, that is, that
a Web server or client is not being operated by an impostor Depending
on the type of certificate in use, a digital certificate issued by a nized and trusted certificate authority (CA) means that the CA hastaken steps to verify the identity of the organization or entity operating
recog-a Web site As recog-a result, recog-a digitrecog-al certificrecog-ate provides recog-a rerecog-asonrecog-able degree
of certainty that a Web site is in fact operated by the organization orentity that claims to operate it
A certificate contains information about the certificate owner, including thefollowing:
■■ The owner’s email address
■■ The owner’s name
Trang 15■■ How the certificate can be used
■■ How long the certificate is valid
■■ The address of the Web site for which the certificate has been issued
■■ The public key associated with the certificate
■■ A message digest (also known as hash) to use to confirm that the
certifi-cate has not been altered since it was issuedThe certificate also contains the certificate ID of the person or entity thatissued the certificate and that certified (signed) the information provided inthe certificate Accordingly, you have to trust the issuer of the certificate, the
certificate authority (CA) A CA’s certificate is referred to as a root certificate
because it forms the basis, or root, of a tree of trust: if you trust the CA’s root
certificate, you trust the certificates issued and signed by that CA (Certificates
are not valid until they are signed by a CA.) Most browsers come preloadedwith the root certificates of several recognized CAs Figure 23-5 shows the rootcertificates preloaded in Firefox To view this list, start Firefox and selectEdit ➪ Preferences ➪ Advanced, click the Manage Certificates button, andthen click the Authorities tab
As you can see, there are quite a few root certificates You can also importnew certificates, a capability you will need when you create a self-signed cer-tificate (See the section titled “Creating a Self-Signed Certificate.”)
Figure 23-5 Viewing Firefox’s preloaded root certificates.