apache http 2 - documentation.help · .htaccess server side includes (ssi) (public_html) microsoft...

Post on 06-Aug-2020

5 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

ApacheHTTP2.0

GoogleSearch

Apache2.01.32.0Apache

(MPM)

(DSO)

URL

SSL/TLSCGISuexecURLRewriting

How-To/

CGI:.htaccessServerSideIncludes(SSI) (public_html)

MicrosoftWindowsNovellNetWareEBCDIC

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

(FAQ)

1.32.0

Apache

Apache2.0

Apache autoconf libtool Apache1.3APACI Apache2.0

Apache1.3 MPMApache1.3MPMProxy HTTP/1.1<Proxy>

PATH_INFO( )PHP PATH_INFO

SSI PATH_INFO

CacheNegotiatedDocs on offCacheNegotiatedDocs CacheNegotiatedDocson

ErrorDocument

ErrorDocument403"SomeMessage

ErrorDocument403"SomeMessage"

URLAccessConfig ResourceConfig httpd.confIncludeconf/srm.conf Apache

httpd.conf srm.confaccess.conf Include

BindAddress PortPortApache-1.3URL ServerName URLServerName MPMAgentLog RefererLog RefererIgnore

mod_log_agent mod_log_referer mod_log_config CustomLogAddModule ClearModuleList

APIFancyIndexing IndexOptions

FancyIndexingmod_negotiationMultiViews

MultiviewsMatch(2.0.51 )ErrorHeader

Headeralwayssetfoobar

Apache1.3 mod_auth_digestApache1.3 mod_mmap_static mod_file_cache

Apache src

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

Apache2.0API Apache1.3Apache2.0

Apache2.0

ApacheHTTP1.32.0

1.32.0

UnixPOSIXUnix Apache

autoconf libtool Apacheconfigure

Apache mod_echo

UnixApache2.0BeOSOS/2WindowsUnix (MPM) ApachePortableRuntime(APR) API POSIX

ApacheAPI2.0API 1.3/

IPv6ApacheApachePortableRuntimelibrary IPv6Apache IPv6listen Listen

NameVirtualHost,VirtualHostIPv6"Listen[2001:db8::1]:8080")

Apache ServerSideInclude

SSI

vhost

WindowsNTUnicode

WindowsNTApache2.0 utf-8UnicodeWindows2000WindowsXP WindowsNTWindows95,98,ME

Apache2.0 Perl(PCRE) Perl5

mod_ssl

Apache2.0OpenSSL SSL/TLS

mod_dav

Apache2.0 Versioning(DAV)

mod_deflate

Apache2.0

mod_auth_ldap

Apache2.0.41HTTP LDAP

mod_auth_digest

mod_charset_lite

Apache2.0

mod_file_cache

Apache2.0 Apache1.3 mod_mmap_static

mod_headers

Apache2.0 mod_proxy

mod_proxy

proxy HTTP/1.1proxyproxy() proxy_connect,proxy_ftp,proxy_http

mod_negotiation

NOTACCEPTABLEMULTIPLECHOICESForceLanguagePriority

mod_autoindex

Autoindex HTML

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

mod_include

SSI SSImod_include$0..$9

mod_auth_dbm

AuthDBMTypeDBM

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

TheApacheLicense,Version2.0

ApacheLicenseVersion2.0,January2004

http://www.apache.org/licenses/

TERMSANDCONDITIONSFORUSE,REPRODUCTION,ANDDISTRIBUTION

1. Definitions

"License"shallmeanthetermsandconditionsforuse,reproduction,anddistributionasdefinedbySections1through9ofthisdocument.

"Licensor"shallmeanthecopyrightownerorentityauthorizedbythecopyrightownerthatisgrantingtheLicense.

"LegalEntity"shallmeantheunionoftheactingentityandallotherentitiesthatcontrol,arecontrolledby,orareundercommoncontrolwiththatentity.Forthepurposesofthisdefinition,"control"means(i)thepower,directorindirect,tocausethedirectionormanagementofsuchentity,whetherbycontractorotherwise,or(ii)ownershipoffiftypercent(50%)ormoreoftheoutstandingshares,or(iii)beneficialownershipofsuchentity.

"You"(or"Your")shallmeananindividualorLegalEntityexercisingpermissionsgrantedbythisLicense.

"Source"formshallmeanthepreferredformformakingmodifications,includingbutnotlimitedtosoftwaresourcecode,documentationsource,andconfigurationfiles.

"Object"formshallmeananyformresultingfrommechanicaltransformationortranslationofaSourceform,includingbutnot

limitedtocompiledobjectcode,generateddocumentation,andconversionstoothermediatypes.

"Work"shallmeantheworkofauthorship,whetherinSourceorObjectform,madeavailableundertheLicense,asindicatedbyacopyrightnoticethatisincludedinorattachedtothework(anexampleisprovidedintheAppendixbelow).

"DerivativeWorks"shallmeananywork,whetherinSourceorObjectform,thatisbasedon(orderivedfrom)theWorkandforwhichtheeditorialrevisions,annotations,elaborations,orothermodificationsrepresent,asawhole,anoriginalworkofauthorship.ForthepurposesofthisLicense,DerivativeWorksshallnotincludeworksthatremainseparablefrom,ormerelylink(orbindbyname)totheinterfacesof,theWorkandDerivativeWorksthereof.

"Contribution"shallmeananyworkofauthorship,includingtheoriginalversionoftheWorkandanymodificationsoradditionstothatWorkorDerivativeWorksthereof,thatisintentionallysubmittedtoLicensorforinclusionintheWorkbythecopyrightownerorbyanindividualorLegalEntityauthorizedtosubmitonbehalfofthecopyrightowner.Forthepurposesofthisdefinition,"submitted"meansanyformofelectronic,verbal,orwrittencommunicationsenttotheLicensororitsrepresentatives,includingbutnotlimitedtocommunicationonelectronicmailinglists,sourcecodecontrolsystems,andissuetrackingsystemsthataremanagedby,oronbehalfof,theLicensorforthepurposeofdiscussingandimprovingtheWork,butexcludingcommunicationthatisconspicuouslymarkedorotherwisedesignatedinwritingbythecopyrightowneras"NotaContribution."

"Contributor"shallmeanLicensorandanyindividualorLegalEntityonbehalfofwhomaContributionhasbeenreceivedby

LicensorandsubsequentlyincorporatedwithintheWork.

2. GrantofCopyrightLicense.SubjecttothetermsandconditionsofthisLicense,eachContributorherebygrantstoYouaperpetual,worldwide,non-exclusive,no-charge,royalty-free,irrevocablecopyrightlicensetoreproduce,prepareDerivativeWorksof,publiclydisplay,publiclyperform,sublicense,anddistributetheWorkandsuchDerivativeWorksinSourceorObjectform.

3. GrantofPatentLicense.SubjecttothetermsandconditionsofthisLicense,eachContributorherebygrantstoYouaperpetual,worldwide,non-exclusive,no-charge,royalty-free,irrevocable(exceptasstatedinthissection)patentlicensetomake,havemade,use,offertosell,sell,import,andotherwisetransfertheWork,wheresuchlicenseappliesonlytothosepatentclaimslicensablebysuchContributorthatarenecessarilyinfringedbytheirContribution(s)aloneorbycombinationoftheirContribution(s)withtheWorktowhichsuchContribution(s)wassubmitted.IfYouinstitutepatentlitigationagainstanyentity(includingacross-claimorcounterclaiminalawsuit)allegingthattheWorkoraContributionincorporatedwithintheWorkconstitutesdirectorcontributorypatentinfringement,thenanypatentlicensesgrantedtoYouunderthisLicenseforthatWorkshallterminateasofthedatesuchlitigationisfiled.

4. Redistribution.YoumayreproduceanddistributecopiesoftheWorkorDerivativeWorksthereofinanymedium,withorwithoutmodifications,andinSourceorObjectform,providedthatYoumeetthefollowingconditions:

a. YoumustgiveanyotherrecipientsoftheWorkorDerivativeWorksacopyofthisLicense;and

b. YoumustcauseanymodifiedfilestocarryprominentnoticesstatingthatYouchangedthefiles;and

c. Youmustretain,intheSourceformofanyDerivativeWorksthatYoudistribute,allcopyright,patent,trademark,andattributionnoticesfromtheSourceformoftheWork,excludingthosenoticesthatdonotpertaintoanypartoftheDerivativeWorks;and

d. IftheWorkincludesa"NOTICE"textfileaspartofitsdistribution,thenanyDerivativeWorksthatYoudistributemustincludeareadablecopyoftheattributionnoticescontainedwithinsuchNOTICEfile,excludingthosenoticesthatdonotpertaintoanypartoftheDerivativeWorks,inatleastoneofthefollowingplaces:withinaNOTICEtextfiledistributedaspartoftheDerivativeWorks;withintheSourceformordocumentation,ifprovidedalongwiththeDerivativeWorks;or,withinadisplaygeneratedbytheDerivativeWorks,ifandwhereversuchthird-partynoticesnormallyappear.ThecontentsoftheNOTICEfileareforinformationalpurposesonlyanddonotmodifytheLicense.YoumayaddYourownattributionnoticeswithinDerivativeWorksthatYoudistribute,alongsideorasanaddendumtotheNOTICEtextfromtheWork,providedthatsuchadditionalattributionnoticescannotbeconstruedasmodifyingtheLicense.

YoumayaddYourowncopyrightstatementtoYourmodificationsandmayprovideadditionalordifferentlicensetermsandconditionsforuse,reproduction,ordistributionofYourmodifications,orforanysuchDerivativeWorksasawhole,providedYouruse,reproduction,anddistributionoftheWorkotherwisecomplieswiththeconditionsstatedinthisLicense.

5. SubmissionofContributions.UnlessYouexplicitlystateotherwise,anyContributionintentionallysubmittedforinclusionintheWorkbyYoutotheLicensorshallbeunderthetermsandconditionsofthisLicense,withoutanyadditionaltermsorconditions.Notwithstandingtheabove,nothinghereinshall

supersedeormodifythetermsofanyseparatelicenseagreementyoumayhaveexecutedwithLicensorregardingsuchContributions.

6. Trademarks.ThisLicensedoesnotgrantpermissiontousethetradenames,trademarks,servicemarks,orproductnamesoftheLicensor,exceptasrequiredforreasonableandcustomaryuseindescribingtheoriginoftheWorkandreproducingthecontentoftheNOTICEfile.

7. DisclaimerofWarranty.Unlessrequiredbyapplicablelaworagreedtoinwriting,LicensorprovidestheWork(andeachContributorprovidesitsContributions)onan"ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied,including,withoutlimitation,anywarrantiesorconditionsofTITLE,NON-INFRINGEMENT,MERCHANTABILITY,orFITNESSFORAPARTICULARPURPOSE.YouaresolelyresponsiblefordeterminingtheappropriatenessofusingorredistributingtheWorkandassumeanyrisksassociatedwithYourexerciseofpermissionsunderthisLicense.

8. LimitationofLiability.Innoeventandundernolegaltheory,whetherintort(includingnegligence),contract,orotherwise,unlessrequiredbyapplicablelaw(suchasdeliberateandgrosslynegligentacts)oragreedtoinwriting,shallanyContributorbeliabletoYoufordamages,includinganydirect,indirect,special,incidental,orconsequentialdamagesofanycharacterarisingasaresultofthisLicenseoroutoftheuseorinabilitytousetheWork(includingbutnotlimitedtodamagesforlossofgoodwill,workstoppage,computerfailureormalfunction,oranyandallothercommercialdamagesorlosses),evenifsuchContributorhasbeenadvisedofthepossibilityofsuchdamages.

9. AcceptingWarrantyorAdditionalLiability.WhileredistributingtheWorkorDerivativeWorksthereof,Youmaychoosetooffer,andchargeafeefor,acceptanceofsupport,warranty,indemnity,

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

orotherliabilityobligationsand/orrightsconsistentwiththisLicense.However,inacceptingsuchobligations,YoumayactonlyonYourownbehalfandonYoursoleresponsibility,notonbehalfofanyotherContributor,andonlyifYouagreetoindemnify,defend,andholdeachContributorharmlessforanyliabilityincurredby,orclaimsassertedagainst,suchContributorbyreasonofyouracceptinganysuchwarrantyoradditionalliability.

ENDOFTERMSANDCONDITIONS

APPENDIX:HowtoapplytheApacheLicensetoyourwork.

ToapplytheApacheLicensetoyourwork,attachthefollowingboilerplatenotice,withthefieldsenclosedbybrackets"[]"replacedwithyourownidentifyinginformation.(Don'tincludethebrackets!)Thetextshouldbeenclosedintheappropriatecommentsyntaxforthefileformat.Wealsorecommendthatafileorclassnameanddescriptionofpurposebeincludedonthesame"printedpage"asthecopyrightnoticeforeasieridentificationwithinthird-partyarchives.

Copyright[yyyy][nameofcopyrightowner]

LicensedundertheApacheLicense,Version2.0(the"License");

youmaynotusethisfileexceptincompliancewiththeLicense.

YoumayobtainacopyoftheLicenseat

http://www.apache.org/licenses/LICENSE-2.0

Unlessrequiredbyapplicablelaworagreedtoinwriting,software

distributedundertheLicenseisdistributedonan"ASIS"BASIS,

WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.

SeetheLicenseforthespecificlanguagegoverningpermissionsand

limitationsundertheLicense.

Modules|Directives|FAQ|Glossary|Sitemap

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

UnixUnix ApacheWindowsApache

Apache2.0Apache1.3 OpenSource libtool autoconf

(2.0.502.0.51)

ApacheApache

()

$lynxhttp://httpd.apache.org/download.cgi

$gzip-dhttpd-2_0_NN.tar.gz

$tarxvfhttpd-2_0_NN.tar

$./configure--prefix=PREFIX

$make

$makeinstall

$viPREFIX/conf/httpd.conf

$PREFIX/bin/apachectlstart

NN PREFIX/usr/local/apache2

ApacheHTTPD

Apache:

50MB Apache10MB

ANSI-CANSI-C FreeSoftwareFoundation(FSF) GNUCcompiler(GCC)(2.7.2)GCC PATH make

HTTP xntpd NTPNTPcomp.protocols.time.ntp NTP

Perl5[] apxs dbmmanage PerlPerl 5(5.003)"configure" ApachePerl4Perl5) --with-perl()./configure

Apache ApacheHTTP

ApacheHTTP

ApacheHTTPDtarball tar:

$gzip-dhttpd-2_0_NN.tar.gz

$tarxvfhttpd-2_0_NN.tar

Apache autoconflibtool buildconf

./configure

Apache --prefixApache

Apache Apacheenable-module moduleenable-module=shared (DSO)disable-module Base

configure configure

/sw/pkg/apache

DSO :

$CC="pgcc"CFLAGS="-O2"\

./configure--prefix=/sw/pkg/apache\

--enable-rewrite=shared\

--enable-speling=shared

configure Makefile

configure configure

Apache :

$make

PentiumIII/Linux2.2 3

PREFIX( --prefix)

$makeinstall

PREFIX/conf/ ApacheHTTP

$viPREFIX/conf/httpd.conf

docs/manual/Apache http://httpd.apache.org/docs/2.0/

ApacheHTTP :

$PREFIX/bin/apachectlstart

URLhttp://localhost/ PREFIX/htdocs/ :

$PREFIX/bin/apachectlstop

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

API

(2.0.552.0.57) configure API (2.0.41

$./config.nice

$make

$makeinstall

$PREFIX/bin/apachectlstop

$PREFIX/bin/apachectlstart

Apache

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

WindowsApache WindowsNT,2000,XPWindows9x,ME

Unix httpd

httpdapachectl

Apache

Listen80(1024) listen

httpd apachectlapachectl httpd HTTPD httpd

httpd httpd.conf

/usr/local/apache2/bin/apachectl-f

/usr/local/apache2/conf/httpd.conf

Apache ErrorLog

...

rootApache

ApacheFAQ

apachectl

root

apachectlSysVinit httpd init

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

httpd apachectl

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

Unix ApacheWindows9x,ME Apache

httpdapachectl

Apache httpd pidUSR1

:

kill-TERM`cat/usr/local/apache2/logs/httpd.pid`

httpd2 -khttpd apachectl apachectl

httpd :

tail-f/usr/local/apache2/logs/error_log

ServerRootPidFile

:TERMapachectl-kstop

TERM stopkill

:USR1apachectl-kgraceful

USR1 graceful

USR1 (WINCH)

MPM

mod_status USR1

status

USR1

(httpd) httpd)

:HUPapachectl-krestart

HUP restart TERMkill

mod_status HUP

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

:

Apache1.2b9 (:

ScoreBoardFile (HUP) "longlostchildcamehome!"(USR1) (HUP)

HTTP(KeepAlive)KeepAlive

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

ApacheHTTP

mod_mime <IfDefine>

Include

TypesConfig

Apache Include

MIME

Apache11 "\"

"#"

apachectlconfigtest

mod_so <IfModule>

LoadModule

Apache LoadModule Apache

-l

<Directory>

<DirectoryMatch>

<Files>

<FilesMatch>

<Location>

<LocationMatch>

<VirtualHost>

<FilesMatch>,<Location>,<LocationMatch>

Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

.htaccess

AccessFileName

AllowOverride

Apache .htaccess

.htaccess

.htaccess .htaccess

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

URL .htaccess

core

mod_proxy

<Directory>

<DirectoryMatch>

<Files>

<FilesMatch>

<IfDefine>

<IfModule>

<Location>

<LocationMatch>

<Proxy>

<ProxyMatch>

<VirtualHost>

<IfDefine> <IfModule>

<IfDefine>httpd httpd-DClosedForNow:

<IfDefineClosedForNow>

Redirect/http://otherserver.example.com/

</IfDefine>

<IfModule> LoadModule

mod_mime_magic MimeMagicFiles

<IfModulemod_mime_magic.c>

MimeMagicFileconf/magic

</IfModule>

<IfDefine><IfModule>"!"

ApacheUnix/usr/local/apache2Windows "c:/Program

Files/ApacheGroup/Apache2"(ApacheWindows)UnixApache/usr/local/apache2/htdocs/dir/

<Directory><Files> <Directory>.htaccess /var/web/dir1

<Directory/var/web/dir1>

Options+Indexes

</Directory>

<Files> private.html

<Filesprivate.html>

Orderallow,deny

Denyfromall

</Files>

<Files><Directory>/var/web/dir1/private.html,/var/web/dir1/subdir2/private.html,/var/web/dir1/subdir3/private.html/var/web/dir1/private.html

<Directory/var/web/dir1>

<Filesprivate.html>

Orderallow,deny

Denyfromall

</Files>

</Directory>

<Location>/privateURLhttp://yoursite.example.com/private,http://yoursite.example.com/private123,http://yoursite.example.com/private/dir/file.html

/private

<Location/private>

OrderAllow,Deny

Denyfromall

</Location>

<Location>URL mod_statusApacheserver-status

<Location/server-status>

SetHandlerserver-status

</Location>

<Directory>,<Files>,<Location>Cshell"*""?"1"[

(regex) <DirectoryMatch>,<FilesMatch>,<LocationMatch>perl regex

regex

<Directory/home/*/public_html>

OptionsIndexes

</Directory>

regex

<FilesMatch\.(?i:gif|jpe?g|png)$>

Orderallow,deny

Denyfromall

</FilesMatch>

<Directory> <Files>()<Location>

<Location>(URL)

<Location/dir/>

Orderallow,deny

Denyfromall

</Location>

http://yoursite.example.com/dir/?http://yoursite.example.com/DIR/(Options)

<Location/>URL

<VirtualHost>

<Proxy> <ProxyMatch>URL mod_proxycnn.com

<Proxyhttp://cnn.com/*>

Orderallow,deny

Denyfromall

</Proxy>

?

Context <Directory> <DirectoryMatch>,<Files>,<FilesMatch>,<Location>,<LocationMatch>,<Proxy>,<ProxyMatch>

AllowOverride<Directory>FollowSymLinks SymLinksIfOwnerMatch Options

<Directory> .htaccessOptions <Files> <FilesMatch>

:

1. <Directory>() .htaccess( .htaccess<Directory>)

2. <DirectoryMatch>( <Directory~>

3. <Files> <FilesMatch>

4. <Location> <LocationMatch>

<Directory><Directory/var/web/dir1> <Directory

/var/web/dir/subdir> <Directory>Include Include

<VirtualHost>

(URL Alias<Location>/<LocationMatch>

A>B>C>D>E

<Location/>

E

</Location>

<Filesf.html>

D

</Files>

<VirtualHost*>

<Directory/a/b>

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

B

</Directory>

</VirtualHost>

<DirectoryMatch"^.*b$">

C

</DirectoryMatch>

<Directory/a/b>

A

</Directory>

<Directory> <Location>

<Location/>

Orderdeny,allow

Allowfromall

</Location>

#Woops!This<Directory>sectionwillhavenoeffect

<Directory/>

Orderallow,deny

Allowfromall

Denyfrombadguy.example.com

</Directory>

core

ID

ServerName

ServerAdmin

ServerSignature

ServerTokens

UseCanonicalName

ServerAdmin ServerTokensServerHTTP

ServerName UseCanonicalNameURL Apache

CoreDumpDirectory

DocumentRoot

ErrorLog

LockFile

PidFile

ScoreBoardFile

ServerRoot

Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

LimitRequestBody

LimitRequestFields

LimitRequestFieldsize

LimitRequestLine

RLimitCPU

RLimitMEM

RLimitNPROC

ThreadStackSize

LimitRequest*Apache

RLimit*Apache fork

ThreadStackSizeNetware

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

Apache uid

ErrorLog

LogLevel

ErrorLog

(unix error_logWindowsOS/2Unix syslog

[WedOct1114:32:522000][error][client127.0.0.1]client

deniedbyserverconfiguration:

/export/home/live/ap/htdocs/test

CGI

tail-ferror_log

mod_log_config

mod_setenvif

CustomLog

LogFormat

SetEnvIf

Apachehttpdmod_log_config, mod_log_agent,TransferLog

Cprintf(1)

CommonLogFormat

LogFormat"%h%l%u%t\"%r\"%>s%b"common

CustomLoglogs/access_logcommon

common "\t"

CustomLog

CommonLogFormat(CLF)

127.0.0.1-frank[10/Oct/2000:13:55:36-0700]"GET

/apache_pb.gifHTTP/1.0"2002326

127.0.0.1(%h)

() IP

-(%l) IdentityCheck On

frank(%u)HTTP IDCGI401

[10/Oct/2000:13:55:36-0700](%t):

[day/month/year:hour:minute:secondzone]

day=2*digit

month=3*letter

year=4*digit

hour=2*digit

minute=2*digit

second=2*digit

zone=(`+'|`-')4*digit

%{format}t

"GET/apache_pb.gifHTTP/1.0"(\"%r\") HTTP/1.0 "%r"

200(%>s) (2))

2326(%b)

CombinedLogFormatCombinedLogFormat

LogFormat"%h%l%u%t\"%r\"%>s%b\"%{Referer}i\"\"%{User-

agent}i\""combined

CustomLoglog/access_logcombined

CommonLogFormat HTTP :

127.0.0.1-frank[10/Oct/2000:13:55:36-0700]"GET

/apache_pb.gifHTTP/1.0"2002326

"http://www.example.com/start.html""Mozilla/4.08[en](Win98;

I;Nav)"

:

"http://www.example.com/start.html"(\"%{Referer}i\")

"Referer"()HTTP )

"Mozilla/4.08[en](Win98;I;Nav)"(\"%{User-agent}i\")

User-AgentHTTP

CustomLogReferLog AgentLog

LogFormat"%h%l%u%t\"%r\"%>s%b"common

CustomLoglogs/access_logcommon

CustomLoglogs/referer_log"%{Referer}i->%U"

CustomLoglogs/agent_log"%{User-agent}i"

LogFormat

:

#Markrequestsfromtheloop-backinterface

SetEnvIfRemote_Addr"127\.0\.0\.1"dontlog

#Markrequestsfortherobots.txtfile

SetEnvIfRequest_URI"^/robots\.txt$"dontlog

#Logwhatremains

CustomLoglogs/access_logcommonenv=!dontlog

SetEnvIfAccept-Language"en"english

CustomLoglogs/english_logcommonenv=english

CustomLoglogs/non_english_logcommonenv=!english

10,000open open

open

mvaccess_logaccess_log.old

mverror_logerror_log.old

apachectlgraceful

sleep600

gzipaccess_log.olderror_log.old

Apachehttpd ( )

Apachehttpd ID

ApacheHTTP

CustomLog"|/usr/local/apache/bin/rotatelogs

/var/log/access_log86400"common

cronolog

>CustomLog ErrorLog <VirtualHost>

LogFormat"%v%l%u%t\"%r\"%>s%b"comonvhost

CustomLoglogs/access_logcomonvhost

%v

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

mod_cgi

mod_rewrite

PidFile

RewriteLog

RewriteLogLevel

ScriptLog

ScriptLogBuffer

ScriptLogLength

PIDApachehttpdID logs/httpd.pidPidFile ID

ScriptLog CGI

mod_rewrite RewriteLogLevel

URL

ApacheURL

mod_alias

mod_proxy

mod_rewrite

mod_userdir

mod_speling

mod_vhost_alias

Alias

AliasMatch

CheckSpelling

DocumentRoot

ErrorDocument

Options

ProxyPass

ProxyPassReverse

Redirect

RedirectMatch

RewriteCond

RewriteMatch

ScriptAlias

ScriptAliasMatch

UserDir

DocumentRoot

ApacheURL-Path(URL DocumentRoot

Apache IP

DocumentRoot

DocumentRootDocumentRoot SymLinksIfOwnerMatch

Alias

Alias/docs/var/web

URL http://www.example.com/docs/dir/file.html

/var/web/dir/file.html ScriptAlias CGI

AliasMatch ScriptAliasMatch

ScriptAliasMatch^/~([a-zA-Z0-9]+)/cgi-bin/(.+)/home/$1/cgi-

bin/$2

http://example.com/~user/cgi-bin/script.cgi/home/user/cgi-bin/script.cgi CGI

Unix user ~user/ mod_userdir

http://www.example.com/~user/file.html

URL /home/user/public_html/file.html

/home/user/ /etc/passwd

Userdir /etc/passwd

"~"( %7e)

http://www.example.com/upages/user/file.html/home/user/public_html/file.html:

AliasMatch^/upages/([a-zA-Z0-9]+)/?(.*)

/home/$1/public_html/$2

URL

Apache DocumentRoot /foo/ /bar/

Redirectpermanent/foo/http://www.example.com/bar/

/foo/URL-Path www.example.com /bar/

/foo/

Apache RedirectMatch

RedirectMatchpermanent^/$

http://www.example.com/startpage.html

:

RedirectMatchtemp.*

http://othersite.example.com/startpage.html

ApacheURL

/foo/ internal.example.com /bar/

ProxyPass/foo/http://internal.example.com/bar/

ProxyPassReverse/foo/http://internal.example.com/bar/

ProxyPass ProxyPassReverseinternal.example.com

internal.example.cominternal.example.com

mod_rewrite () mod_rewrite

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

FileNotFound

URL

"FileNotFound" HTMLURLmod_speling() (:spelling)

Found"

mod_speling URLunixmod_speling

ApacheHTTP404(filenotfound)ErrorDocument

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>MiscellaneousDocumentation

SecurityTips

Somehintsandtipsonsecurityissuesinsettingupawebserver.Someofthesuggestionswillbegeneral,othersspecifictoApache.

KeepuptoDate

TheApacheHTTPServerhasagoodrecordforsecurityandadevelopercommunityhighlyconcernedaboutsecurityissues.Butitisinevitablethatsomeproblems--smallorlarge--willbediscoveredinsoftwareafteritisreleased.Forthisreason,itiscrucialtokeepawareofupdatestothesoftware.IfyouhaveobtainedyourversionoftheHTTPServerdirectlyfromApache,wehighlyrecommendyousubscribetotheApacheHTTPServerAnnouncementsListwhereyoucankeepinformedofnewreleasesandsecurityupdates.Similarservicesareavailablefrommostthird-partydistributorsofApachesoftware.

Ofcourse,mosttimesthatawebserveriscompromised,itisnotbecauseofproblemsintheHTTPServercode.Rather,itcomesfromproblemsinadd-oncode,CGIscripts,ortheunderlyingOperatingSystem.Youmustthereforestayawareofproblemsandupdateswithallthesoftwareonyoursystem.

PermissionsonServerRootDirectories

Intypicaloperation,Apacheisstartedbytherootuser,anditswitchestotheuserdefinedbytheUserdirectivetoservehits.Asisthecasewithanycommandthatrootexecutes,youmusttakecarethatitisprotectedfrommodificationbynon-rootusers.Notonlymustthefilesthemselvesbewriteableonlybyroot,butsomustthedirectories,andparentsofalldirectories.Forexample,ifyouchoosetoplaceServerRootin/usr/local/apachethenitissuggestedthatyoucreatethatdirectoryasroot,withcommandslikethese:

mkdir/usr/local/apache

cd/usr/local/apache

mkdirbinconflogs

chown0.binconflogs

chgrp0.binconflogs

chmod755.binconflogs

Itisassumedthat/,/usr,and/usr/localareonlymodifiablebyroot.Whenyouinstallthehttpdexecutable,youshouldensurethatitissimilarlyprotected:

cphttpd/usr/local/apache/bin

chown0/usr/local/apache/bin/httpd

chgrp0/usr/local/apache/bin/httpd

chmod511/usr/local/apache/bin/httpd

Youcancreateanhtdocssubdirectorywhichismodifiablebyotherusers--sincerootneverexecutesanyfilesoutofthere,andshouldn'tbecreatingfilesinthere.

Ifyouallownon-rootuserstomodifyanyfilesthatrooteitherexecutesorwritesonthenyouopenyoursystemtorootcompromises.Forexample,someonecouldreplacethehttpdbinarysothatthenexttimeyoustartit,itwillexecutesomearbitrarycode.Ifthelogsdirectoryiswriteable(byanon-rootuser),someonecouldreplacealogfilewithasymlinktosome

othersystemfile,andthenrootmightoverwritethatfilewitharbitrarydata.Ifthelogfilesthemselvesarewriteable(byanon-rootuser),thensomeonemaybeabletooverwritethelogitselfwithbogusdata.

ServerSideIncludes

ServerSideIncludes(SSI)presentaserveradministratorwithseveralpotentialsecurityrisks.

Thefirstriskistheincreasedloadontheserver.AllSSI-enabledfileshavetobeparsedbyApache,whetherornotthereareanySSIdirectivesincludedwithinthefiles.Whilethisloadincreaseisminor,inasharedserverenvironmentitcanbecomesignificant.

SSIfilesalsoposethesamerisksthatareassociatedwithCGIscriptsingeneral.Usingtheexeccmdelement,SSI-enabledfilescanexecuteanyCGIscriptorprogramunderthepermissionsoftheuserandgroupApacherunsas,asconfiguredinhttpd.conf.

TherearewaystoenhancethesecurityofSSIfileswhilestilltakingadvantageofthebenefitstheyprovide.

ToisolatethedamageawaywardSSIfilecancause,aserveradministratorcanenablesuexecasdescribedintheCGIinGeneralsection.

EnablingSSIforfileswith.htmlor.htmextensionscanbedangerous.Thisisespeciallytrueinashared,orhightraffic,serverenvironment.SSI-enabledfilesshouldhaveaseparateextension,suchastheconventional.shtml.Thishelpskeepserverloadataminimumandallowsforeasiermanagementofrisk.

AnothersolutionistodisabletheabilitytorunscriptsandprogramsfromSSIpages.TodothisreplaceIncludeswithIncludesNOEXECintheOptionsdirective.Notethatusersmaystilluse<--#includevirtual="..."-->toexecuteCGIscriptsifthesescriptsareindirectoriesdesignatedbyaScriptAliasdirective.

CGIinGeneral

Firstofall,youalwayshavetorememberthatyoumusttrustthewritersoftheCGIscripts/programsoryourabilitytospotpotentialsecurityholesinCGI,whethertheyweredeliberateoraccidental.CGIscriptscanrunessentiallyarbitrarycommandsonyoursystemwiththepermissionsofthewebserveruserandcanthereforebeextremelydangerousiftheyarenotcarefullychecked.

AlltheCGIscriptswillrunasthesameuser,sotheyhavepotentialtoconflict(accidentallyordeliberately)withotherscriptse.g.UserAhatesUserB,sohewritesascripttotrashUserB'sCGIdatabase.OneprogramwhichcanbeusedtoallowscriptstorunasdifferentusersissuEXECwhichisincludedwithApacheasof1.2andiscalledfromspecialhooksintheApacheservercode.AnotherpopularwayofdoingthisiswithCGIWrap.

NonScriptAliasedCGI

AllowinguserstoexecuteCGIscriptsinanydirectoryshouldonlybeconsideredif:

Youtrustyourusersnottowritescriptswhichwilldeliberatelyoraccidentallyexposeyoursystemtoanattack.Youconsidersecurityatyoursitetobesofeebleinotherareas,astomakeonemorepotentialholeirrelevant.Youhavenousers,andnobodyevervisitsyourserver.

ScriptAliasedCGI

LimitingCGItospecialdirectoriesgivestheadmincontroloverwhatgoesintothosedirectories.ThisisinevitablymoresecurethannonscriptaliasedCGI,butonlyifuserswithwriteaccesstothedirectoriesaretrustedortheadminiswillingtotesteachnewCGIscript/programforpotentialsecurityholes.

MostsiteschoosethisoptionoverthenonscriptaliasedCGIapproach.

Othersourcesofdynamiccontent

Embeddedscriptingoptionswhichrunaspartoftheserveritself,suchasmod_php,mod_perl,mod_tcl,andmod_python,runundertheidentityoftheserveritself(seetheUserdirective),andthereforescriptsexecutedbytheseenginespotentiallycanaccessanythingtheserverusercan.Somescriptingenginesmayproviderestrictions,butitisbettertobesafeandassumenot.

ProtectingSystemSettings

Torunareallytightship,you'llwanttostopusersfromsettingup.htaccessfileswhichcanoverridesecurityfeaturesyou'veconfigured.Here'sonewaytodoit.

Intheserverconfigurationfile,put

<Directory/>

AllowOverrideNone

</Directory>

Thispreventstheuseof.htaccessfilesinalldirectoriesapartfromthosespecificallyenabled.

ProtectServerFilesbyDefault

OneaspectofApachewhichisoccasionallymisunderstoodisthefeatureofdefaultaccess.Thatis,unlessyoutakestepstochangeit,iftheservercanfinditswaytoafilethroughnormalURLmappingrules,itcanserveittoclients.

Forinstance,considerthefollowingexample:

#cd/;ln-s/public_html

Accessinghttp://localhost/~root/

Thiswouldallowclientstowalkthroughtheentirefilesystem.Toworkaroundthis,addthefollowingblocktoyourserver'sconfiguration:

<Directory/>

OrderDeny,Allow

Denyfromall

</Directory>

Thiswillforbiddefaultaccesstofilesystemlocations.AddappropriateDirectoryblockstoallowaccessonlyinthoseareasyouwish.Forexample,

<Directory/usr/users/*/public_html>

OrderDeny,Allow

Allowfromall

</Directory>

<Directory/usr/local/httpd>

OrderDeny,Allow

Allowfromall

</Directory>

PayparticularattentiontotheinteractionsofLocationandDirectorydirectives;forinstance,evenif<Directory/>deniesaccess,a<Location/>directivemightoverturnit.

AlsobewaryofplayinggameswiththeUserDirdirective;setting

ittosomethinglike./wouldhavethesameeffect,forroot,asthefirstexampleabove.IfyouareusingApache1.3orabove,westronglyrecommendthatyouincludethefollowinglineinyourserverconfigurationfiles:

UserDirdisabledroot

Copyright2013TheApacheSoftwareFoundation.

WatchingYourLogs

Tokeepup-to-datewithwhatisactuallygoingonagainstyourserveryouhavetochecktheLogFiles.Eventhoughthelogfilesonlyreportswhathasalreadyhappened,theywillgiveyousomeunderstandingofwhatattacksisthrownagainsttheserverandallowyoutocheckifthenecessarylevelofsecurityispresent.

Acoupleofexamples:

grep-c"/jsp/source.jsp?/jsp//jsp/source.jsp??"access_log

grep"clientdenied"error_log|tail-n10

ThefirstexamplewilllistthenumberofattackstryingtoexploittheApacheTomcatSource.JSPMalformedRequestInformationDisclosureVulnerability,thesecondexamplewilllistthetenlastdeniedclients,forexample:

[ThuJul1117:18:392002][error][clientfoo.bar.com]client

deniedbyserverconfiguration:

/usr/local/apache/htdocs/.htpasswd

Asyoucansee,thelogfilesonlyreportwhatalreadyhashappened,soiftheclienthadbeenabletoaccessthe.htpasswdfileyouwouldhaveseensomethingsimilarto:

foo.bar.com--[12/Jul/2002:01:59:13+0200]"GET/.htpasswd

HTTP/1.1"

inyourAccessLog.Thismeansyouprobablycommentedoutthefollowinginyourserverconfigurationfile:

<Files~"^\.ht">

Orderallow,deny

Denyfromall

</Files>

LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

(DSO)

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

ApacheHTTP SharedObject)(DSO) DSO

DSO

mod_so LoadModule

ApacheDSO mod_so.ccore.cDSO Apacheenable-module=shared DSODSODSO httpd.conf mod_so

Apache()DSOApache DSO :ApacheApache CDSODSO Apache

Apache2.0DSO :

1. Apache mod_foo.cDSO mod_foo.so:

$./configure--prefix=/path/to/install--enable-

foo=shared

$makeinstall

2. Apache mod_foo.cDSO mod_foo.so:

$./configure--add-

module=module_type:/path/to/3rdparty/mod_foo.c--enable-

foo=shared

$makeinstall

3. Apache:

$./configure--enable-so

$makeinstall

4. Apache mod_foo.c apxs Apache:

$cd/path/to/3rdparty

$apxs-cmod_foo.c

$apxs-i-a-nfoomod_foo.la

httpd.conf LoadModule

UnixOS (DSO)/

: ld.so

DSO DSO DSO libfoo.so libfoo.so.1.2

( /usr/lib) /usr/lib -R libfoo.so ()DSO

DSO (DSO))

DSO DSO (dlopen() DSO) DSO(

DSOAPI

DSO :DSO (

DSO

1998DSO :Perl5(XSDnaLoaderApache

ApacheDSO

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

DSO:

configureApache (SSL[mod_perl,PHP3] Apache

Apache DSO/ apxsApacheapxs-i apachectlrestart

DSO:

Unix 20%(PIC)(positionindependentcode)

DSODSO () DSO DSOApache PIC(dlopen()

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

ApacheHTTP/1.1

mod_negotiation

Accept-Language:fr

Accept-Language:fr;q=1.0,en;q=0.5

Accept:text/html;q=1.0,text/*;q=0.8,image/gif;q=0.6,

image/jpeg;q=0.6,image/*;q=0.5,*/*;q=0.1

ApacheHTTP/1.1'server driven'Language,Accept-Charset,Accept-EncodingApache'transparent' RFC2295RFC2296'featurenegotiation'

URI (RFC2396)Apache HTTP01

Apache

variant

(*.var) variant'Multiviews'

type-map type-map (Apache MIMEtype-map)

AddHandlertype-map.var

variant) foo foo.var

URI:foo

URI:foo.en.html

Content-type:text/html

Content-language:en

URI:foo.fr.de.html

Content-type:text/html;charset=iso-8859-2

Content-language:fr,de

MultiViews "qs"

URI:foo

URI:foo.jpeg

Content-type:image/jpeg;qs=0.8

URI:foo.gif

Content-type:image/gif;qs=0.5

URI:foo.txt

Content-type:text/plain;qs=0.01

qs0.0001.000qs 0.000variant 'qs'variantqs1.0qs variantJPEG ASCII qs variant

mod_negotiation

MultiviewsMultiViews httpd.conf <Directory>

<Files>( AllowOverride) OptionsAll MultiViews

MultiViews: /some/dir/fooMultiViews /some/dir/foo

MultiViews DirectoryIndex

DirectoryIndexindex

index.html index.html3

MultiViews

Apachevariant

1. ApacheServer drivennegotiationApacheApache Apache

2. RFC2295 transparentcontentnegotiation variant 2296'remotevariantselectionalgorithm'

Accept Accept-Language

Accept-Encoding Accept-Charset

Apachevariant() Apache

1. Accept*variant4

2. variant variant variant

1. variant Acceptvariant

2. variant

3. () Accept-Language ()LanguagePriorityvariant

4. (text/html)

5. Accept-Charset varianttext/*

6. ISO-8859-1 variant

7. variant user-agentvariant variant

8. variant

9. variant

3. variant

4. variant ()representation") variantHTMLVary

Apache ApacheAccept

Accept: "image/*""*/*"

Accept:image/*,*/*

"image/"

Accept:text/html,text/plain,image/gif,image/jpeg,*/*

Accept:text/html,text/plain,image/gif,image/jpeg,*/*;

q=0.01

1.0()

Accept:q Apache"*/*"0.01q"type/*"0.02q ("*/*")

Apache2.0

Accept-Language

"MultipleChoices" LanguagePriority

Language en-GB enAcceptableVariants" LanguagePriorityen Apache "fr" "fr"

(CookieURL) mod_negotiationprefer-language

mod_negotiationvariant

ExampleSetEnvIfCookie"language=en"prefer-language=en

SetEnvIfCookie"language=fr"prefer-language=fr

TransparentContentNegotiation

Apachetransparentcontentnegotiation(RFC2295)variant {encoding..}variantvariantAccept-EncodingvariantvariantRVSA/1.0(RFC2296)RVSA/1.0variant5

MIME( html) (gz)

:

foo.en.htmlfoo.html.enfoo.en.html.gz

:

foo.html.en foofoo.html

-

foo.en.html foo foo.htmlfoo.html.en.gz foo

foo.htmlfoo.gzfoo.html.gz

foo.en.html.gz foo foo.htmlfoo.html.gzfoo.gz

foo.gz.html.en foofoo.gzfoo.gz.html

foo.html

foo.html.gz.en foofoo.htmlfoo.html.gz

foo.gz

( foo)

MIME( foo.html) ()

URLHTTP/1.0

HTTP/1.0 () HTTP/1.1

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

AlanJ.Flavell Language2.0

Apache

"500ServerError"

NCSAhttpd1.3/

1. NCSA

2. URL

3. URL

URL /

ApacheCGI :

REDIRECT_HTTP_ACCEPT=*/*,image/gif,image/x-xbitmap,

image/jpeg

REDIRECT_HTTP_USER_AGENT=Mozilla/1.1b2(X11;I;HP-UXA.09.05

9000/712)

REDIRECT_PATH=.:/bin:/usr/local/bin:/etc

REDIRECT_QUERY_STRING=

REDIRECT_REMOTE_ADDR=121.345.78.123

REDIRECT_REMOTE_HOST=ooh.ahhh.com

REDIRECT_SERVER_NAME=crash.bang.edu

REDIRECT_SERVER_PORT=80

REDIRECT_SERVER_SOFTWARE=Apache/0.8.15

REDIRECT_URL=/cgi-bin/buggy.pl

REDIRECT_

REDIRECT_URL REDIRECT_QUERY_STRINGURL(CGI CGI)

AllowOverride .htaccess ErrorDocument

ErrorDocument500/cgi-bin/crash-recover

ErrorDocument500"Sorry,ourscriptcrashed.Ohdear"

ErrorDocument500http://xxx/

ErrorDocument404/Lame_excuses/not_found.html

ErrorDocument401/Subscription/how_to_subscribe.html

ErrorDocument<3-digit-code><action>

action()

1. (")

2. URL

3. URL

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

/SSI URLApache

CGI

HTTP_USER_AGENT REDIRECT_HTTP_USER_AGENT

Apache REDIRECT_URL

URL

ErrorDocumentCGI ErrorDocumentPerl

...

print"Content-type:text/html\n";

printf"Status:%sConditionIntercepted\n",

$ENV{"REDIRECT_STATUS"};

...

404NotFound

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

Apache

DNS

core

mpm_common

<VirtualHost>

Listen

Apache IPApache

Listen Listen listen

808000

Listen80

Listen8000

Listen192.170.2.1:80

Listen192.170.2.5:8000

IPv6

Listen[2001:db8::a00:20ff:fea7:ccea]:80

IPv6

IPv6 APRIPv6

IPv6IPv4IPv6 ApacheIPv6 Apache

IPv4IPv6 IPv4IPv6configure Listen

Listen80

--enable-v4-mappedApache v4-mapped FreeBSD,NetBSD,OpenBSDApache

APR IPv4

Listen0.0.0.0:80

Listen192.170.2.1:80

IPv4IPv6 (IPv4)configure Listen

Listen[::]:80

Listen0.0.0.0:80

--disable-v4-mappedApache disable-v4-mapped FreeBSD,NetBSD,OpenBSD

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

Listen Listenlisten<VirtualHost> <VirtualHost> <VirtualHost>listen

(MPM)

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

ApacheHTTP

ApacheHTTP

Apache2.0

:

Apache Apache1.3POSIX (perchild)

MPMApache MPM

MPM

MPM MPMApache

MPM./configure --with-mpm=NAMEMPM

MPM ./httpd-l

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

MPM

OSMPMMPM

BeOS beos

Netware mpm_netware

OS/2 mpmt_os2

Unix prefork

Windows mpm_winnt

Apache

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

ApacheHTTP

mod_env

mod_rewrite

mod_setenvif

mod_unique_id

BrowserMatch

BrowserMatchNoCase

PassEnv

RewriteRule

SetEnv

SetEnvIf

SetEnvIfNoCase

UnsetEnv

Apache

mod_setenvif referrerHTTPReferer )RewriteRule [E=...]

mod_unique_id

CGIApache CGISSI

CGICGI suexecCGI (:'_')

mod_access

mod_cgi

mod_ext_filter

mod_headers

mod_include

mod_log_config

mod_rewrite

Allow

CustomLog

Deny

ExtFilterDefine

Header

LogFormat

RewriteCond

RewriteRule

CGICGI CGIApache

SSImod_include INCLUDES server-parsed(SSI)

allowfromenv= denyfromenv=

LogFormat %e gif

Header

ExtFilterDefine mod_ext_filterenableenv=

URLRewriteCond %{ENV:...}mod_rewrite ENV:

ApachePassEnv

downgrade-1.0HTTP/1.0 HTTP/1.0

force-no-vary Vary

force-response-1.0HTTP/1.0 HTTP/1.0 HTTP/1.1

gzip-only-text/html1 text/html mod_deflate

no-gzipmod_deflate DEFLATE

nokeepaliveKeepAlive

prefer-languagemod_negotiation (en,ja,x-klingon) variant

redirect-carefully

suppress-error-charsetApache2.0.40

()

httpd.conf

#

#ThefollowingdirectivesmodifynormalHTTPresponsebehavior.

#ThefirstdirectivedisableskeepaliveforNetscape2.xandbrowsersthat

#spoofit.Thereareknownproblemswiththesebrowserimplementations.

#TheseconddirectiveisforMicrosoftInternetExplorer4.0b2

#whichhasabrokenHTTP/1.1implementationanddoesnotproperly

#supportkeepalivewhenitisusedon301or302(redirect)responses.

#

BrowserMatch"Mozilla/2"nokeepalive

BrowserMatch"MSIE4\.0b2;"nokeepalivedowngrade-1.0force-response-1.0

#

#ThefollowingdirectivedisablesHTTP/1.1responsestobrowserswhich

#areinviolationoftheHTTP/1.0specbynotbeingabletogroka

#basic1.1response.

#

BrowserMatch"RealPlayer4\.0"force-response-1.0

BrowserMatch"Java/1\.0"force-response-1.0

BrowserMatch"JDK/1\.0"force-response-1.0

SetEnvIfRequest_URI\.gifimage-request

SetEnvIfRequest_URI\.jpgimage-request

SetEnvIfRequest_URI\.pngimage-request

CustomLoglogs/access_logcommonenv=!image-request

inline

SetEnvIfReferer"^http://www.example.com/"local_referal

#AllowbrowsersthatdonotsendRefererinfo

SetEnvIfReferer"^$"local_referal

<Directory/web/images>

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

OrderDeny,Allow

Denyfromall

Allowfromenv=local_referal

</Directory>

ApacheToday KeepingYourImagesfromAdorningOtherSites

Apache

Apache

mod_actions

mod_asis

mod_cgi

mod_imap

mod_info

mod_mime

mod_negotiation

mod_status

Action

AddHandler

RemoveHandler

SetHandler

Apache

Apache1.1

Action

default-handler:default_handelr()send-as-is:HTTP (mod_asiscgi-script:CGI (mod_cgi)imap-file: (mod_imap)server-info: (mod_info)server-status: (mod_status)type-map:

CGI html footer.plCGI

Actionadd-footer/cgi-bin/footer.pl

AddHandleradd-footer.html

CGI ( PATH_TRANSLATED

HTTP send-as-isHTTPsend-as-is

<Directory/web/htdocs/asis>

SetHandlersend-as-is

</Directory>

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

ApacheAPI

char*handler

(:"-")

Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

mod_deflate

mod_ext_filter

mod_include

AddInputFilter

AddOutputFilter

RemoveInputFilter

RemoveOutputFilter

ExtFilterDefine

ExtFilterOptions

SetInputFilter

SetOutputFilter

Apache() SetOutputFilter,AddInputFilter,AddOutputFilter,RemoveInputFilter,RemoveOutputFilter

ApacheHTTP

INCLUDESmod_includeServer-SideInclude

DEFLATEmod_deflate

mod_ext_filter

suEXEC

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

suEXECApacheWebID IDSSI web

CGI SSIsuEXEC

Apache

1 setuid setgidUNIX

2

3 suEXECsuEXEC ApachesuEXEC

4suEXECApache suEXECsuEXEC suEXEC

?!

suEXEC

suEXEC

suEXECApacheweb setuid"wrapper"HTTPwrapper Apachewrapper

wrapper

1. wrapper?

wrapper

2. wrapper?

wrapper ApacheWebsuEXEC

3. wrapper ?

wrapper? (Apache)

4. CGI,SSI?

CGI,SSI'/' '..'?-with-suexec-docroot=DIR)

5. ?

?

6. ?

?

7. ?

suEXEC rootCGI/SSI

8. IDID ?

ID CGI/SSIID

9. ?

suEXEC'root'CGI/SSI

10. IDID ?

ID CGI/SSI

11. wrapper?

setuidsetgid

12. CGI/SSI (changedirectory)?

13. Apache?

suEXEC?(suEXEC)

14. ?

15. CGI/SSI?

16. CGI/SSI

CGI/SSI

17. CGI/SSIsetuidsetgid ?

UID/GID

18. / /?

?

19. ?

suEXEC ()

20. CGI/SSIexec?

suEXEC

suEXECwrapper

suEXEC

suEXEC

suEXEC

--enable-suexec

suEXECenable-suexec --with-suexec-xxxxx

--with-suexec-bin=PATH

suexec bin=/usr/sbin/suexec

--with-suexec-caller=UID

Apache suexec

--with-suexec-userdir=DIR

suEXEC ("*") UserdirUserDir

--with-suexec-docroot=DIR

ApachesuEXEC (UserDir"/htdocs" "--datadir=/home/apachewrapper"/home/apache/htdocs"

--with-suexec-uidmin=UID

suEXECUID 500100

--with-suexec-gidmin=GID

suEXECGID 100

--with-suexec-logfile=FILE

suEXEC ()logfiledir)

--with-suexec-safepath=PATH

CGIPATH "/usr/local/bin:/usr/bin:/bin"

suEXECwrapper--enable-suexecsuEXEC "make"(Apache) makeinstall"/usr/local/apache/sbin/suexec" rootwrapperID

suEXEC --with-suexec-callerconfiguresuEXEC

Userwww

Groupwebgroup

suexec"/usr/local/apache2/sbin/suexec"

chgrpwebgroup/usr/local/apache2/bin/suexec

chmod4750/usr/local/apache2/bin/suexec

Apache suEXEC

suEXEC

Apache --sbindir suexec"/usr/local/apache/sbin/suexec") suEXEC

[notice]suEXECmechanismenabled(wrapper:/path/to/suexec)

wrapper

suEXECApache ApachekillHUP

suEXEC suexec Apachekill

suEXEC

CGIsuEXEC SuexecUserGroup

:suEXECwrapper VirtualHost SuexecUserGroup

ID CGI <VirtualHost>

<VirtualHost> ID

:mod_userdir IDCGI--with-suexec-userdir

suEXEC

suEXECwrapper --with-suexec-logfile

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

:

! Apache

wrapper suEXEC""

suEXEC

suEXEC Apache

suEXECPATH

suEXEC

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>MiscellaneousDocumentation

ApachePerformanceTuning

Apache2.xisageneral-purposewebserver,designedtoprovideabalanceofflexibility,portability,andperformance.Althoughithasnotbeendesignedspecificallytosetbenchmarkrecords,Apache2.xiscapableofhighperformanceinmanyreal-worldsituations.

ComparedtoApache1.3,release2.xcontainsmanyadditionaloptimizationstoincreasethroughputandscalability.Mostoftheseimprovementsareenabledbydefault.However,therearecompile-timeandrun-timeconfigurationchoicesthatcansignificantlyaffectperformance.ThisdocumentdescribestheoptionsthataserveradministratorcanconfiguretotunetheperformanceofanApache2.xinstallation.SomeoftheseconfigurationoptionsenablethehttpdtobettertakeadvantageofthecapabilitiesofthehardwareandOS,whileothersallowtheadministratortotradefunctionalityforspeed.

HardwareandOperatingSystemIssues

ThesinglebiggesthardwareissueaffectingwebserverperformanceisRAM.Awebservershouldnevereverhavetoswap,asswappingincreasesthelatencyofeachrequestbeyondapointthatusersconsider"fastenough".Thiscausesuserstohitstopandreload,furtherincreasingtheload.Youcan,andshould,controltheMaxClientssettingsothatyourserverdoesnotspawnsomanychildrenitstartsswapping.Thisprocedurefordoingthisissimple:determinethesizeofyouraverageApacheprocess,bylookingatyourprocesslistviaatoolsuchastop,anddividethisintoyourtotalavailablememory,leavingsomeroomforotherprocesses.

Beyondthattherestismundane:getafastenoughCPU,afastenoughnetworkcard,andfastenoughdisks,where"fastenough"issomethingthatneedstobedeterminedbyexperimentation.

Operatingsystemchoiceislargelyamatteroflocalconcerns.Butsomeguidelinesthathaveprovengenerallyusefulare:

Runthelateststablereleaseandpatchleveloftheoperatingsystemthatyouchoose.ManyOSsuppliershaveintroducedsignificantperformanceimprovementstotheirTCPstacksandthreadlibrariesinrecentyears.

IfyourOSsupportsasendfile(2)systemcall,makesureyouinstallthereleaseand/orpatchesneededtoenableit.(WithLinux,forexample,thismeansusingLinux2.4orlater.ForearlyreleasesofSolaris8,youmayneedtoapplyapatch.)Onsystemswhereitisavailable,sendfileenablesApache2todeliverstaticcontentfasterandwithlowerCPUutilization.

Run-TimeConfigurationIssues

RelatedModules RelatedDirectivesmod_dir

mpm_common

mod_status

AllowOverride

DirectoryIndex

HostnameLookups

EnableMMAP

EnableSendfile

KeepAliveTimeout

MaxSpareServers

MinSpareServers

Options

StartServers

HostnameLookupsandotherDNSconsiderationsPriortoApache1.3,HostnameLookupsdefaultedtoOn.ThisaddslatencytoeveryrequestbecauseitrequiresaDNSlookuptocompletebeforetherequestisfinished.InApache1.3thissettingdefaultstoOff.Ifyouneedtohaveaddressesinyourlogfilesresolvedtohostnames,usethelogresolveprogramthatcomeswithApache,oroneofthenumerouslogreportingpackageswhichareavailable.

Itisrecommendedthatyoudothissortofpostprocessingofyourlogfilesonsomemachineotherthantheproductionwebservermachine,inorderthatthisactivitynotadverselyaffectserverperformance.

IfyouuseanyAllowfromdomainorDenyfromdomaindirectives(i.e.,usingahostname,oradomainname,ratherthananIPaddress)thenyouwillpayfortwoDNSlookups(areverse,followedbyaforwardlookuptomakesurethatthereverseisnotbeingspoofed).Forbestperformance,therefore,useIP

addresses,ratherthannames,whenusingthesedirectives,ifpossible.

Notethatit'spossibletoscopethedirectives,suchaswithina<Location/server-status>section.InthiscasetheDNSlookupsareonlyperformedonrequestsmatchingthecriteria.Here'sanexamplewhichdisableslookupsexceptfor.htmland.cgifiles:

HostnameLookupsoff

<Files~"\.(html|cgi)$">

HostnameLookupson

</Files>

Butevenstill,ifyoujustneedDNSnamesinsomeCGIsyoucouldconsiderdoingthegethostbynamecallinthespecificCGIsthatneedit.

FollowSymLinksandSymLinksIfOwnerMatchWhereverinyourURL-spaceyoudonothaveanOptionsFollowSymLinks,oryoudohaveanOptionsSymLinksIfOwnerMatchApachewillhavetoissueextrasystemcallstocheckuponsymlinks.Oneextracallperfilenamecomponent.Forexample,ifyouhad:

DocumentRoot/www/htdocs

<Directory/>

OptionsSymLinksIfOwnerMatch

</Directory>

andarequestismadefortheURI/index.html.ThenApachewillperformlstat(2)on/www,/www/htdocs,and/www/htdocs/index.html.Theresultsoftheselstatsarenevercached,sotheywilloccuroneverysinglerequest.Ifyoureallydesirethesymlinkssecuritycheckingyoucandosomething

likethis:

DocumentRoot/www/htdocs

<Directory/>

OptionsFollowSymLinks

</Directory>

<Directory/www/htdocs>

Options-FollowSymLinks+SymLinksIfOwnerMatch

</Directory>

ThisatleastavoidstheextrachecksfortheDocumentRootpath.Notethatyou'llneedtoaddsimilarsectionsifyouhaveanyAliasorRewriteRulepathsoutsideofyourdocumentroot.Forhighestperformance,andnosymlinkprotection,setFollowSymLinkseverywhere,andneversetSymLinksIfOwnerMatch.

AllowOverrideWhereverinyourURL-spaceyouallowoverrides(typically.htaccessfiles)Apachewillattempttoopen.htaccessforeachfilenamecomponent.Forexample,

DocumentRoot/www/htdocs

<Directory/>

AllowOverrideall

</Directory>

andarequestismadefortheURI/index.html.ThenApachewillattempttoopen/.htaccess,/www/.htaccess,and/www/htdocs/.htaccess.ThesolutionsaresimilartothepreviouscaseofOptionsFollowSymLinks.ForhighestperformanceuseAllowOverrideNoneeverywhereinyourfilesystem.

Negotiation

Ifatallpossible,avoidcontent-negotiationifyou'rereallyinterestedineverylastounceofperformance.Inpracticethebenefitsofnegotiationoutweightheperformancepenalties.There'sonecasewhereyoucanspeeduptheserver.Insteadofusingawildcardsuchas:

DirectoryIndexindex

Useacompletelistofoptions:

DirectoryIndexindex.cgiindex.plindex.shtmlindex.html

whereyoulistthemostcommonchoicefirst.

Alsonotethatexplicitlycreatingatype-mapfileprovidesbetterperformancethanusingMultiViews,asthenecessaryinformationcanbedeterminedbyreadingthissinglefile,ratherthanhavingtoscanthedirectoryforfiles.

Ifyoursiteneedscontentnegotiationconsiderusingtype-mapfiles,ratherthantheOptionsMultiViewsdirectivetoaccomplishthenegotiation.SeetheContentNegotiationdocumentationforafulldiscussionofthemethodsofnegotiation,andinstructionsforcreatingtype-mapfiles.

Memory-mappingInsituationswhereApache2.xneedstolookatthecontentsofafilebeingdelivered--forexample,whendoingserver-side-includeprocessing--itnormallymemory-mapsthefileiftheOSsupportssomeformofmmap(2).

Onsomeplatforms,thismemory-mappingimprovesperformance.However,therearecaseswherememory-mappingcanhurttheperformanceoreventhestabilityofthehttpd:

Onsomeoperatingsystems,mmapdoesnotscaleaswellasread(2)whenthenumberofCPUsincreases.OnmultiprocessorSolarisservers,forexample,Apache2.xsometimesdeliversserver-parsedfilesfasterwhenmmapisdisabled.

Ifyoumemory-mapafilelocatedonanNFS-mountedfilesystemandaprocessonanotherNFSclientmachinedeletesortruncatesthefile,yourprocessmaygetabuserrorthenexttimeittriestoaccessthemappedfilecontent.

Forinstallationswhereeitherofthesefactorsapplies,youshoulduseEnableMMAPofftodisablethememory-mappingofdeliveredfiles.(Note:Thisdirectivecanbeoverriddenonaper-directorybasis.)

SendfileInsituationswhereApache2.xcanignorethecontentsofthefiletobedelivered--forexample,whenservingstaticfilecontent--itnormallyusesthekernelsendfilesupportthefileiftheOSsupportsthesendfile(2)operation.

Onmostplatforms,usingsendfileimprovesperformancebyeliminatingseparatereadandsendmechanics.However,therearecaseswhereusingsendfilecanharmthestabilityofthehttpd:

Someplatformsmayhavebrokensendfilesupportthatthebuildsystemdidnotdetect,especiallyifthebinarieswerebuiltonanotherboxandmovedtosuchamachinewithbrokensendfilesupport.

WithanNFS-mountedfiles,thekernelmaybeunabletoreliablyservethenetworkfilethroughit'sowncache.

Forinstallationswhereeitherofthesefactorsapplies,youshould

useEnableSendfileofftodisablesendfiledeliveryoffilecontents.(Note:Thisdirectivecanbeoverriddenonaper-directorybasis.)

ProcessCreationPriortoApache1.3theMinSpareServers,MaxSpareServers,andStartServerssettingsallhaddrasticeffectsonbenchmarkresults.Inparticular,Apacherequireda"ramp-up"periodinordertoreachanumberofchildrensufficienttoservetheloadbeingapplied.AftertheinitialspawningofStartServerschildren,onlyonechildpersecondwouldbecreatedtosatisfytheMinSpareServerssetting.Soaserverbeingaccessedby100simultaneousclients,usingthedefaultStartServersof5wouldtakeontheorder95secondstospawnenoughchildrentohandletheload.Thisworksfineinpracticeonreal-lifeservers,becausetheyaren'trestartedfrequently.Butdoesreallypoorlyonbenchmarkswhichmightonlyrunfortenminutes.

Theone-per-secondrulewasimplementedinanefforttoavoidswampingthemachinewiththestartupofnewchildren.Ifthemachineisbusyspawningchildrenitcan'tservicerequests.ButithassuchadrasticeffectontheperceivedperformanceofApachethatithadtobereplaced.AsofApache1.3,thecodewillrelaxtheone-per-secondrule.Itwillspawnone,waitasecond,thenspawntwo,waitasecond,thenspawnfour,anditwillcontinueexponentiallyuntilitisspawning32childrenpersecond.ItwillstopwheneveritsatisfiestheMinSpareServerssetting.

Thisappearstoberesponsiveenoughthatit'salmostunnecessarytotwiddletheMinSpareServers,MaxSpareServersandStartServersknobs.Whenmorethan4childrenarespawnedpersecond,amessagewillbeemittedtotheErrorLog.Ifyouseealotoftheseerrorsthenconsider

tuningthesesettings.Usethemod_statusoutputasaguide.

RelatedtoprocesscreationisprocessdeathinducedbytheMaxRequestsPerChildsetting.Bydefaultthisis0,whichmeansthatthereisnolimittothenumberofrequestshandledperchild.Ifyourconfigurationcurrentlyhasthissettosomeverylownumber,suchas30,youmaywanttobumpthisupsignificantly.IfyouarerunningSunOSoranoldversionofSolaris,limitthisto10000orsobecauseofmemoryleaks.

Whenkeep-alivesareinuse,childrenwillbekeptbusydoingnothingwaitingformorerequestsonthealreadyopenconnection.ThedefaultKeepAliveTimeoutof15secondsattemptstominimizethiseffect.Thetradeoffhereisbetweennetworkbandwidthandserverresources.Innoeventshouldyouraisethisaboveabout60seconds,asmostofthebenefitsarelost.

Compile-TimeConfigurationIssues

ChoosinganMPMApache2.xsupportspluggableconcurrencymodels,calledMulti-ProcessingModules(MPMs).WhenbuildingApache,youmustchooseanMPMtouse.Thereareplatform-specificMPMsforsomeplatforms:beos,mpm_netware,mpmt_os2,andmpm_winnt.ForgeneralUnix-typesystems,thereareseveralMPMsfromwhichtochoose.ThechoiceofMPMcanaffectthespeedandscalabilityofthehttpd:

TheworkerMPMusesmultiplechildprocesseswithmanythreadseach.Eachthreadhandlesoneconnectionatatime.Workergenerallyisagoodchoiceforhigh-trafficserversbecauseithasasmallermemoryfootprintthanthepreforkMPM.ThepreforkMPMusesmultiplechildprocesseswithonethreadeach.Eachprocesshandlesoneconnectionatatime.Onmanysystems,preforkiscomparableinspeedtoworker,butitusesmorememory.Prefork'sthreadlessdesignhasadvantagesoverworkerinsomesituations:itcanbeusedwithnon-thread-safethird-partymodules,anditiseasiertodebugonplatformswithpoorthreaddebuggingsupport.

FormoreinformationontheseandotherMPMs,pleaseseetheMPMdocumentation.

ModulesSincememoryusageissuchanimportantconsiderationinperformance,youshouldattempttoeliminatemodulesthatyouarenotactuallyusing.IfyouhavebuiltthemodulesasDSOs,eliminatingmodulesisasimplematterofcommentingouttheassociatedLoadModuledirectiveforthatmodule.Thisallowsyoutoexperimentwithremovingmodules,andseeingifyoursitestill

functionsintheirabsense.

If,ontheotherhand,youhavemodulesstaticallylinkedintoyourApachebinary,youwillneedtorecompileApacheinordertoremoveunwantedmodules.

Anassociatedquestionthatariseshereis,ofcourse,whatmodulesyouneed,andwhichonesyoudon't.Theanswerherewill,ofcourse,varyfromonewebsitetoanother.However,theminimallistofmoduleswhichyoucangetbywithtendstoincludemod_mime,mod_dir,andmod_log_config.mod_log_configis,ofcourse,optional,asyoucanrunawebsitewithoutlogfiles.Thisis,however,notrecommended.

AtomicOperationsSomemodules,suchasmod_cacheandrecentdevelopmentbuildsoftheworkerMPM,useAPR'satomicAPI.ThisAPIprovidesatomicoperationsthatcanbeusedforlightweightthreadsynchronization.

Bydefault,APRimplementstheseoperationsusingthemostefficientmechanismavailableoneachtargetOS/CPUplatform.ManymodernCPUs,forexample,haveaninstructionthatdoesanatomiccompare-and-swap(CAS)operationinhardware.Onsomeplatforms,however,APRdefaultstoaslower,mutex-basedimplementationoftheatomicAPIinordertoensurecompatibilitywitholderCPUmodelsthatlacksuchinstructions.IfyouarebuildingApacheforoneoftheseplatforms,andyouplantorunonlyonnewerCPUs,youcanselectafasteratomicimplementationatbuildtimebyconfiguringApachewiththe--enable-nonportable-atomicsoption:

./buildconf

./configure--with-mpm=worker--enable-nonportable-atomics=yes

The--enable-nonportable-atomicsoptionisrelevantforthefollowingplatforms:

SolarisonSPARCBydefault,APRusesmutex-basedatomicsonSolaris/SPARC.Ifyouconfigurewith--enable-nonportable-atomics,however,APRgeneratescodethatusesaSPARCv8plusopcodeforfasthardwarecompare-and-swap.IfyouconfigureApachewiththisoption,theatomicoperationswillbemoreefficient(allowingforlowerCPUutilizationandhigherconcurrency),buttheresultingexecutablewillrunonlyonUltraSPARCchips.Linuxonx86Bydefault,APRusesmutex-basedatomicsonLinux.Ifyouconfigurewith--enable-nonportable-atomics,however,APRgeneratescodethatusesa486opcodeforfasthardwarecompare-and-swap.Thiswillresultinmoreefficientatomicoperations,buttheresultingexecutablewillrunonlyon486andlaterchips(andnoton386).

mod_statusandExtendedStatusOnIfyouincludemod_statusandyoualsosetExtendedStatusOnwhenbuildingandrunningApache,thenoneveryrequestApachewillperformtwocallstogettimeofday(2)(ortimes(2)dependingonyouroperatingsystem),and(pre-1.3)severalextracallstotime(2).Thisisalldonesothatthestatusreportcontainstimingindications.Forhighestperformance,setExtendedStatusoff(whichisthedefault).

acceptSerialization-multiplesockets

Warning:

Thissectionhasnotbeenfullyupdatedtotakeintoaccountchangesmadeinthe2.xversionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

ThisdiscussesashortcomingintheUnixsocketAPI.SupposeyourwebserverusesmultipleListenstatementstolistenoneithermultipleportsormultipleaddresses.InordertotesteachsockettoseeifaconnectionisreadyApacheusesselect(2).select(2)indicatesthatasockethaszerooratleastoneconnectionwaitingonit.Apache'smodelincludesmultiplechildren,andalltheidleonestestfornewconnectionsatthesametime.Anaiveimplementationlookssomethinglikethis(theseexamplesdonotmatchthecode,they'recontrivedforpedagogicalpurposes):

for(;;){

for(;;){

fd_setaccept_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;

}

processthenew_connection;

}

Butthisnaiveimplementationhasaseriousstarvationproblem.

Recallthatmultiplechildrenexecutethisloopatthesametime,andsomultiplechildrenwillblockatselectwhentheyareinbetweenrequests.Allthoseblockedchildrenwillawakenandreturnfromselectwhenasinglerequestappearsonanysocket(thenumberofchildrenwhichawakenvariesdependingontheoperatingsystemandtimingissues).Theywillallthenfalldownintotheloopandtrytoaccepttheconnection.Butonlyonewillsucceed(assumingthere'sstillonlyoneconnectionready),therestwillbeblockedinaccept.Thiseffectivelylocksthosechildrenintoservingrequestsfromthatonesocketandnoothersockets,andthey'llbestuckthereuntilenoughnewrequestsappearonthatsockettowakethemallup.ThisstarvationproblemwasfirstdocumentedinPR#467.Thereareatleasttwosolutions.

Onesolutionistomakethesocketsnon-blocking.Inthiscasetheacceptwon'tblockthechildren,andtheywillbeallowedtocontinueimmediately.ButthiswastesCPUtime.Supposeyouhavetenidlechildreninselect,andoneconnectionarrives.Thennineofthosechildrenwillwakeup,trytoaccepttheconnection,fail,andloopbackintoselect,accomplishingnothing.Meanwhilenoneofthosechildrenareservicingrequeststhatoccurredonothersocketsuntiltheygetbackuptotheselectagain.OverallthissolutiondoesnotseemveryfruitfulunlessyouhaveasmanyidleCPUs(inamultiprocessorbox)asyouhaveidlechildren,notaverylikelysituation.

Anothersolution,theoneusedbyApache,istoserializeentryintotheinnerloop.Thelooplookslikethis(differenceshighlighted):

for(;;){

accept_mutex_on();

for(;;){

fd_setaccept_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();

processthenew_connection;

}

Thefunctionsaccept_mutex_onandaccept_mutex_offimplementamutualexclusionsemaphore.Onlyonechildcanhavethemutexatanytime.Thereareseveralchoicesforimplementingthesemutexes.Thechoiceisdefinedinsrc/conf.h(pre-1.3)orsrc/include/ap_config.h(1.3orlater).Somearchitecturesdonothaveanylockingchoicemade,onthesearchitecturesitisunsafetousemultipleListendirectives.

ThedirectiveAcceptMutexcanbeusedtochangetheselectedmuteximplementationatrun-time.

AcceptMutexflock

Thismethodusestheflock(2)systemcalltolockalockfile(locatedbytheLockFiledirective).

AcceptMutexfcntl

Thismethodusesthefcntl(2)systemcalltolockalockfile(locatedbytheLockFiledirective).

AcceptMutexsysvsem

(1.3orlater)ThismethodusesSysV-stylesemaphoresto

implementthemutex.UnfortunatelySysV-stylesemaphoreshavesomebadside-effects.Oneisthatit'spossibleApachewilldiewithoutcleaningupthesemaphore(seetheipcs(8)manpage).TheotheristhatthesemaphoreAPIallowsforadenialofserviceattackbyanyCGIsrunningunderthesameuidasthewebserver(i.e.,allCGIs,unlessyouusesomethinglikesuexecorcgiwrapper).ForthesereasonsthismethodisnotusedonanyarchitectureexceptIRIX(wheretheprevioustwoareprohibitivelyexpensiveonmostIRIXboxes).

AcceptMutexpthread

(1.3orlater)ThismethodusesPOSIXmutexesandshouldworkonanyarchitectureimplementingthefullPOSIXthreadsspecification,howeverappearstoonlyworkonSolaris(2.5orlater),andeventhenonlyincertainconfigurations.Ifyouexperimentwiththisyoushouldwatchoutforyourserverhangingandnotresponding.Staticcontentonlyserversmayworkjustfine.

AcceptMutexposixsem

(2.0orlater)ThismethodusesPOSIXsemaphores.Thesemaphoreownershipisnotrecoveredifathreadintheprocessholdingthemutexsegfaults,resultinginahangofthewebserver.

Ifyoursystemhasanothermethodofserializationwhichisn'tintheabovelistthenitmaybeworthwhileaddingcodeforittoAPR.

Anothersolutionthathasbeenconsideredbutneverimplementedistopartiallyserializetheloop--thatis,letinacertainnumberofprocesses.Thiswouldonlybeofinterestonmultiprocessorboxeswhereit'spossiblemultiplechildrencouldrunsimultaneously,andtheserializationactuallydoesn'ttakeadvantageofthefullbandwidth.Thisisapossibleareaoffutureinvestigation,butpriorityremainslowbecausehighlyparallelwebserversarenot

thenorm.

IdeallyyoushouldrunserverswithoutmultipleListenstatementsifyouwantthehighestperformance.Butreadon.

acceptSerialization-singlesocketTheaboveisfineanddandyformultiplesocketservers,butwhataboutsinglesocketservers?Intheorytheyshouldn'texperienceanyofthesesameproblemsbecauseallchildrencanjustblockinaccept(2)untilaconnectionarrives,andnostarvationresults.Inpracticethishidesalmostthesame"spinning"behaviourdiscussedaboveinthenon-blockingsolution.ThewaythatmostTCPstacksareimplemented,thekernelactuallywakesupallprocessesblockedinacceptwhenasingleconnectionarrives.Oneofthoseprocessesgetstheconnectionandreturnstouser-space,therestspininthekernelandgobacktosleepwhentheydiscoverthere'snoconnectionforthem.Thisspinningishiddenfromtheuser-landcode,butit'stherenonetheless.Thiscanresultinthesameload-spikingwastefulbehaviourthatanon-blockingsolutiontothemultiplesocketscasecan.

Forthisreasonwehavefoundthatmanyarchitecturesbehavemore"nicely"ifweserializeeventhesinglesocketcase.Sothisisactuallythedefaultinalmostallcases.CrudeexperimentsunderLinux(2.0.30onadualPentiumpro166w/128MbRAM)haveshownthattheserializationofthesinglesocketcasecauseslessthana3%decreaseinrequestspersecondoverunserializedsingle-socket.Butunserializedsingle-socketshowedanextra100mslatencyoneachrequest.Thislatencyisprobablyawashonlonghaullines,andonlyanissueonLANs.IfyouwanttooverridethesinglesocketserializationyoucandefineSINGLE_LISTEN_UNSERIALIZED_ACCEPTandthensingle-socketserverswillnotserializeatall.

LingeringCloseAsdiscussedindraft-ietf-http-connection-00.txtsection8,inorderforanHTTPservertoreliablyimplementtheprotocolitneedstoshutdowneachdirectionofthecommunicationindependently(recallthataTCPconnectionisbi-directional,eachhalfisindependentoftheother).Thisfactisoftenoverlookedbyotherservers,butiscorrectlyimplementedinApacheasof1.2.

WhenthisfeaturewasaddedtoApacheitcausedaflurryofproblemsonvariousversionsofUnixbecauseofashortsightedness.TheTCPspecificationdoesnotstatethattheFIN_WAIT_2statehasatimeout,butitdoesn'tprohibitit.Onsystemswithoutthetimeout,Apache1.2inducesmanysocketsstuckforeverintheFIN_WAIT_2state.InmanycasesthiscanbeavoidedbysimplyupgradingtothelatestTCP/IPpatchessuppliedbythevendor.Incaseswherethevendorhasneverreleasedpatches(i.e.,SunOS4--althoughfolkswithasourcelicensecanpatchitthemselves)wehavedecidedtodisablethisfeature.

Therearetwowaysofaccomplishingthis.OneisthesocketoptionSO_LINGER.Butasfatewouldhaveit,thishasneverbeenimplementedproperlyinmostTCP/IPstacks.Evenonthosestackswithaproperimplementation(i.e.,Linux2.0.31)thismethodprovestobemoreexpensive(cputime)thanthenextsolution.

Forthemostpart,Apacheimplementsthisinafunctioncalledlingering_close(inhttp_main.c).Thefunctionlooksroughlylikethis:

voidlingering_close(ints)

{

charjunk_buffer[2048];

/*shutdownthesendingside*/

shutdown(s,1);

signal(SIGALRM,lingering_death);

alarm(30);

for(;;){

select(sforreading,2secondtimeout);

if(error)break;

if(sisreadyforreading){

if(read(s,junk_buffer,sizeof(junk_buffer))<=0){

break;

}

/*justtossawaywhateverishere*/

}

}

close(s);

}

Thisnaturallyaddssomeexpenseattheendofaconnection,butitisrequiredforareliableimplementation.AsHTTP/1.1becomesmoreprevalent,andallconnectionsarepersistent,thisexpensewillbeamortizedovermorerequests.IfyouwanttoplaywithfireanddisablethisfeatureyoucandefineNO_LINGCLOSE,butthisisnotrecommendedatall.Inparticular,asHTTP/1.1pipelinedpersistentconnectionscomeintouselingering_closeisanabsolutenecessity(andpipelinedconnectionsarefaster,soyouwanttosupportthem).

ScoreboardFileApache'sparentandchildrencommunicatewitheachotherthroughsomethingcalledthescoreboard.Ideallythisshouldbeimplementedinsharedmemory.Forthoseoperatingsystemsthatweeitherhaveaccessto,orhavebeengivendetailedportsfor,ittypicallyisimplementedusingsharedmemory.Therestdefaulttousinganon-diskfile.Theon-diskfileisnotonlyslow,butitisunreliable(andlessfeatured).Perusethesrc/main/conf.hfileforyourarchitectureandlookforeitherUSE_MMAP_SCOREBOARDorUSE_SHMGET_SCOREBOARD.Definingoneofthosetwo(aswell

astheircompanionsHAVE_MMAPandHAVE_SHMGETrespectively)enablesthesuppliedsharedmemorycode.Ifyoursystemhasanothertypeofsharedmemory,editthefilesrc/main/http_main.candaddthehooksnecessarytouseitinApache.(Sendusbackapatchtooplease.)

Historicalnote:TheLinuxportofApachedidn'tstarttousesharedmemoryuntilversion1.2ofApache.ThisoversightresultedinreallypoorandunreliablebehaviourofearlierversionsofApacheonLinux.

DYNAMIC_MODULE_LIMITIfyouhavenointentionofusingdynamicallyloadedmodules(youprobablydon'tifyou'rereadingthisandtuningyourserverforeverylastounceofperformance)thenyoushouldadd-DDYNAMIC_MODULE_LIMIT=0whenbuildingyourserver.ThiswillsaveRAMthat'sallocatedonlyforsupportingdynamicallyloadedmodules.

Appendix:DetailedAnalysisofaTrace

HereisasystemcalltraceofApache2.0.38withtheworkerMPMonSolaris8.Thistracewascollectedusing:

truss-l-phttpd_child_pid.

The-loptiontellstrusstologtheIDoftheLWP(lightweightprocess--Solaris'sformofkernel-levelthread)thatinvokeseachsystemcall.

Othersystemsmayhavedifferentsystemcalltracingutilitiessuchasstrace,ktrace,orpar.Theyallproducesimilaroutput.

Inthistrace,aclienthasrequesteda10KBstaticfilefromthehttpd.Tracesofnon-staticrequestsorrequestswithcontentnegotiationlookwildlydifferent(andquiteuglyinsomecases).

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

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

Inthistrace,thelistenerthreadisrunningwithinLWP#67.

Notethelackofaccept(2)serialization.Onthisparticularplatform,theworkerMPMusesanunserializedacceptbydefaultunlessitislisteningonmultipleports.

/65:lwp_park(0x00000000,0)=0

/67:lwp_unpark(65,1)=0

Uponacceptingtheconnection,thelistenerthreadwakesupaworkerthreadtodotherequestprocessing.Inthistrace,theworkerthreadthathandlestherequestismappedtoLWP#65.

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

Inordertoimplementvirtualhosts,Apacheneedstoknowthelocalsocketaddressusedtoaccepttheconnection.Itispossibletoeliminatethiscallinmanysituations(suchaswhentherearenovirtualhosts,orwhenListendirectivesareusedwhichdonothavewildcardaddresses).Butnoefforthasyetbeenmadetodotheseoptimizations.

/65:brk(0x002170E8)=0

/65:brk(0x002190E8)=0

Thebrk(2)callsallocatememoryfromtheheap.Itisraretoseetheseinasystemcalltrace,becausethehttpdusescustommemoryallocators(apr_poolandapr_bucket_alloc)formostrequestprocessing.Inthistrace,thehttpdhasjustbeenstarted,soitmustcallmalloc(3)togettheblocksofrawmemorywithwhichtocreatethecustommemoryallocators.

/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,theworkerthreadputstheconnectiontotheclient(filedescriptor9)innon-blockingmode.Thesetsockopt(2)andgetsockopt(2)callsareaside-effectofhowSolaris'slibchandlesfcntl(2)onsockets.

/65:read(9,"GET/10k.htm"..,8000)=97

Theworkerthreadreadstherequestfromtheclient.

/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

ThishttpdhasbeenconfiguredwithOptionsFollowSymLinksandAllowOverrideNone.Thusitdoesn'tneedtolstat(2)eachdirectoryinthepathleadinguptotherequestedfile,norcheckfor.htaccessfiles.Itsimplycallsstat(2)toverifythatthefile:1)exists,and2)isaregularfile,notadirectory.

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

Inthisexample,thehttpdisabletosendtheHTTPresponseheaderandtherequestedfilewithasinglesendfilev(2)systemcall.Sendfilesemanticsvaryamongoperatingsystems.Onsomeothersystems,itisnecessarytodoawrite(2)orwritev(2)calltosendtheheadersbeforecallingsendfile(2).

/65:write(4,"127.0.0.1-"..,78)=78

Thiswrite(2)callrecordstherequestintheaccesslog.Notethatonethingmissingfromthistraceisatime(2)call.UnlikeApache1.3,Apache2.xusesgettimeofday(3)tolookupthetime.Onsomeoperatingsystems,likeLinuxorSolaris,gettimeofdayhasanoptimizedimplementationthatdoesn'trequireasmuchoverheadasatypicalsystemcall.

/65:shutdown(9,1,1)=0

/65:poll(0xFAF7B980,1,2000)=1

/65:read(9,0xFAF7BC20,512)=0

/65:close(9)=0

Theworkerthreaddoesalingeringcloseoftheconnection.

/65:close(10)=0

/65:lwp_park(0x00000000,0)(sleeping...)

Finallytheworkerthreadclosesthefilethatithasjustdelivered

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

andblocksuntilthelistenerassignsitanotherconnection.

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

Meanwhile,thelistenerthreadisabletoacceptanotherconnectionassoonasithasdispatchedthisconnectiontoaworkerthread(subjecttosomeflow-controllogicintheworkerMPMthatthrottlesthelistenerifalltheavailableworkersarebusy).Thoughitisn'tapparentfromthistrace,thenextaccept(2)can(andusuallydoes,underhighloadconditions)occurinparallelwiththeworkerthread'shandlingofthejust-acceptedconnection.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>MiscellaneousDocumentation

URLRewritingGuide

OriginallywrittenbyRalfS.Engelschall<rse@apache.org>December1997

Thisdocumentsupplementsthemod_rewritereferencedocumentation.ItdescribeshowonecanuseApache'smod_rewritetosolvetypicalURL-basedproblemswithwhichwebmastersarecommononyconfronted.WegivedetaileddescriptionsonhowtosolveeachproblembyconfiguringURLrewritingrulesets.

Introductiontomod_rewrite

TheApachemodulemod_rewriteisakillerone,i.e.itisareallysophisticatedmodulewhichprovidesapowerfulwaytodoURLmanipulations.WithityoucandonearlyalltypesofURLmanipulationsyoueverdreamedabout.Thepriceyouhavetopayistoacceptcomplexity,becausemod_rewrite'smajordrawbackisthatitisnoteasytounderstandanduseforthebeginner.AndevenApacheexpertssometimesdiscovernewaspectswheremod_rewritecanhelp.

Inotherwords:Withmod_rewriteyoueithershootyourselfinthefootthefirsttimeandneveruseitagainorloveitfortherestofyourlifebecauseofitspower.Thispapertriestogiveyouafewinitialsuccesseventstoavoidthefirstcasebypresentingalreadyinventedsolutionstoyou.

PracticalSolutions

HerecomealotofpracticalsolutionsI'veeitherinventedmyselforcollectedfromotherpeople'ssolutionsinthepast.FeelfreetolearntheblackmagicofURLrewritingfromtheseexamples.

ATTENTION:Dependingonyourserver-configurationitcanbenecessarytoslightlychangetheexamplesforyoursituation,e.g.addingthe[PT]flagwhenadditionallyusingmod_aliasandmod_userdir,etc.Orrewritingarulesettofitin.htaccesscontextinsteadofper-servercontext.Alwaystrytounderstandwhataparticularrulesetreallydoesbeforeyouuseit.Itavoidproblems.

URLLayout

CanonicalURLsDescription:

OnsomewebserverstherearemorethanoneURLforaresource.UsuallytherearecanonicalURLs(whichshouldbeactuallyusedanddistributed)andthosewhicharejustshortcuts,internalones,etc.IndependentofwhichURLtheusersuppliedwiththerequestheshouldfinallyseethecanonicaloneonly.

Solution:WedoanexternalHTTPredirectforallnon-canonicalURLstofixtheminthelocationviewoftheBrowserandforallsubsequentrequests.Intheexamplerulesetbelowwereplace/~userbythecanonical/u/userandfixamissingtrailingslashfor/u/user.

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

RewriteRule^/([uge])/([^/]+)$/$1/$2/[R]

CanonicalHostnamesDescription:

Thegoalofthisruleistoforcetheuseofaparticularhostname,inpreferencetootherhostnameswhichmaybeusedtoreachthesamesite.Forexample,ifyouwishtoforcetheuseofwww.example.cominsteadofexample.com,youmightuseavariantofthefollowingrecipe.

Solution:

#Forsitesrunningonaportotherthan80

RewriteCond%{HTTP_HOST}!^www\.example\.com[NC]

RewriteCond%{HTTP_HOST}!^$

RewriteCond%{SERVER_PORT}!^80$

RewriteRule^/(.*)http://www.example.com:%{SERVER_PORT}/$1[L,R]

#Andforasiterunningonport80

RewriteCond%{HTTP_HOST}!^www\.example\.com[NC]

RewriteCond%{HTTP_HOST}!^$

RewriteRule^/(.*)http://www.example.com/$1[L,R]

MovedDocumentRootDescription:

UsuallytheDocumentRootofthewebserverdirectlyrelatestotheURL"/".Butoftenthisdataisnotreallyoftop-levelpriority,itisperhapsjustoneentityofalotofdatapools.ForinstanceatourIntranetsitesthereare/e/www/(thehomepageforWWW),/e/sww/(thehomepagefortheIntranet)etc.NowbecausethedataoftheDocumentRootstaysat/e/www/wehadtomakesurethatallinlinedimagesandotherstuffinsidethisdatapoolworkforsubsequentrequests.

Solution:WeredirecttheURL/to/e/www/:

RewriteEngineon

RewriteRule^/$/e/www/[R]

NotethatthiscanalsobehandledusingtheRedirectMatchdirective:

RedirectMatch^/$http://example.com/e/www/

TrailingSlashProblem

Description:EverywebmastercansingasongabouttheproblemofthetrailingslashonURLsreferencingdirectories.Iftheyaremissing,theserverdumpsanerror,becauseifyousay/~quux/fooinsteadof/~quux/foo/thentheserversearchesforafilenamedfoo.Andbecausethisfileisadirectoryitcomplains.Actuallyittriestofixititselfinmostofthecases,butsometimesthismechanismneedtobeemulatedbyyou.ForinstanceafteryouhavedonealotofcomplicatedURLrewritingstoCGIscriptsetc.

Solution:Thesolutiontothissubtleproblemistolettheserveraddthetrailingslashautomatically.Todothiscorrectlywehavetouseanexternalredirect,sothebrowsercorrectlyrequestssubsequentimagesetc.Ifweonlydidainternalrewrite,thiswouldonlyworkforthedirectorypage,butwouldgowrongwhenanyimagesareincludedintothispagewithrelativeURLs,becausethebrowserwouldrequestanin-linedobject.Forinstance,arequestforimage.gifin/~quux/foo/index.htmlwouldbecome/~quux/image.gifwithouttheexternalredirect!

So,todothistrickwewrite:

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo$foo/[R]

Thecrazyandlazycanevendothefollowinginthetop-level.htaccessfileoftheirhomedir.Butnoticethatthiscreatessomeprocessingoverhead.

RewriteEngineon

RewriteBase/~quux/

RewriteCond%{REQUEST_FILENAME}-d

RewriteRule^(.+[^/])$$1/[R]

WebclusterthroughHomogeneousURLLayoutDescription:

WewanttocreateahomogeneousandconsistentURLlayoutoverallWWWserversonaIntranetwebcluster,i.e.allURLs(perdefinitionserverlocalandthusserverdependent!)becomeactuallyserverindependent!WhatwewantistogivetheWWWnamespaceaconsistentserver-independentlayout:noURLshouldhavetoincludeanyphysicallycorrecttargetserver.Theclusteritselfshoulddriveusautomaticallytothephysicaltargethost.

Solution:First,theknowledgeofthetargetserverscomefrom(distributed)externalmapswhichcontaininformationwhereourusers,groupsandentitiesstay.Thehavetheform

user1server_of_user1

user2server_of_user2

::

Weputthemintofilesmap.xxx-to-host.SecondweneedtoinstructallserverstoredirectURLsoftheforms

/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

whentheURLisnotlocallyvalidtoaserver.Thefollowingrulesetdoesthisforusbythehelpofthemapfiles(assumingthatserver0isadefaultserverwhichwillbeusedifauserhasnoentryinthemap):

RewriteEngineon

RewriteMapuser-to-hosttxt:/path/to/map.user-to-host

RewriteMapgroup-to-hosttxt:/path/to/map.group-to-host

RewriteMapentity-to-hosttxt:/path/to/map.entity-to-host

RewriteRule^/u/([^/]+)/?(.*)http://${user-to-host:$1|server0}

RewriteRule^/g/([^/]+)/?(.*)http://${group-to-host:$1|server0}

RewriteRule^/e/([^/]+)/?(.*)http://${entity-to-host:$1|server0}

RewriteRule^/([uge])/([^/]+)/?$/$1/$2/.www/

RewriteRule^/([uge])/([^/]+)/([^.]+.+)/$1/$2/.www/$3\

MoveHomedirstoDifferentWebserverDescription:

Manywebmastershaveaskedforasolutiontothefollowingsituation:Theywantedtoredirectjustallhomedirsonawebservertoanotherwebserver.Theyusuallyneedsuchthingswhenestablishinganewerwebserverwhichwillreplacetheoldoneovertime.

Solution:Thesolutionistrivialwithmod_rewrite.Ontheoldwebserverwejustredirectall/~user/anypathURLsto

http://newserver/~user/anypath.

RewriteEngineon

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

StructuredHomedirsDescription:

Somesiteswiththousandsofusersusuallyuseastructuredhomedirlayout,i.e.eachhomedirisinasubdirectorywhichbeginsforinstancewiththefirstcharacteroftheusername.So,/~foo/anypathis/home/f/foo/.www/anypathwhile/~bar/anypathis/home/b/bar/.www/anypath.

Solution:WeusethefollowingrulesettoexpandthetildeURLsintoexactlytheabovelayout.

RewriteEngineon

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

FilesystemReorganizationDescription:

Thisreallyisahardcoreexample:akillerapplicationwhichheavilyusesper-directoryRewriteRulestogetasmoothlookandfeelontheWebwhileitsdatastructureisnevertouchedoradjusted.Background:net.swismyarchiveoffreelyavailableUnixsoftwarepackages,whichIstartedtocollectin1992.Itisbothmyhobbyandjobtotothis,becausewhileI'mstudyingcomputerscienceIhavealsoworkedformanyyearsasasystemandnetworkadministratorinmysparetime.EveryweekIneedsomesortofsoftwaresoIcreatedadeephierarchyofdirectorieswhereIstoredthe

packages:

drwxrwxr-x2netswusers512Aug318:39Audio/

drwxrwxr-x2netswusers512Jul914:37Benchmark/

drwxrwxr-x12netswusers512Jul900:34Crypto/

drwxrwxr-x5netswusers512Jul900:41Database/

drwxrwxr-x4netswusers512Jul3019:25Dicts/

drwxrwxr-x10netswusers512Jul901:54Graphic/

drwxrwxr-x5netswusers512Jul901:58Hackers/

drwxrwxr-x8netswusers512Jul903:19InfoSys/

drwxrwxr-x3netswusers512Jul903:21Math/

drwxrwxr-x3netswusers512Jul903:24Misc/

drwxrwxr-x9netswusers512Aug116:33Network/

drwxrwxr-x2netswusers512Jul905:53Office/

drwxrwxr-x7netswusers512Jul909:24SoftEng/

drwxrwxr-x7netswusers512Jul912:17System/

drwxrwxr-x12netswusers512Aug320:15Typesetting/

drwxrwxr-x10netswusers512Jul914:08X11/

InJuly1996IdecidedtomakethisarchivepublictotheworldviaaniceWebinterface."Nice"meansthatIwantedtoofferaninterfacewhereyoucanbrowsedirectlythroughthearchivehierarchy.And"nice"meansthatIdidn'twantedtochangeanythinginsidethishierarchy-notevenbyputtingsomeCGIscriptsatthetopofit.Why?BecausetheabovestructureshouldbelateraccessibleviaFTPaswell,andIdidn'twantanyWeborCGIstufftobethere.

Solution:Thesolutionhastwoparts:ThefirstisasetofCGIscriptswhichcreateallthepagesatalldirectorylevelson-the-fly.Iputthemunder/e/netsw/.www/asfollows:

-rw-r--r--1netswusers1318Aug118:10.wwwacl

drwxr-xr-x18netswusers512Aug515:51DATA/

-rw-rw-rw-1netswusers372982Aug516:35LOGFILE

-rw-r--r--1netswusers659Aug409:27TODO

-rw-r--r--1netswusers5697Aug118:01netsw-about.html

-rwxr-xr-x1netswusers579Aug210:33netsw-access.pl

-rwxr-xr-x1netswusers1532Aug117:35netsw-changes.cgi

-rwxr-xr-x1netswusers2866Aug514:49netsw-home.cgi

drwxr-xr-x2netswusers512Jul823:47netsw-img/

-rwxr-xr-x1netswusers24050Aug515:49netsw-lsdir.cgi

-rwxr-xr-x1netswusers1589Aug318:43netsw-search.cgi

-rwxr-xr-x1netswusers1885Aug117:41netsw-tree.cgi

-rw-r--r--1netswusers234Jul3016:35netsw-unlimit.lst

TheDATA/subdirectoryholdstheabovedirectorystructure,i.e.therealnet.swstuffandgetsautomaticallyupdatedviardistfromtimetotime.Thesecondpartoftheproblemremains:howtolinkthesetwostructurestogetherintoonesmooth-lookingURLtree?WewanttohidetheDATA/directoryfromtheuserwhilerunningtheappropriateCGIscriptsforthevariousURLs.Hereisthesolution:firstIputthefollowingintotheper-directoryconfigurationfileintheDocumentRootoftheservertorewritetheannouncedURL/net.sw/totheinternalpath/e/netsw:

RewriteRule^net.sw$net.sw/[R]

RewriteRule^net.sw/(.*)$e/netsw/$1

Thefirstruleisforrequestswhichmissthetrailingslash!Thesecondruledoestherealthing.Andthencomesthekillerconfigurationwhichstaysintheper-directoryconfigfile/e/netsw/.www/.wwwacl:

OptionsExecCGIFollowSymLinksIncludesMultiViews

RewriteEngineon

#wearereachedvia/net.sw/prefix

RewriteBase/net.sw/

#firstwerewritetherootdirto

#thehandlingcgiscript

RewriteRule^$netsw-home.cgi[L]

RewriteRule^index\.html$netsw-home.cgi[L]

#stripoutthesubdirswhen

#thebrowserrequestsusfromperdirpages

RewriteRule^.+/(netsw-[^/]+/.+)$$1[L]

#andnowbreaktherewritingforlocalfiles

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]

#anythingelseisasubdirwhichgetshandled

#byanothercgiscript

RewriteRule!^netsw-lsdir\.cgi.*-[C]

RewriteRule(.*)netsw-lsdir.cgi/$1

Somehintsforinterpretation:

1. NoticetheL(last)flagandnosubstitutionfield('-')intheforthpart

2. Noticethe!(not)characterandtheC(chain)flagatthefirstruleinthelastpart

3. Noticethecatch-allpatterninthelastrule

NCSAimagemaptoApachemod_imapDescription:

WhenswitchingfromtheNCSAwebservertothemoremodernApachewebserveralotofpeoplewantasmoothtransition.SotheywantpageswhichusetheiroldNCSAimagemapprogramtoworkunderApachewiththemodernmod_imap.Theproblemisthattherearealotofhyperlinksaroundwhichreferencetheimagemapprogramvia/cgi-bin/imagemap/path/to/page.map.UnderApachethishastoreadjust/path/to/page.map.

Solution:Weuseaglobalruletoremovetheprefixon-the-flyforallrequests:

RewriteEngineon

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

SearchpagesinmorethanonedirectoryDescription:

Sometimesitisnecessarytoletthewebserversearchforpagesinmorethanonedirectory.HereMultiViewsorothertechniquescannothelp.

Solution:Weprogramaexplicitrulesetwhichsearchesforthefilesinthedirectories.

RewriteEngineon

#firsttrytofinditincustom/...

#...andiffoundstopandbehappy:

RewriteCond/your/docroot/dir1/%{REQUEST_FILENAME}-f

RewriteRule^(.+)/your/docroot/dir1/$1[L]

#secondtrytofinditinpub/...

#...andiffoundstopandbehappy:

RewriteCond/your/docroot/dir2/%{REQUEST_FILENAME}-f

RewriteRule^(.+)/your/docroot/dir2/$1[L]

#elsegoonforotherAliasorScriptAliasdirectives,

#etc.

RewriteRule^(.+)-[PT]

SetEnvironmentVariablesAccordingToURLPartsDescription:

PerhapsyouwanttokeepstatusinformationbetweenrequestsandusetheURLtoencodeit.Butyoudon'twanttouseaCGIwrapperforallpagesjusttostripoutthisinformation.

Solution:WeusearewriteruletostripoutthestatusinformationandrememberitviaanenvironmentvariablewhichcanbelaterdereferencedfromwithinXSSIorCGI.ThiswayaURL/foo/S=java/bar/getstranslatedto/foo/bar/andtheenvironmentvariablenamedSTATUSissettothevalue"java".

RewriteEngineon

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

VirtualUserHosts

Description:Assumethatyouwanttoprovidewww.username.host.domain.comforthehomepageofusernameviajustDNSArecordstothesamemachineandwithoutanyvirtualhostsonthismachine.

Solution:ForHTTP/1.0requeststhereisnosolution,butforHTTP/1.1requestswhichcontainaHost:HTTPheaderwecanusethefollowingrulesettorewritehttp://www.username.host.com/anypathinternallyto/home/username/anypath:

RewriteEngineon

RewriteCond%{HTTP_HOST}^www\.[^.]+\.host\.com$

RewriteRule^(.+)%{HTTP_HOST}$1[C]

RewriteRule^www\.([^.]+)\.host\.com(.*)/home/$1$2

RedirectHomedirsForForeignersDescription:

WewanttoredirecthomedirURLstoanotherwebserverwww.somewhere.comwhentherequestinguserdoesnotstayinthelocaldomainourdomain.com.Thisissometimesusedinvirtualhostcontexts.

Solution:Justarewritecondition:

RewriteEngineon

RewriteCond%{REMOTE_HOST}!^.+\.ourdomain\.com$

RewriteRule^(/~.+)http://www.somewhere.com/$1[R,L]

RedirectFailingURLsToOtherWebserverDescription:

AtypicalFAQaboutURLrewritingishowtoredirectfailingrequestsonwebserverAtowebserverB.UsuallythisisdoneviaErrorDocumentCGI-scriptsinPerl,butthereisalsoamod_rewritesolution.ButnoticethatthisperformsmorepoorlythanusinganErrorDocumentCGI-script!

Solution:Thefirstsolutionhasthebestperformancebutlessflexibility,andislesserrorsafe:

RewriteEngineon

RewriteCond/your/docroot/%{REQUEST_FILENAME}!-f

RewriteRule^(.+)http://webserverB

TheproblemhereisthatthiswillonlyworkforpagesinsidetheDocumentRoot.WhileyoucanaddmoreConditions(forinstancetoalsohandlehomedirs,etc.)thereisbettervariant:

RewriteEngineon

RewriteCond%{REQUEST_URI}!-U

RewriteRule^(.+)http://webserverB.dom/$1

ThisusestheURLlook-aheadfeatureofmod_rewrite.TheresultisthatthiswillworkforalltypesofURLsandisasafeway.Butitdoesaperformanceimpactonthewebserver,becauseforeveryrequestthereisonemoreinternalsubrequest.So,ifyourwebserverrunsonapowerfulCPU,usethisone.Ifitisaslowmachine,usethefirstapproachorbetteraErrorDocumentCGI-script.

ExtendedRedirection

Description:Sometimesweneedmorecontrol(concerningthecharacterescapingmechanism)ofURLsonredirects.UsuallytheApachekernelsURLescapefunctionalsoescapesanchors,i.e.URLslike"url#anchor".Youcannotusethisdirectlyonredirectswithmod_rewritebecausetheuri_escape()functionofApachewouldalsoescapethehashcharacter.HowcanweredirecttosuchaURL?

Solution:WehavetouseakludgebytheuseofaNPH-CGIscriptwhichdoestheredirectitself.Becauseherenoescapingisdone(NPH=non-parseableheaders).FirstweintroduceanewURLschemexredirect:bythefollowingper-serverconfig-line(shouldbeoneofthelastrewriterules):

RewriteRule^xredirect:(.+)/path/to/nph-xredirect.cgi/$1\

[T=application/x-httpd-cgi,L]

ThisforcesallURLsprefixedwithxredirect:tobepipedthroughthenph-xredirect.cgiprogram.Andthisprogramjustlookslike:

#!/path/to/perl

##

##nph-xredirect.cgi--NPH/CGIscriptforextendedredirects

##Copyright(c)1997RalfS.Engelschall,AllRightsReserved.

##

$|=1;

$url=$ENV{'PATH_INFO'};

print"HTTP/1.0302MovedTemporarily\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>302MovedTemporarily(EXTENDED)</title>\n";

print"</head>\n";

print"<body>\n";

print"<h1>MovedTemporarily(EXTENDED)</h1>\n";

print"Thedocumenthasmoved<aHREF=\"$url\">here</a>.<p>\n";

print"</body>\n";

print"</html>\n";

##EOF##

ThisprovidesyouwiththefunctionalitytodoredirectstoallURLschemes,i.e.includingtheonewhicharenotdirectlyacceptedbymod_rewrite.Forinstanceyoucannowalsoredirecttonews:newsgroupvia

RewriteRule^anyurlxredirect:news:newsgroup

Notice:Youhavenottoput[R]or[R,L]totheaboverulebecausethexredirect:needtobeexpandedlaterbyourspecial"pipethrough"ruleabove.

ArchiveAccessMultiplexerDescription:

DoyouknowthegreatCPAN(ComprehensivePerlArchiveNetwork)underhttp://www.perl.com/CPAN?ThisdoesaredirecttooneofseveralFTPserversaroundtheworldwhichcarryaCPANmirrorandisapproximatelynearthelocationof

therequestingclient.ActuallythiscanbecalledanFTPaccessmultiplexingservice.WhileCPANrunsviaCGIscripts,howcanasimilarapproachimplementedviamod_rewrite?

Solution:Firstwenoticethatfromversion3.0.0mod_rewritecanalsousethe"ftp:"schemeonredirects.Andsecond,thelocationapproximationcanbedonebyaRewriteMapoverthetop-leveldomainoftheclient.Withatrickychainedrulesetwecanusethistop-leveldomainasakeytoourmultiplexingmap.

RewriteEngineon

RewriteMapmultiplextxt:/path/to/map.cxan

RewriteRule^/CxAN/(.*)%{REMOTE_HOST}::$1[C]

RewriteRule^.+\.([a-zA-Z]+)::(.*)$${multiplex:$1|ftp.default.dom}$2[R,L]

##

##map.cxan--MultiplexingMapforCxAN

##

deftp://ftp.cxan.de/CxAN/

ukftp://ftp.cxan.uk/CxAN/

comftp://ftp.cxan.com/CxAN/

:

##EOF##

Time-DependentRewritingDescription:

Whentricksliketime-dependentcontentshouldhappenalotofwebmastersstilluseCGIscriptswhichdoforinstanceredirectstospecializedpages.Howcanitbedonevia

mod_rewrite?

Solution:TherearealotofvariablesnamedTIME_xxxforrewriteconditions.Inconjunctionwiththespeciallexicographiccomparisonpatterns<STRING,>STRINGand=STRINGwecandotime-dependentredirects:

RewriteEngineon

RewriteCond%{TIME_HOUR}%{TIME_MIN}>0700

RewriteCond%{TIME_HOUR}%{TIME_MIN}<1900

RewriteRule^foo\.html$foo.day.html

RewriteRule^foo\.html$foo.night.html

Thisprovidesthecontentoffoo.day.htmlundertheURLfoo.htmlfrom07:00-19:00andattheremainingtimethecontentsoffoo.night.html.Justanicefeatureforahomepage...

BackwardCompatibilityforYYYYtoXXXXmigrationDescription:

HowcanwemakeURLsbackwardcompatible(stillexistingvirtually)aftermigratingdocument.YYYYtodocument.XXXX,e.g.aftertranslatingabunchof.htmlfilesto.phtml?

Solution:Wejustrewritethenametoitsbasenameandtestforexistenceofthenewextension.Ifitexists,wetakethatname,elsewerewritetheURLtoitsoriginalstate.

#backwardcompatibilityrulesetfor

#rewritingdocument.htmltodocument.phtml

#whenandonlywhendocument.phtmlexists

#butnolongerdocument.html

RewriteEngineon

RewriteBase/~quux/

#parseoutbasename,butrememberthefact

RewriteRule^(.*)\.html$$1[C,E=WasHTML:yes]

#rewritetodocument.phtmlifexists

RewriteCond%{REQUEST_FILENAME}.phtml-f

RewriteRule^(.*)$$1.phtml[S=1]

#elsereversethepreviousbasenamecutout

RewriteCond%{ENV:WasHTML}^yes$

RewriteRule^(.*)$$1.html

ContentHandling

FromOldtoNew(intern)Description:

Assumewehaverecentlyrenamedthepagefoo.htmltobar.htmlandnowwanttoprovidetheoldURLforbackwardcompatibility.ActuallywewantthatusersoftheoldURLevennotrecognizethatthepageswasrenamed.

Solution:WerewritetheoldURLtothenewoneinternallyviathefollowingrule:

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo\.html$bar.html

FromOldtoNew(extern)Description:

Assumeagainthatwehaverecentlyrenamedthepagefoo.htmltobar.htmlandnowwanttoprovidetheoldURLforbackwardcompatibility.ButthistimewewantthattheusersoftheoldURLgethintedtothenewone,i.e.theirbrowsersLocationfieldshouldchange,too.

Solution:WeforceaHTTPredirecttothenewURLwhichleadstoachangeofthebrowsersandthustheusersview:

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo\.html$bar.html[R]

BrowserDependentContentDescription:

Atleastforimportanttop-levelpagesitissometimesnecessarytoprovidetheoptimumofbrowserdependentcontent,i.e.onehastoprovideamaximumversionforthelatestNetscapevariants,aminimumversionfortheLynxbrowsersandaaveragefeatureversionforallothers.

Solution:Wecannotusecontentnegotiationbecausethebrowsersdonotprovidetheirtypeinthatform.InsteadwehavetoactontheHTTPheader"User-Agent".Thefollowingcondigdoesthefollowing:IftheHTTPheader"User-Agent"beginswith"Mozilla/3",thepagefoo.htmlisrewrittentofoo.NS.htmlandandtherewritingstops.Ifthebrowseris"Lynx"or"Mozilla"ofversion1or2theURLbecomesfoo.20.html.Allotherbrowsersreceivepagefoo.32.html.Thisisdonebythefollowingruleset:

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]

DynamicMirrorDescription:

Assumetherearenicewebpagesonremotehostswewanttobringintoournamespace.ForFTPserverswewouldusethemirrorprogramwhichactuallymaintainsanexplicitup-to-

datecopyoftheremotedataonthelocalmachine.ForawebserverwecouldusetheprogramwebcopywhichactssimilarviaHTTP.Butbothtechniqueshaveonemajordrawback:Thelocalcopyisalwaysjustasup-to-dateasoftenweruntheprogram.Itwouldbemuchbetterifthemirrorisnotastaticonewehavetoestablishexplicitly.Insteadwewantadynamicmirrorwithdatawhichgetsupdatedautomaticallywhenthereisneed(updateddataontheremotehost).

Solution:ToprovidethisfeaturewemaptheremotewebpageoreventhecompleteremotewebareatoournamespacebytheuseoftheProxyThroughputfeature(flag[P]):

RewriteEngineon

RewriteBase/~quux/

RewriteRule^hotsheet/(.*)$http://www.tstimpreso.com/hotsheet/

RewriteEngineon

RewriteBase/~quux/

RewriteRule^usa-news\.html$http://www.quux-corp.com/news/index.html

ReverseDynamicMirrorDescription:

...

Solution:

RewriteEngineon

RewriteCond/mirror/of/remotesite/$1-U

RewriteRule^http://www\.remotesite\.com/(.*)$/mirror/of/remotesite/$1

RetrieveMissingDatafromIntranetDescription:

Thisisatrickywayofvirtuallyrunningacorporate(external)Internetwebserver(www.quux-corp.dom),whileactuallykeepingandmaintainingitsdataona(internal)Intranetwebserver(www2.quux-corp.dom)whichisprotectedbyafirewall.Thetrickisthatontheexternalwebserverweretrievetherequesteddataon-the-flyfromtheinternalone.

Solution:First,wehavetomakesurethatourfirewallstillprotectstheinternalwebserverandthatonlytheexternalwebserverisallowedtoretrievedatafromit.Forapacket-filteringfirewallwecouldforinstanceconfigureafirewallrulesetlikethefollowing:

ALLOWHostwww.quux-corp.domPort>1024-->Hostwww2.quux-corp.domPort

DENYHost*Port*-->Hostwww2.quux-corp.domPort

Justadjustittoyouractualconfigurationsyntax.Nowwecanestablishthemod_rewriteruleswhichrequestthemissingdatainthebackgroundthroughtheproxythroughputfeature:

RewriteRule^/~([^/]+)/?(.*)/home/$1/.www/$2

RewriteCond%{REQUEST_FILENAME}!-f

RewriteCond%{REQUEST_FILENAME}!-d

RewriteRule^/home/([^/]+)/.www/?(.*)http://www2.quux-corp.dom/~$1/pub/$2[

LoadBalancingDescription:

Supposewewanttoloadbalancethetraffictowww.foo.comoverwww[0-5].foo.com(atotalof6servers).Howcanthis

bedone?

Solution:Therearealotofpossiblesolutionsforthisproblem.WewilldiscussfirstacommonlyknownDNS-basedvariantandthenthespecialonewithmod_rewrite:

1. DNSRound-RobinThesimplestmethodforload-balancingistousetheDNSround-robinfeatureofBIND.Hereyoujustconfigurewww[0-9].foo.comasusualinyourDNSwithA(address)records,e.g.

www0INA1.2.3.1

www1INA1.2.3.2

www2INA1.2.3.3

www3INA1.2.3.4

www4INA1.2.3.5

www5INA1.2.3.6

Thenyouadditionallyaddthefollowingentry:

wwwINCNAMEwww0.foo.com.

INCNAMEwww1.foo.com.

INCNAMEwww2.foo.com.

INCNAMEwww3.foo.com.

INCNAMEwww4.foo.com.

INCNAMEwww5.foo.com.

INCNAMEwww6.foo.com.

Noticethatthisseemswrong,butisactuallyanintendedfeatureofBINDandcanbeusedinthisway.However,nowwhenwww.foo.comgetsresolved,BINDgivesoutwww0-www6-butinaslightlypermutated/rotatedorder

everytime.Thiswaytheclientsarespreadoverthevariousservers.Butnoticethatthisnotaperfectloadbalancingscheme,becauseDNSresolveinformationgetscachedbytheothernameserversonthenet,soonceaclienthasresolvedwww.foo.comtoaparticularwwwN.foo.com,allsubsequentrequestsalsogotothisparticularnamewwwN.foo.com.Butthefinalresultisok,becausethetotalsumoftherequestsarereallyspreadoverthevariouswebservers.

2. DNSLoad-BalancingAsophisticatedDNS-basedmethodforload-balancingistousetheprogramlbnamedwhichcanbefoundathttp://www.stanford.edu/~schemers/docs/lbnamed/lbnamed.htmlItisaPerl5programinconjunctionwithauxilliarytoolswhichprovidesarealload-balancingforDNS.

3. ProxyThroughputRound-RobinInthisvariantweusemod_rewriteanditsproxythroughputfeature.Firstwededicatewww0.foo.comtobeactuallywww.foo.combyusingasingle

wwwINCNAMEwww0.foo.com.

entryintheDNS.Thenweconvertwww0.foo.comtoaproxy-onlyserver,i.e.weconfigurethismachinesoallarrivingURLsarejustpushedthroughtheinternalproxytooneofthe5otherservers(www1-www5).Toaccomplishthiswefirstestablisharulesetwhichcontactsaloadbalancingscriptlb.plforallURLs.

RewriteEngineon

RewriteMaplbprg:/path/to/lb.pl

RewriteRule^/(.+)$${lb:$1}[P,L]

Thenwewritelb.pl:

#!/path/to/perl

##

##lb.pl--loadbalancingscript

##

$|=1;

$name="www";#thehostnamebase

$first=1;#thefirstserver(not0here,because0ismyself)

$last=5;#thelastserverintheround-robin

$domain="foo.dom";#thedomainname

$cnt=0;

while(<STDIN>){

$cnt=(($cnt+1)%($last+1-$first));

$server=sprintf("%s%d.%s",$name,$cnt+$first,$domain);

print"http://$server/$_";

}

##EOF##

Alastnotice:Whyisthisuseful?Seemslikewww0.foo.comstillisoverloaded?Theanswerisyes,itisoverloaded,butwithplainproxythroughputrequests,only!AllSSI,CGI,ePerl,etc.processingiscompletelydoneontheothermachines.Thisistheessentialpoint.

4. Hardware/TCPRound-Robin

Thereisahardwaresolutionavailable,too.CiscohasabeastcalledLocalDirectorwhichdoesaloadbalancingattheTCP/IPlevel.Actuallythisissomesortofacircuitlevelgatewayinfrontofawebcluster.Ifyouhaveenoughmoneyandreallyneedasolutionwithhighperformance,usethisone.

NewMIME-type,NewServiceDescription:

OnthenettherearealotofniftyCGIprograms.Buttheirusageisusuallyboring,soalotofwebmasterdon'tusethem.EvenApache'sActionhandlerfeatureforMIME-typesisonlyappropriatewhentheCGIprogramsdon'tneedspecialURLs(actuallyPATH_INFOandQUERY_STRINGS)astheirinput.First,letusconfigureanewfiletypewithextension.scgi(forsecureCGI)whichwillbeprocessedbythepopularcgiwrapprogram.TheproblemhereisthatforinstanceweuseaHomogeneousURLLayout(seeabove)afileinsidetheuserhomedirshastheURL/u/user/foo/bar.scgi.ButcgiwrapneedstheURLintheform/~user/foo/bar.scgi/.Thefollowingrulesolvestheproblem:

RewriteRule^/[uge]/([^/]+)/\.www/(.+)\.scgi(.*)...

.../internal/cgi/user/cgiwrap/~$1/$2.scgi$3[NS,T=application/x-http-cgi

Orassumewehavesomemoreniftyprograms:wwwlog(whichdisplaystheaccess.logforaURLsubtreeandwwwidx(whichrunsGlimpseonaURLsubtree).WehavetoprovidetheURLareatotheseprogramssotheyknowonwhichareatheyhavetoacton.Butusuallythisugly,becausetheyareallthetimesstillrequestedfromthatareas,i.e.

typicallywewouldruntheswwidxprogramfromwithin/u/user/foo/viahyperlinkto

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

whichisugly.Becausewehavetohard-codeboththelocationoftheareaandthelocationoftheCGIinsidethehyperlink.Whenwehavetoreorganizethearea,wespendalotoftimechangingthevarioushyperlinks.

Solution:ThesolutionhereistoprovideaspecialnewURLformatwhichautomaticallyleadstotheproperCGIinvocation.Weconfigurethefollowing:

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

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

Nowthehyperlinktosearchat/u/user/foo/readsonly

HREF="*"

whichinternallygetsautomaticallytransformedto

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

ThesameapproachleadstoaninvocationfortheaccesslogCGIprogramwhenthehyperlink:loggetsused.

FromStatictoDynamicDescription:

Howcanwetransformastaticpagefoo.htmlintoa

dynamicvariantfoo.cgiinaseamlessway,i.e.withoutnoticebythebrowser/user.

Solution:WejustrewritetheURLtotheCGI-scriptandforcethecorrectMIME-typesoitgetsreallyrunasaCGI-script.Thiswayarequestto/~quux/foo.htmlinternallyleadstotheinvocationof/~quux/foo.cgi.

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo\.html$foo.cgi[T=application/x-httpd-cgi

On-the-flyContent-RegenerationDescription:

Herecomesareallyesotericfeature:Dynamicallygeneratedbutstaticallyservedpages,i.e.pagesshouldbedeliveredaspurestaticpages(readfromthefilesystemandjustpassedthrough),buttheyhavetobegenerateddynamicallybythewebserverifmissing.ThiswayyoucanhaveCGI-generatedpageswhicharestaticallyservedunlessone(oracronjob)removesthestaticcontents.Thenthecontentsgetsrefreshed.

Solution:Thisisdoneviathefollowingruleset:

RewriteCond%{REQUEST_FILENAME}!-s

RewriteRule^page\.html$page.cgi[T=application/x-httpd-cgi,L]

Herearequesttopage.htmlleadstoainternalrunofacorrespondingpage.cgiifpage.htmlisstillmissingorhasfilesizenull.Thetrickhereisthatpage.cgiisausualCGI

scriptwhich(additionallytoitsSTDOUT)writesitsoutputtothefilepage.html.Onceitwasrun,theserversendsoutthedataofpage.html.Whenthewebmasterwantstoforcearefreshthecontents,hejustremovespage.html(usuallydonebyacronjob).

DocumentWithAutorefreshDescription:

Wouldn'titbenicewhilecreatingacomplexwebpageifthewebbrowserwouldautomaticallyrefreshthepageeverytimewewriteanewversionfromwithinoureditor?Impossible?

Solution:No!WejustcombinetheMIMEmultipartfeature,thewebserverNPHfeatureandtheURLmanipulationpowerofmod_rewrite.First,weestablishanewURLfeature:Addingjust:refreshtoanyURLcausesthistoberefreshedeverytimeitgetsupdatedonthefilesystem.

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

NowwhenwereferencetheURL

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

thisleadstotheinternalinvocationoftheURL

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

TheonlymissingpartistheNPH-CGIscript.Althoughonewouldusuallysay"leftasanexercisetothereader";-)Iwillprovidethis,too.

#!/sw/bin/perl

##

##nph-refresh--NPH/CGIscriptforautorefreshingpages

##Copyright(c)1997RalfS.Engelschall,AllRightsReserved.

##

$|=1;

#splittheQUERY_STRINGvariable

@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=1if($QS_seq'');

$QS_n=3600if($QS_neq'');

if($QS_feq''){

print"HTTP/1.0200OK\n";

print"Content-type:text/html\n\n";

print"&lt;b&gt;ERROR&lt;/b&gt;:Nofilegiven\n";

exit(0);

}

if(!-f$QS_f){

print"HTTP/1.0200OK\n";

print"Content-type:text/html\n\n";

print"&lt;b&gt;ERROR&lt;/b&gt;:File$QS_fnotfound\n";

exit(0);

}

subprint_http_headers_multipart_begin{

print"HTTP/1.0200OK\n";

$bound="ThisRandomString12345";

print"Content-type:multipart/x-mixed-replace;boundary=$bound\n";

&print_http_headers_multipart_next;

}

subprint_http_headers_multipart_next{

print"\n--$bound\n";

}

subprint_http_headers_multipart_end{

print"\n--$bound--\n";

}

subdisplayhtml{

local($buffer)=@_;

$len=length($buffer);

print"Content-type:text/html\n";

print"Content-length:$len\n\n";

print$buffer;

}

subreadfile{

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);

submystat{

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($mtimene$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##

MassVirtualHostingDescription:

The<VirtualHost>featureofApacheisniceandworksgreatwhenyoujusthaveafewdozensvirtualhosts.ButwhenyouareanISPandhavehundredsofvirtualhoststoprovidethisfeatureisnotthebestchoice.

Solution:ToprovidethisfeaturewemaptheremotewebpageoreventhecompleteremotewebareatoournamespacebytheuseoftheProxyThroughputfeature(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

##

:

#usethecanonicalhostnameonredirects,etc.

UseCanonicalNameon

:

#addthevirtualhostinfrontoftheCLF-format

CustomLog/path/to/access_log"%{VHOST}e%h%l%u%t\"%r\"%>s%b"

:

#enabletherewritingengineinthemainserver

RewriteEngineon

#definetwomaps:oneforfixingtheURLandonewhichdefines

#theavailablevirtualhostswiththeircorresponding

#DocumentRoot.

RewriteMaplowercaseint:tolower

RewriteMapvhosttxt:/path/to/vhost.map

#Nowdotheactualvirtualhostmapping

#viaahugeandcomplicatedsinglerule:

#

#1.makesurewedon'tmapforcommonlocations

RewriteCond%{REQUEST_URI}!^/commonurl1/.*

RewriteCond%{REQUEST_URI}!^/commonurl2/.*

:

RewriteCond%{REQUEST_URI}!^/commonurlN/.*

#

#2.makesurewehaveaHostheader,because

#currentlyourapproachonlysupports

#virtualhostingthroughthisheader

RewriteCond%{HTTP_HOST}!^$

#

#3.lowercasethehostname

RewriteCond${lowercase:%{HTTP_HOST}|NONE}^(.+)$

#

#4.lookupthishostnameinvhost.mapand

#rememberitonlywhenitisapath

#(andnot"NONE"fromabove)

RewriteCond${vhost:%1}^(/.*)$

#

#5.finallywecanmaptheURLtoitsdocrootlocation

#andrememberthevirtualhostforloggingpuposes

RewriteRule^/(.*)$%1/$1[E=VHOST:${lowercase:%{HTTP_HOST}}]

:

AccessRestriction

BlockingofRobotsDescription:

Howcanweblockareallyannoyingrobotfromretrievingpagesofaspecificwebarea?A/robots.txtfilecontainingentriesofthe"RobotExclusionProtocol"istypicallynotenoughtogetridofsucharobot.

Solution:WeusearulesetwhichforbidstheURLsofthewebarea/~quux/foo/arc/(perhapsaverydeepdirectoryindexedareawheretherobottraversalwouldcreatebigserverload).Wehavetomakesurethatweforbidaccessonlytotheparticularrobot,i.e.justforbiddingthehostwheretherobotrunsisnotenough.Thiswouldblockusersfromthishost,too.WeaccomplishthisbyalsomatchingtheUser-AgentHTTPheaderinformation.

RewriteCond%{HTTP_USER_AGENT}^NameOfBadRobot.*

RewriteCond%{REMOTE_ADDR}^123\.45\.67\.[8-9]$

RewriteRule^/~quux/foo/arc/.+-[F]

BlockedInline-ImagesDescription:

Assumewehaveunderhttp://www.quux-corp.de/~quux/somepageswithinlinedGIFgraphics.Thesegraphicsarenice,soothersdirectlyincorporatethemviahyperlinkstotheirpages.Wedon'tlikethispracticebecauseitaddsuselesstraffictoourserver.

Solution:Whilewecannot100%protecttheimagesfrominclusion,we

canatleastrestrictthecaseswherethebrowsersendsaHTTPRefererheader.

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]

HostDenyDescription:

Howcanweforbidalistofexternallyconfiguredhostsfromusingourserver?

Solution:ForApache>=1.3b6:

RewriteEngineon

RewriteMaphosts-denytxt:/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]

ForApache<=1.3b6:

RewriteEngineon

RewriteMaphosts-denytxt:/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!Thisisamap,notalist,evenwhenwetreatitassuch.

##mod_rewriteparsesitforkey/valuepairs,soatleasta

##dummyvalue"-"mustbepresentforeachentry.

##

193.102.180.41-

bsdti1.sdm.de-

192.76.162.40-

ProxyDenyDescription:

HowcanweforbidacertainhostorevenauserofaspecialhostfromusingtheApacheproxy?

Solution:Wefirsthavetomakesuremod_rewriteisbelow(!)mod_proxyintheConfigurationfilewhencompilingtheApachewebserver.Thiswayitgetscalledbeforemod_proxy.Thenweconfigurethefollowingforahost-dependentdeny...

RewriteCond%{REMOTE_HOST}^badhost\.mydomain\.com$

RewriteRule!^http://[^/.]\.mydomain.com.*-[F]

...andthisoneforauser@host-dependentdeny:

RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}^badguy@badhost\.mydomain\.com$

RewriteRule!^http://[^/.]\.mydomain.com.*-[F]

SpecialAuthenticationVariantDescription:

Sometimesaveryspecialauthenticationisneeded,forinstanceaauthenticationwhichchecksforasetofexplicitlyconfiguredusers.Onlytheseshouldreceiveaccessandwithoutexplicitprompting(whichwouldoccurwhenusingtheBasicAuthviamod_auth).

Solution:Weusealistofrewriteconditionstoexcludeallexceptourfriends:

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-basedDeflectorDescription:

HowcanweprogramaflexibleURLDeflectorwhichactsonthe"Referer"HTTPheaderandcanbeconfiguredwithasmanyreferringpagesaswelike?

Solution:Usethefollowingreallytrickyruleset...

RewriteMapdeflectortxt:/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]

...inconjunctionwithacorrespondingrewritemap:

##

##deflector.map

##

http://www.badguys.com/bad/index.html-

http://www.badguys.com/bad/index2.html-

http://www.badguys.com/bad/index3.htmlhttp://somewhere.com/

Thisautomaticallyredirectstherequestbacktothereferringpage(when"-"isusedasthevalueinthemap)ortoaspecificURL(whenanURLisspecifiedinthemapasthesecondargument).

Other

ExternalRewritingEngineDescription:

AFAQ:HowcanwesolvetheFOO/BAR/QUUX/etc.problem?Thereseemsnosolutionbytheuseofmod_rewrite...

Solution:UseanexternalRewriteMap,i.e.aprogramwhichactslikeaRewriteMap.ItisrunonceonstartupofApachereceivestherequestedURLsonSTDINandhastoputtheresulting(usuallyrewritten)URLonSTDOUT(sameorder!).

RewriteEngineon

RewriteMapquux-mapprg:/path/to/map.quux.pl

RewriteRule^/~quux/(.*)$/~quux/${quux-map:$1}

#!/path/to/perl

#disablebufferedI/Owhichwouldlead

#todeadloopsfortheApacheserver

$|=1;

#readURLsoneperlinefromstdinand

#generatesubstitutionURLonstdout

while(<>){

s|^foo/|bar/|;

print$_;

}

Thisisademonstration-onlyexampleandjustrewritesallURLs/~quux/foo/...to/~quux/bar/....Actuallyyoucanprogramwhateveryoulike.Butnoticethatwhilesuch

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

mapscanbeusedalsobyanaverageuser,onlythesystemadministratorcandefineit.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

ServerPath

IP

IP IP

IPDNS IP

SSL SSL IP

core DocumentRoot

NameVirtualHost

ServerAlias

ServerName

ServerPath

VirtualHost

<VirtualHost>

IP()NameVirtualHost *IP

*:80 NameVirtualHost IP

<VirtualHost> <VirtualHost>NameVirtualHost(IP ServerName

ServerName DocumentRoot

www.domain.tld www.otherdomain.tld

httpd.conf

NameVirtualHost*:80

<VirtualHost*:80>

ServerNamewww.domain.tld

ServerAliasdomain.tld*.domain.tld

DocumentRoot/www/domain

</VirtualHost>

<VirtualHost*:80>

ServerNamewww.otherdomain.tld

DocumentRoot/www/otherdomain

</VirtualHost>

NameVirtualHost VirtualHost *IP IPIP

<VirtualHost>

ServerAliasdomain.tld*.domain.tld

domain.tld www.domain.tldServerName ServerAlias

<VirtualHost> (<VirtualHost>)

<NameVirtualHost>IP<VirtualHost> ServerName ServerAlias

IP

IP NameVirtualHost <VirtualHost>

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

?

ServerPath

NameVirtualHost111.22.33.44

<VirtualHost111.22.33.44>

ServerNamewww.domain.tld

ServerPath/domain

DocumentRoot/web/domain

</VirtualHost>

? "/domain"URIhttp://www.domain.tld/domain/ Host:

http://www.domain.tld/

http://www.domain.tld/domain/

"file.html"" ../icons/image.gif") /domain/(: "http://www.domain.tld/domain/misc/file.html""/domain/misc/file.html")

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>VirtualHosts

ApacheIP-basedVirtualHostSupport

SeealsoName-basedVirtualHostsSupport

Systemrequirements

AsthetermIP-basedindicates,theservermusthaveadifferentIPaddressforeachIP-basedvirtualhost.Thiscanbeachievedbythemachinehavingseveralphysicalnetworkconnections,orbyuseofvirtualinterfaceswhicharesupportedbymostmodernoperatingsystems(seesystemdocumentationfordetails,thesearefrequentlycalled"ipaliases",andthe"ifconfig"commandismostcommonlyusedtosetthemup).

HowtosetupApache

Therearetwowaysofconfiguringapachetosupportmultiplehosts.Eitherbyrunningaseparatehttpddaemonforeachhostname,orbyrunningasingledaemonwhichsupportsallthevirtualhosts.

Usemultipledaemonswhen:

Therearesecuritypartitioningissues,suchascompany1doesnotwantanyoneatcompany2tobeabletoreadtheirdataexceptviatheweb.Inthiscaseyouwouldneedtwodaemons,eachrunningwithdifferentUser,Group,Listen,andServerRootsettings.YoucanaffordthememoryandfiledescriptorrequirementsoflisteningtoeveryIPaliasonthemachine.It'sonlypossibletoListentothe"wildcard"address,ortospecificaddresses.Soifyouhaveaneedtolistentoaspecificaddressforwhateverreason,thenyouwillneedtolistentoallspecificaddresses.(AlthoughonehttpdcouldlistentoN-1oftheaddresses,andanothercouldlistentotheremainingaddress.)

Useasingledaemonwhen:

Sharingofthehttpdconfigurationbetweenvirtualhostsisacceptable.Themachineservicesalargenumberofrequests,andsotheperformancelossinrunningseparatedaemonsmaybesignificant.

Settingupmultipledaemons

Createaseparatehttpdinstallationforeachvirtualhost.Foreachinstallation,usetheListendirectiveintheconfigurationfiletoselectwhichIPaddress(orvirtualhost)thatdaemonservices.e.g.

Listenwww.smallco.com:80

ItisrecommendedthatyouuseanIPaddressinsteadofahostname(seeDNScaveats).

Settingupasingledaemonwithvirtualhosts

Forthiscase,asinglehttpdwillservicerequestsforthemainserverandallthevirtualhosts.TheVirtualHostdirectiveintheconfigurationfileisusedtosetthevaluesofServerAdmin,ServerName,DocumentRoot,ErrorLogandTransferLogorCustomLogconfigurationdirectivestodifferentvaluesforeachvirtualhost.e.g.

<VirtualHostwww.smallco.com>

ServerAdminwebmaster@mail.smallco.com

DocumentRoot/groups/smallco/www

ServerNamewww.smallco.com

ErrorLog/groups/smallco/logs/error_log

TransferLog/groups/smallco/logs/access_log

</VirtualHost>

<VirtualHostwww.baygroup.org>

ServerAdminwebmaster@mail.baygroup.org

DocumentRoot/groups/baygroup/www

ServerNamewww.baygroup.org

ErrorLog/groups/baygroup/logs/error_log

TransferLog/groups/baygroup/logs/access_log

</VirtualHost>

ItisrecommendedthatyouuseanIPaddressinsteadofahostname(seeDNScaveats).

AlmostanyconfigurationdirectivecanbeputintheVirtualHostdirective,withtheexceptionofdirectivesthatcontrolprocesscreationandafewotherdirectives.TofindoutifadirectivecanbeusedintheVirtualHostdirective,checktheContextusingthedirectiveindex.

SuexecUserGroupmaybeusedinsideaVirtualHostdirectiveifthesuEXECwrapperisused.

SECURITY:Whenspecifyingwheretowritelogfiles,beawareofsomesecurityriskswhicharepresentifanyoneotherthantheuserthatstartsApachehaswriteaccesstothedirectorywhere

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

theyarewritten.Seethesecuritytipsdocumentfordetails.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>VirtualHosts

DynamicallyConfiguredMassVirtualHosting

ThisdocumentdescribeshowtoefficientlyserveanarbitrarynumberofvirtualhostswiththeApachehttpdwebserver.

Motivation

Thetechniquesdescribedhereareofinterestifyourhttpd.confcontainsmany<VirtualHost>sectionsthataresubstantiallythesame,forexample:

NameVirtualHost111.22.33.44

<VirtualHost111.22.33.44>

ServerNamewww.customer-1.com

DocumentRoot/www/hosts/www.customer-1.com/docs

ScriptAlias/cgi-bin//www/hosts/www.customer-1.com/cgi-bin

</VirtualHost>

<VirtualHost111.22.33.44>

ServerNamewww.customer-2.com

DocumentRoot/www/hosts/www.customer-2.com/docs

ScriptAlias/cgi-bin//www/hosts/www.customer-2.com/cgi-bin

</VirtualHost>

#blahblahblah

<VirtualHost111.22.33.44>

ServerNamewww.customer-N.com

DocumentRoot/www/hosts/www.customer-N.com/docs

ScriptAlias/cgi-bin//www/hosts/www.customer-N.com/cgi-bin

</VirtualHost>

Thebasicideaistoreplaceallofthestatic<VirtualHost>configurationswithamechanismthatworksthemoutdynamically.Thishasanumberofadvantages:

1. Yourconfigurationfileissmaller,soApachestartsmorequicklyanduseslessmemory.

2. AddingvirtualhostsissimplyamatterofcreatingtheappropriatedirectoriesinthefilesystemandentriesintheDNS-youdon'tneedtoreconfigureorrestartApache.

Themaindisadvantageisthatyoucannothaveadifferentlogfileforeachvirtualhost;however,ifyouhavemanyvirtualhosts,doingthiscanbeabadideaanyway,becauseofthenumberoffiledescriptorsneeded.Itisbettertologtoapipeorafifo,andarrangefortheprocessattheotherendtodistributethelogstothecustomers.(Thiscanalsobeusedtoaccumulatestatistics,

etc.).

Overview

Avirtualhostisdefinedbytwopiecesofinformation:itsIPaddress,andthecontentsoftheHost:headerintheHTTPrequest.Thedynamicmassvirtualhostingtechniqueusedhereisbasedonautomaticallyinsertingthisinformationintothepathnameofthefilethatisusedtosatisfytherequest.Thiscanbemosteasilydonebyusingmod_vhost_aliaswithApache2.0.Alternatively,mod_rewritecanbeused.Bothofthesemodulesaredisabledbydefault;youmustenableoneofthemwhenconfiguringandbuildingApacheifyouwanttousethistechnique.

Acoupleofthingsneedtobe`faked'tomakethedynamicvirtualhostlooklikeanormalone.Themostimportantistheservername,whichisusedbyApachetogenerateself-referentialURLsetc.ItisconfiguredwiththeServerNamedirective,anditisavailabletoCGIsviatheSERVER_NAMEenvironmentvariable.TheactualvalueusedatruntimeiscontrolledbytheUseCanonicalNamesetting.WithUseCanonicalNameOff,theservernameistakenfromthecontentsoftheHost:headerintherequest.WithUseCanonicalNameDNS,itistakenfromareverseDNSlookupofthevirtualhost'sIPaddress.Theformersettingisusedforname-baseddynamicvirtualhosting,andthelatterisusedforIP-basedhosting.IfApachecannotworkouttheservernamebecausethereisnoHost:header,ortheDNSlookupfails,thenthevalueconfiguredwithServerNameisusedinstead.

Theotherthingto`fake'isthedocumentroot(configuredwithDocumentRootandavailabletoCGIsviatheDOCUMENT_ROOTenvironmentvariable).Inanormalconfiguration,thisisusedbythecoremodulewhenmappingURIstofilenames,butwhentheserverisconfiguredtododynamicvirtualhosting,thatjobmustbetakenoverbyanothermodule(eithermod_vhost_aliasormod_rewrite),whichhasadifferentwayofdoingthemapping.

NeitherofthesemodulesisresponsibleforsettingtheDOCUMENT_ROOTenvironmentvariablesoifanyCGIsorSSIdocumentsmakeuseofit,theywillgetamisleadingvalue.

SimpleDynamicVirtualHosts

Thisextractfromhttpd.confimplementsthevirtualhostarrangementoutlinedintheMotivationsectionabove,butinagenericfashionusingmod_vhost_alias.

#gettheservernamefromtheHost:header

UseCanonicalNameOff

#thislogformatcanbesplitper-virtual-hostbasedonthe

firstfield

LogFormat"%V%h%l%u%t\"%r\"%s%b"vcommon

CustomLoglogs/access_logvcommon

#includetheservernameinthefilenamesusedtosatisfy

requests

VirtualDocumentRoot/www/hosts/%0/docs

VirtualScriptAlias/www/hosts/%0/cgi-bin

ThisconfigurationcanbechangedintoanIP-basedvirtualhostingsolutionbyjustturningUseCanonicalNameOffintoUseCanonicalNameDNS.TheservernamethatisinsertedintothefilenameisthenderivedfromtheIPaddressofthevirtualhost.

AVirtuallyHostedHomepagesSystem

Thisisanadjustmentoftheabovesystem,tailoredforanISP'shomepagesserver.Usingaslightlymorecomplicatedconfiguration,wecanselectsubstringsoftheservernametouseinthefilenamesothat,forexample,thedocumentsforwww.user.isp.comarefoundin/home/user/.Itusesasinglecgi-bindirectoryinsteadofonepervirtualhost.

#allthepreliminarystuffisthesameasabove,then

#includepartoftheservernameinthefilenames

VirtualDocumentRoot/www/hosts/%2/docs

#singlecgi-bindirectory

ScriptAlias/cgi-bin//www/std-cgi/

ThereareexamplesofmorecomplicatedVirtualDocumentRootsettingsinthemod_vhost_aliasdocumentation.

UsingMultipleVirtualHostingSystemsontheSameServer

Withmorecomplicatedsetups,youcanuseApache'snormal<VirtualHost>directivestocontrolthescopeofthevariousvirtualhostingconfigurations.Forexample,youcouldhaveoneIPaddressforgeneralcustomers'homepages,andanotherforcommercialcustomers,withthefollowingsetup.Thiscan,ofcourse,becombinedwithconventional<VirtualHost>configurationsections.

UseCanonicalNameOff

LogFormat"%V%h%l%u%t\"%r\"%s%b"vcommon

<Directory/www/commercial>

OptionsFollowSymLinks

AllowOverrideAll

</Directory>

<Directory/www/homepages>

OptionsFollowSymLinks

AllowOverrideNone

</Directory>

<VirtualHost111.22.33.44>

ServerNamewww.commercial.isp.com

CustomLoglogs/access_log.commercialvcommon

VirtualDocumentRoot/www/commercial/%0/docs

VirtualScriptAlias/www/commercial/%0/cgi-bin

</VirtualHost>

<VirtualHost111.22.33.45>

ServerNamewww.homepages.isp.com

CustomLoglogs/access_log.homepagesvcommon

VirtualDocumentRoot/www/homepages/%0/docs

ScriptAlias/cgi-bin//www/std-cgi/

</VirtualHost>

MoreEfficientIP-BasedVirtualHosting

TheconfigurationchangessuggestedtoturnthefirstexampleintoanIP-basedvirtualhostingsetupresultinaratherinefficientsetup.AnewDNSlookupisrequiredforeveryrequest.Toavoidthisoverhead,thefilesystemcanbearrangedtocorrespondtotheIPaddresses,insteadoftothehostnames,therebynegatingtheneedforaDNSlookup.Loggingwillalsohavetobeadjustedtofitthissystem.

#gettheservernamefromthereverseDNSoftheIPaddress

UseCanonicalNameDNS

#includetheIPaddressinthelogssotheymaybesplit

LogFormat"%A%h%l%u%t\"%r\"%s%b"vcommon

CustomLoglogs/access_logvcommon

#includetheIPaddressinthefilenames

VirtualDocumentRootIP/www/hosts/%0/docs

VirtualScriptAliasIP/www/hosts/%0/cgi-bin

SimpleDynamicVirtualHostsUsingmod_rewrite

Thisextractfromhttpd.confdoesthesamethingasthefirstexample.Thefirsthalfisverysimilartothecorrespondingpartabove,exceptforsomechanges,requiredforbackwardcompatibilityandtomakethemod_rewritepartworkproperly;thesecondhalfconfiguresmod_rewritetodotheactualwork.

Thereareacoupleofespeciallytrickybits:bydefault,mod_rewriterunsbeforeotherURItranslationmodules(mod_aliasetc.)-soifyouwishtousethesemodules,mod_rewritemustbeconfiguredtoaccommodatethem.Also,somemagicisrequiredtodoaper-dynamic-virtual-hostequivalentofScriptAlias.

#gettheservernamefromtheHost:header

UseCanonicalNameOff

#splittablelogs

LogFormat"%{Host}i%h%l%u%t\"%r\"%s%b"vcommon

CustomLoglogs/access_logvcommon

<Directory/www/hosts>

#ExecCGIisneededherebecausewecan'tforce

#CGIexecutioninthewaythatScriptAliasdoes

OptionsFollowSymLinksExecCGI

</Directory>

#nowforthehardbit

RewriteEngineOn

#aServerNamederivedfromaHost:headermaybeanycaseat

all

RewriteMaplowercaseint:tolower

##dealwithnormaldocumentsfirst:

#allowAlias/icons/towork-repeatforotheraliases

RewriteCond%{REQUEST_URI}!^/icons/

#allowCGIstowork

RewriteCond%{REQUEST_URI}!^/cgi-bin/

#dothemagic

RewriteRule^/(.*)$/www/hosts/${lowercase:%

{SERVER_NAME}}/docs/$1

##andnowdealwithCGIs-wehavetoforceaMIMEtype

RewriteCond%{REQUEST_URI}^/cgi-bin/

RewriteRule^/(.*)$/www/hosts/${lowercase:%{SERVER_NAME}}/cgi-

bin/$1[T=application/x-httpd-cgi]

#that'sit!

AHomepagesSystemUsingmod_rewrite

Thisdoesthesamethingasthesecondexample.

RewriteEngineon

RewriteMaplowercaseint:tolower

#allowCGIstowork

RewriteCond%{REQUEST_URI}!^/cgi-bin/

#checkthehostnameisrightsothattheRewriteRuleworks

RewriteCond${lowercase:%{SERVER_NAME}}^www\.[a-z-

]+\.isp\.com$

#concatenatethevirtualhostnameontothestartoftheURI

#the[C]meansdothenextrewriteontheresultofthisone

RewriteRule^(.+)${lowercase:%{SERVER_NAME}}$1[C]

#nowcreatetherealfilename

RewriteRule^www\.([a-z-]+)\.isp\.com/(.*)/home/$1/$2

#definetheglobalCGIdirectory

ScriptAlias/cgi-bin//www/std-cgi/

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

UsingaSeparateVirtualHostConfigurationFile

Thisarrangementusesmoreadvancedmod_rewritefeaturestoworkoutthetranslationfromvirtualhosttodocumentroot,fromaseparateconfigurationfile.Thisprovidesmoreflexibility,butrequiresmorecomplicatedconfiguration.

Thevhost.mapfileshouldlooksomethinglikethis:

www.customer-1.com/www/customers/1

www.customer-2.com/www/customers/2

#...

www.customer-N.com/www/customers/N

Thehttpd.confshouldcontainthefollowing:

RewriteEngineon

RewriteMaplowercaseint:tolower

#definethemapfile

RewriteMapvhosttxt:/www/conf/vhost.map

#dealwithaliasesasabove

RewriteCond%{REQUEST_URI}!^/icons/

RewriteCond%{REQUEST_URI}!^/cgi-bin/

RewriteCond${lowercase:%{SERVER_NAME}}^(.+)$

#thisdoesthefile-basedremap

RewriteCond${vhost:%1}^(/.*)$

RewriteRule^/(.*)$%1/docs/$1

RewriteCond%{REQUEST_URI}^/cgi-bin/

RewriteCond${lowercase:%{SERVER_NAME}}^(.+)$

RewriteCond${vhost:%1}^(/.*)$

RewriteRule^/(.*)$%1/cgi-bin/$1[T=application/x-httpd-cgi]

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>VirtualHosts

VirtualHostExamples

Thisdocumentattemptstoanswerthecommonly-askedquestionsaboutsettingupvirtualhosts.Thesescenariosarethoseinvolvingmultiplewebsitesrunningonasingleserver,vianame-basedorIP-basedvirtualhosts.

Runningseveralname-basedwebsitesonasingleIPaddress.

YourserverhasasingleIPaddress,andmultiplealiases(CNAMES)pointtothismachineinDNS.Youwanttorunawebserverforwww.example1.comandwww.example2.orgonthismachine.

Note

CreatingvirtualhostconfigurationsonyourApacheserverdoesnotmagicallycauseDNSentriestobecreatedforthosehostnames.YoumusthavethenamesinDNS,resolvingtoyourIPaddress,ornobodyelsewillbeabletoseeyourwebsite.Youcanputentriesinyourhostsfileforlocaltesting,butthatwillworkonlyfromthemachinewiththosehostsentries.

Serverconfiguration#EnsurethatApachelistensonport80

Listen80

#ListenforvirtualhostrequestsonallIPaddresses

NameVirtualHost*:80

<VirtualHost*:80>

DocumentRoot/www/example1

ServerNamewww.example1.com

#Otherdirectiveshere

</VirtualHost>

<VirtualHost*:80>

DocumentRoot/www/example2

ServerNamewww.example2.org

#Otherdirectiveshere

</VirtualHost>

Theasterisksmatchalladdresses,sothemainserverservesno

requests.Duetothefactthatwww.example1.comisfirstintheconfigurationfile,ithasthehighestpriorityandcanbeseenasthedefaultorprimaryserver.ThatmeansthatifarequestisreceivedthatdoesnotmatchoneofthespecifiedServerNamedirectives,itwillbeservedbythisfirstVirtualHost.

Note

Youcan,ifyouwish,replace*withtheactualIPaddressofthesystem.Inthatcase,theargumenttoVirtualHostmustmatchtheargumenttoNameVirtualHost:

NameVirtualHost172.20.30.40

<VirtualHost172.20.30.40>

#etc...

However,itisadditionallyusefultouse*onsystemswheretheIPaddressisnotpredictable-forexampleifyouhaveadynamicIPaddresswithyourISP,andyouareusingsomevarietyofdynamicDNSsolution.Since*matchesanyIPaddress,thisconfigurationwouldworkwithoutchangeswheneveryourIPaddresschanges.

Theaboveconfigurationiswhatyouwillwanttouseinalmostallname-basedvirtualhostingsituations.Theonlythingthatthisconfigurationwillnotworkfor,infact,iswhenyouareservingdifferentcontentbasedondifferingIPaddressesorports.

Name-basedhostsonmorethanoneIPaddress.

Note

AnyofthetechniquesdiscussedherecanbeextendedtoanynumberofIPaddresses.

TheserverhastwoIPaddresses.Onone(172.20.30.40),wewillservethe"main"server,server.domain.comandontheother(172.20.30.50),wewillservetwoormorevirtualhosts.

ServerconfigurationListen80

#Thisisthe"main"serverrunningon172.20.30.40

ServerNameserver.domain.com

DocumentRoot/www/mainserver

#Thisistheotheraddress

NameVirtualHost172.20.30.50

<VirtualHost172.20.30.50>

DocumentRoot/www/example1

ServerNamewww.example1.com

#Otherdirectiveshere...

</VirtualHost>

<VirtualHost172.20.30.50>

DocumentRoot/www/example2

ServerNamewww.example2.org

#Otherdirectiveshere...

</VirtualHost>

Anyrequesttoanaddressotherthan172.20.30.50willbeservedfromthemainserver.Arequestto172.20.30.50withanunknownhostname,ornoHost:header,willbeservedfromwww.example1.com.

ServingthesamecontentondifferentIPaddresses(suchasaninternalandexternaladdress).

TheservermachinehastwoIPaddresses(192.168.1.1and172.20.30.40).Themachineissittingbetweenaninternal(intranet)networkandanexternal(internet)network.Outsideofthenetwork,thenameserver.example.comresolvestotheexternaladdress(172.20.30.40),butinsidethenetwork,thatsamenameresolvestotheinternaladdress(192.168.1.1).

Theservercanbemadetorespondtointernalandexternalrequestswiththesamecontent,withjustoneVirtualHostsection.

ServerconfigurationNameVirtualHost192.168.1.1

NameVirtualHost172.20.30.40

<VirtualHost192.168.1.1172.20.30.40>

DocumentRoot/www/server1

ServerNameserver.example.com

ServerAliasserver

</VirtualHost>

NowrequestsfrombothnetworkswillbeservedfromthesameVirtualHost.

Note:

Ontheinternalnetwork,onecanjustusethenameserverratherthanthefullyqualifiedhostnameserver.example.com.

Notealsothat,intheaboveexample,youcanreplacethelistofIPaddresseswith*,whichwillcausetheservertorespondthesameonalladdresses.

Runningdifferentsitesondifferentports.

YouhavemultipledomainsgoingtothesameIPandalsowanttoservemultipleports.Bydefiningtheportsinthe"NameVirtualHost"tag,youcanallowthistowork.Ifyoutryusing<VirtualHostname:port>withouttheNameVirtualHostname:portoryoutrytousetheListendirective,yourconfigurationwillnotwork.

ServerconfigurationListen80

Listen8080

NameVirtualHost172.20.30.40:80

NameVirtualHost172.20.30.40:8080

<VirtualHost172.20.30.40:80>

ServerNamewww.example1.com

DocumentRoot/www/domain-80

</VirtualHost>

<VirtualHost172.20.30.40:8080>

ServerNamewww.example1.com

DocumentRoot/www/domain-8080

</VirtualHost>

<VirtualHost172.20.30.40:80>

ServerNamewww.example2.org

DocumentRoot/www/otherdomain-80

</VirtualHost>

<VirtualHost172.20.30.40:8080>

ServerNamewww.example2.org

DocumentRoot/www/otherdomain-8080

</VirtualHost>

IP-basedvirtualhosting

TheserverhastwoIPaddresses(172.20.30.40and172.20.30.50)whichresolvetothenameswww.example1.comandwww.example2.orgrespectively.

ServerconfigurationListen80

<VirtualHost172.20.30.40>

DocumentRoot/www/example1

ServerNamewww.example1.com

</VirtualHost>

<VirtualHost172.20.30.50>

DocumentRoot/www/example2

ServerNamewww.example2.org

</VirtualHost>

Requestsforanyaddressnotspecifiedinoneofthe<VirtualHost>directives(suchaslocalhost,forexample)willgotothemainserver,ifthereisone.

Mixedport-basedandip-basedvirtualhosts

TheservermachinehastwoIPaddresses(172.20.30.40and172.20.30.50)whichresolvetothenameswww.example1.comandwww.example2.orgrespectively.Ineachcase,wewanttorunhostsonports80and8080.

ServerconfigurationListen172.20.30.40:80

Listen172.20.30.40:8080

Listen172.20.30.50:80

Listen172.20.30.50:8080

<VirtualHost172.20.30.40:80>

DocumentRoot/www/example1-80

ServerNamewww.example1.com

</VirtualHost>

<VirtualHost172.20.30.40:8080>

DocumentRoot/www/example1-8080

ServerNamewww.example1.com

</VirtualHost>

<VirtualHost172.20.30.50:80>

DocumentRoot/www/example2-80

ServerNamewww.example1.org

</VirtualHost>

<VirtualHost172.20.30.50:8080>

DocumentRoot/www/example2-8080

ServerNamewww.example2.org

</VirtualHost>

Mixedname-basedandIP-basedvhosts

Onsomeofmyaddresses,Iwanttodoname-basedvirtualhosts,andonothers,IP-basedhosts.

ServerconfigurationListen80

NameVirtualHost172.20.30.40

<VirtualHost172.20.30.40>

DocumentRoot/www/example1

ServerNamewww.example1.com

</VirtualHost>

<VirtualHost172.20.30.40>

DocumentRoot/www/example2

ServerNamewww.example2.org

</VirtualHost>

<VirtualHost172.20.30.40>

DocumentRoot/www/example3

ServerNamewww.example3.net

</VirtualHost>

#IP-based

<VirtualHost172.20.30.50>

DocumentRoot/www/example4

ServerNamewww.example4.edu

</VirtualHost>

<VirtualHost172.20.30.60>

DocumentRoot/www/example5

ServerNamewww.example5.gov

</VirtualHost>

UsingVirtual_hostandmod_proxytogether

Thefollowingexampleallowsafront-endmachinetoproxyavirtualhostthroughtoaserverrunningonanothermachine.Intheexample,avirtualhostofthesamenameisconfiguredonamachineat192.168.111.2.TheProxyPreserveHostOndirectiveisusedsothatthedesiredhostnameispassedthrough,incaseweareproxyingmultiplehostnamestoasinglemachine.

<VirtualHost*:*>

ProxyPreserveHostOn

ProxyPass/http://192.168.111.2/

ProxyPassReverse/http://192.168.111.2/

ServerNamehostname.example.com

</VirtualHost>

Using_default_vhosts

_default_vhostsforallportsCatchingeveryrequesttoanyunspecifiedIPaddressandport,i.e.,anaddress/portcombinationthatisnotusedforanyothervirtualhost.

Serverconfiguration<VirtualHost_default_:*>

DocumentRoot/www/default

</VirtualHost>

Usingsuchadefaultvhostwithawildcardporteffectivelypreventsanyrequestgoingtothemainserver.

Adefaultvhostneverservesarequestthatwassenttoanaddress/portthatisusedforname-basedvhosts.IftherequestcontainedanunknownornoHost:headeritisalwaysservedfromtheprimaryname-basedvhost(thevhostforthataddress/portappearingfirstintheconfigurationfile).

YoucanuseAliasMatchorRewriteRuletorewriteanyrequesttoasingleinformationpage(orscript).

_default_vhostsfordifferentportsSameassetup1,buttheserverlistensonseveralportsandwewanttouseasecond_default_vhostforport80.

Serverconfiguration<VirtualHost_default_:80>

DocumentRoot/www/default80

#...

</VirtualHost>

<VirtualHost_default_:*>

DocumentRoot/www/default

#...

</VirtualHost>

Thedefaultvhostforport80(whichmustappearbeforeanydefaultvhostwithawildcardport)catchesallrequeststhatweresenttoanunspecifiedIPaddress.Themainserverisneverusedtoservearequest.

_default_vhostsforoneportWewanttohaveadefaultvhostforport80,butnootherdefaultvhosts.

Serverconfiguration<VirtualHost_default_:80>

DocumentRoot/www/default

...

</VirtualHost>

Arequesttoanunspecifiedaddressonport80isservedfromthedefaultvhostanyotherrequesttoanunspecifiedaddressandportisservedfromthemainserver.

Migratinganame-basedvhosttoanIP-basedvhost

Thename-basedvhostwiththehostnamewww.example2.org(fromourname-basedexample,setup2)shouldgetitsownIPaddress.ToavoidproblemswithnameserversorproxieswhocachedtheoldIPaddressforthename-basedvhostwewanttoprovidebothvariantsduringamigrationphase.Thesolutioniseasy,becausewecansimplyaddthenewIPaddress(172.20.30.50)totheVirtualHostdirective.

ServerconfigurationListen80

ServerNamewww.example1.com

DocumentRoot/www/example1

NameVirtualHost172.20.30.40

<VirtualHost172.20.30.40172.20.30.50>

DocumentRoot/www/example2

ServerNamewww.example2.org

#...

</VirtualHost>

<VirtualHost172.20.30.40>

DocumentRoot/www/example3

ServerNamewww.example3.net

ServerAlias*.example3.net

#...

</VirtualHost>

Thevhostcannowbeaccessedthroughthenewaddress(asanIP-basedvhost)andthroughtheoldaddress(asaname-basedvhost).

UsingtheServerPathdirective

Wehaveaserverwithtwoname-basedvhosts.InordertomatchthecorrectvirtualhostaclientmustsendthecorrectHost:header.OldHTTP/1.0clientsdonotsendsuchaheaderandApachehasnocluewhatvhosttheclienttriedtoreach(andservestherequestfromtheprimaryvhost).ToprovideasmuchbackwardcompatibilityaspossiblewecreateaprimaryvhostwhichreturnsasinglepagecontaininglinkswithanURLprefixtothename-basedvirtualhosts.

ServerconfigurationNameVirtualHost172.20.30.40

<VirtualHost172.20.30.40>

#primaryvhost

DocumentRoot/www/subdomain

RewriteEngineOn

RewriteRule^/.*/www/subdomain/index.html

#...

</VirtualHost>

<VirtualHost172.20.30.40>

DocumentRoot/www/subdomain/sub1

ServerNamewww.sub1.domain.tld

ServerPath/sub1/

RewriteEngineOn

RewriteRule^(/sub1/.*)/www/subdomain$1

#...

</VirtualHost>

<VirtualHost172.20.30.40>

DocumentRoot/www/subdomain/sub2

ServerNamewww.sub2.domain.tld

ServerPath/sub2/

RewriteEngineOn

RewriteRule^(/sub2/.*)/www/subdomain$1

#...

</VirtualHost>

DuetotheServerPathdirectivearequesttotheURLhttp://www.sub1.domain.tld/sub1/isalwaysservedfromthesub1-vhost.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ArequesttotheURLhttp://www.sub1.domain.tld/isonlyservedfromthesub1-vhostiftheclientsentacorrectHost:header.IfnoHost:headerissenttheclientgetstheinformationpagefromtheprimaryhost.Pleasenotethatthereisoneoddity:Arequesttohttp://www.sub2.domain.tld/sub1/isalsoservedfromthesub1-vhostiftheclientsentnoHost:header.TheRewriteRuledirectivesareusedtomakesurethataclientwhichsentacorrectHost:headercanusebothURLvariants,i.e.,withorwithoutURLprefix.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>VirtualHosts

AnIn-DepthDiscussionofVirtualHostMatching

ThevirtualhostcodewascompletelyrewritteninApache1.3.ThisdocumentattemptstoexplainexactlywhatApachedoeswhendecidingwhatvirtualhosttoserveahitfrom.WiththehelpofthenewNameVirtualHostdirectivevirtualhostconfigurationshouldbealoteasierandsaferthanwithversionspriorto1.3.

Ifyoujustwanttomakeitworkwithoutunderstandinghow,herearesomeexamples.

ConfigFileParsing

Thereisamain_serverwhichconsistsofallthedefinitionsappearingoutsideof<VirtualHost>sections.Therearevirtualservers,calledvhosts,whicharedefinedby<VirtualHost>sections.

ThedirectivesListen,ServerName,ServerPath,andServerAliascanappearanywherewithinthedefinitionofaserver.However,eachappearanceoverridesthepreviousappearance(withinthatserver).

ThedefaultvalueoftheListenfieldformain_serveris80.Themain_serverhasnodefaultServerPath,orServerAlias.ThedefaultServerNameisdeducedfromtheserver'sIPaddress.

Themain_serverListendirectivehastwofunctions.OnefunctionistodeterminethedefaultnetworkportApachewillbindto.ThesecondfunctionistospecifytheportnumberwhichisusedinabsoluteURIsduringredirects.

Unlikethemain_server,vhostportsdonotaffectwhatportsApachelistensforconnectionson.

EachaddressappearingintheVirtualHostdirectivecanhaveanoptionalport.Iftheportisunspecifieditdefaultstothevalueofthemain_server'smostrecentListenstatement.Thespecialport*indicatesawildcardthatmatchesanyport.Collectivelytheentiresetofaddresses(includingmultipleArecordresultsfromDNSlookups)arecalledthevhost'saddressset.

UnlessaNameVirtualHostdirectiveisusedforaspecificIPaddressthefirstvhostwiththataddressistreatedasanIP-basedvhost.TheIPaddresscanalsobethewildcard*.

Ifname-basedvhostsshouldbeusedaNameVirtualHost

directivemustappearwiththeIPaddresssettobeusedforthename-basedvhosts.Inotherwords,youmustspecifytheIPaddressthatholdsthehostnamealiases(CNAMEs)foryourname-basedvhostsviaaNameVirtualHostdirectiveinyourconfigurationfile.

MultipleNameVirtualHostdirectivescanbeusedeachwithasetofVirtualHostdirectivesbutonlyoneNameVirtualHostdirectiveshouldbeusedforeachspecificIP:portpair.

TheorderingofNameVirtualHostandVirtualHostdirectivesisnotimportantwhichmakesthefollowingtwoexamplesidentical(onlytheorderoftheVirtualHostdirectivesforoneaddresssetisimportant,seebelow):

NameVirtualHost

111.22.33.44

<VirtualHost

111.22.33.44>

#serverA

...

</VirtualHost>

<VirtualHost

111.22.33.44>

#serverB

...

</VirtualHost>

NameVirtualHost

111.22.33.55

<VirtualHost

111.22.33.55>

#serverC

...

</VirtualHost>

<VirtualHost

111.22.33.55>

#serverD

...

</VirtualHost>

<VirtualHost

111.22.33.44>

#serverA

</VirtualHost>

<VirtualHost

111.22.33.55>

#serverC

...

</VirtualHost>

<VirtualHost

111.22.33.44>

#serverB

...

</VirtualHost>

<VirtualHost

111.22.33.55>

#serverD

...

</VirtualHost>

NameVirtualHost

111.22.33.44

NameVirtualHost

111.22.33.55

(Toaidthereadabilityofyourconfigurationyoushouldprefertheleftvariant.)

AfterparsingtheVirtualHostdirective,thevhostserverisgivenadefaultListenequaltotheportassignedtothefirstnameinitsVirtualHostdirective.

ThecompletelistofnamesintheVirtualHostdirectivearetreatedjustlikeaServerAlias(butarenotoverriddenbyanyServerAliasstatement)ifallnamesresolvetothesameaddressset.NotethatsubsequentListenstatementsforthisvhostwillnotaffecttheportsassignedintheaddressset.

DuringinitializationalistforeachIPaddressisgeneratedandinsertedintoanhashtable.IftheIPaddressisusedinaNameVirtualHostdirectivethelistcontainsallname-basedvhostsforthegivenIPaddress.IftherearenovhostsdefinedforthataddresstheNameVirtualHostdirectiveisignoredandanerrorislogged.ForanIP-basedvhostthelistinthehashtableisempty.

DuetoafasthashingfunctiontheoverheadofhashinganIPaddressduringarequestisminimalandalmostnotexistent.AdditionallythetableisoptimizedforIPaddresseswhichvaryinthelastoctet.

Foreveryvhostvariousdefaultvaluesareset.Inparticular:

1. IfavhosthasnoServerAdmin,Timeout,KeepAliveTimeout,KeepAlive,MaxKeepAliveRequests,ReceiveBufferSize,orSendBufferSizedirectivethentherespectivevalueisinheritedfromthemain_server.(Thatis,inheritedfromwhateverthefinalsettingofthatvalueisinthemain_server.)

2. The"lookupdefaults"thatdefinethedefaultdirectorypermissionsforavhostaremergedwiththoseofthemain_server.Thisincludesanyper-directoryconfigurationinformationforanymodule.

3. Theper-serverconfigsforeachmodulefromthemain_serveraremergedintothevhostserver.

Essentially,themain_serveristreatedas"defaults"ora"base"onwhichtobuildeachvhost.Butthepositioningofthesemain_serverdefinitionsintheconfigfileislargelyirrelevant--theentireconfigofthemain_serverhasbeenparsedwhenthisfinalmergingoccurs.Soevenifamain_serverdefinitionappearsafteravhostdefinitionitmightaffectthevhostdefinition.

Ifthemain_serverhasnoServerNameatthispoint,thenthehostnameofthemachinethathttpdisrunningonisusedinstead.Wewillcallthemain_serveraddresssetthoseIPaddressesreturnedbyaDNSlookupontheServerNameofthemain_server.

ForanyundefinedServerNamefields,aname-basedvhostdefaultstotheaddressgivenfirstintheVirtualHoststatementdefiningthevhost.

Anyvhostthatincludesthemagic_default_wildcardisgiventhesameServerNameasthemain_server.

VirtualHostMatching

Theserverdetermineswhichvhosttouseforarequestasfollows:

HashtablelookupWhentheconnectionisfirstmadebyaclient,theIPaddresstowhichtheclientconnectedislookedupintheinternalIPhashtable.

Ifthelookupfails(theIPaddresswasn'tfound)therequestisservedfromthe_default_vhostifthereissuchavhostfortheporttowhichtheclientsenttherequest.Ifthereisnomatching_default_vhosttherequestisservedfromthemain_server.

IftheIPaddressisnotfoundinthehashtablethenthematchagainsttheportnumbermayalsoresultinanentrycorrespondingtoaNameVirtualHost*,whichissubsequentlyhandledlikeothername-basedvhosts.

Ifthelookupsucceeded(acorrespondinglistfortheIPaddresswasfound)thenextstepistodecideifwehavetodealwithanIP-basedoraname-basevhost.

IP-basedvhostIftheentrywefoundhasanemptynamelistthenwehavefoundanIP-basedvhost,nofurtheractionsareperformedandtherequestisservedfromthatvhost.

Name-basedvhostIftheentrycorrespondstoaname-basedvhostthenamelistcontainsoneormorevhoststructures.ThislistcontainsthevhostsinthesameorderastheVirtualHostdirectivesappearintheconfigfile.

Thefirstvhostonthislist(thefirstvhostintheconfigfilewiththespecifiedIPaddress)hasthehighestpriorityandcatchesanyrequesttoanunknownservernameorarequestwithoutaHost:headerfield.

IftheclientprovidedaHost:headerfieldthelistissearchedforamatchingvhostandthefirsthitonaServerNameorServerAliasistakenandtherequestisservedfromthatvhost.AHost:headerfieldcancontainaportnumber,butApachealwaysmatchesagainsttherealporttowhichtheclientsenttherequest.

IftheclientsubmittedaHTTP/1.0requestwithoutHost:headerfieldwedon'tknowtowhatservertheclienttriedtoconnectandanyexistingServerPathismatchedagainsttheURIfromtherequest.Thefirstmatchingpathonthelistisusedandtherequestisservedfromthatvhost.

IfnomatchingvhostcouldbefoundtherequestisservedfromthefirstvhostwithamatchingportnumberthatisonthelistfortheIPtowhichtheclientconnected(asalreadymentionedbefore).

PersistentconnectionsTheIPlookupdescribedaboveisonlydoneonceforaparticularTCP/IPsessionwhilethenamelookupisdoneoneveryrequestduringaKeepAlive/persistentconnection.Inotherwordsaclientmayrequestpagesfromdifferentname-basedvhostsduringasinglepersistentconnection.

AbsoluteURIIftheURIfromtherequestisanabsoluteURI,anditshostnameandportmatchthemainserveroroneoftheconfiguredvirtualhostsandmatchtheaddressandporttowhichtheclientsentthe

request,thenthescheme/hostname/portprefixisstrippedoffandtheremainingrelativeURIisservedbythecorrespondingmainserverorvirtualhost.Ifitdoesnotmatch,thentheURIremainsuntouchedandtherequestistakentobeaproxyrequest.

ObservationsAname-basedvhostcanneverinterferewithanIP-basevhostandviceversa.IP-basedvhostscanonlybereachedthroughanIPaddressofitsownaddresssetandneverthroughanyotheraddress.Thesameappliestoname-basedvhosts,theycanonlybereachedthroughanIPaddressofthecorrespondingaddresssetwhichmustbedefinedwithaNameVirtualHostdirective.ServerAliasandServerPathchecksareneverperformedforanIP-basedvhost.Theorderofname-/IP-based,the_default_vhostandtheNameVirtualHostdirectivewithintheconfigfileisnotimportant.Onlytheorderingofname-basedvhostsforaspecificaddresssetissignificant.Theonename-basedvhoststhatcomesfirstintheconfigurationfilehasthehighestpriorityforitscorrespondingaddressset.ForsecurityreasonstheportnumbergiveninaHost:headerfieldisneverusedduringthematchingprocess.Apachealwaysusestherealporttowhichtheclientsenttherequest.IfaServerPathdirectiveexistswhichisaprefixofanotherServerPathdirectivethatappearslaterintheconfigurationfile,thentheformerwillalwaysbematchedandthelatterwillneverbematched.(ThatisassumingthatnoHost:headerfieldwasavailabletodisambiguatethetwo.)IftwoIP-basedvhostshaveanaddressincommon,thevhostappearingfirstintheconfigfileisalwaysmatched.Suchathingmighthappeninadvertently.Theserverwillgivea

warningintheerrorlogfilewhenitdetectsthis.A_default_vhostcatchesarequestonlyifthereisnoothervhostwithamatchingIPaddressandamatchingportnumberfortherequest.Therequestisonlycaughtiftheportnumbertowhichtheclientsenttherequestmatchestheportnumberofyour_default_vhostwhichisyourstandardListenbydefault.Awildcardportcanbespecified(i.e.,_default_:*)tocatchrequeststoanyavailableport.ThisalsoappliestoNameVirtualHost*vhosts.Themain_serverisonlyusedtoservearequestiftheIPaddressandportnumbertowhichtheclientconnectedisunspecifiedanddoesnotmatchanyothervhost(includinga_default_vhost).Inotherwordsthemain_serveronlycatchesarequestforanunspecifiedaddress/portcombination(unlessthereisa_default_vhostwhichmatchesthatport).A_default_vhostorthemain_serverisnevermatchedforarequestwithanunknownormissingHost:headerfieldiftheclientconnectedtoanaddress(andport)whichisusedforname-basedvhosts,e.g.,inaNameVirtualHostdirective.YoushouldneverspecifyDNSnamesinVirtualHostdirectivesbecauseitwillforceyourservertorelyonDNStoboot.FurthermoreitposesasecuritythreatifyoudonotcontroltheDNSforallthedomainslisted.There'smoreinformationavailableonthisandthenexttwotopics.ServerNameshouldalwaysbesetforeachvhost.OtherwiseADNSlookupisrequiredforeachvhost.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Tips

InadditiontothetipsontheDNSIssuespage,herearesomefurthertips:

Placeallmain_serverdefinitionsbeforeanyVirtualHostdefinitions.(Thisistoaidthereadabilityoftheconfiguration--thepost-configmergingprocessmakesitnon-obviousthatdefinitionsmixedinaroundvirtualhostsmightaffectallvirtualhosts.)GroupcorrespondingNameVirtualHostandVirtualHostdefinitionsinyourconfigurationtoensurebetterreadability.AvoidServerPathswhichareprefixesofotherServerPaths.Ifyoucannotavoidthisthenyouhavetoensurethatthelonger(morespecific)prefixvhostappearsearlierintheconfigurationfilethantheshorter(lessspecific)prefix(i.e.,"ServerPath/abc"shouldappearafter"ServerPath/abc/def").

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

20 Unix 64

Apache

1. setrlimit()

2. setrlimit(RLIMIT_NOFILE) (Solaris2.3)

3.

4. stdio256

:

<VirtualHost>12 Apache

#!/bin/sh

ulimit-S-n100

exechttpd

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

LogFormat %v:

LogFormat"%v%h%l%u%t\"%r\"%>s%b"vhost

CustomLoglogs/multiple_vhost_logvhost

commonlogformat( ServerName)(CustomLogFormats)

(1) split-logfileApachesupport

:

split-logfile</logs/multiple_vhost_log

.log

DNSApache

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

Apache DNSApache

<VirtualHostwww.abc.dom>

ServerAdminwebgirl@abc.dom

DocumentRoot/www/abc

</VirtualHost>

Apache ApacheDNS www.abc.dom DNS1.2)

www.abc.dom10.0.0.1

<VirtualHost10.0.0.1>

ServerAdminwebgirl@abc.dom

DocumentRoot/www/abc

</VirtualHost>

ApacheDNS ServerName

IP URLURL

<VirtualHost10.0.0.1>

ServerNamewww.abc.dom

ServerAdminwebgirl@abc.dom

DocumentRoot/www/abc

</VirtualHost>

() Apache1.2abc.dom DNS www.abc.dom

<VirtualHostwww.abc.dom>

ServerAdminwebgirl@abc.dom

DocumentRoot/www/abc

</VirtualHost>

<VirtualHostwww.def.dom>

ServerAdminwebguy@def.dom

DocumentRoot/www/def

</VirtualHost>

10.0.0.1 www.abc.dom 10.0.0.2 www.def.domdef.domDNS abc.dom

www.def.dom10.0.0.1 DNSDNSwww.def.dom

10.0.0.1 (http://www.abc.dom/whateverURLdef.dom

Apache1.1 ApachehttpdIP ServerName C gethostname(DNS DNS

DNS OS /etc/resolv.conf

/etc/nsswitch.conf

DNS HOSTRESORDER localmod_env CGImanOS

VirtualHostIPListenIP ServerName <VirtualHost_default_:*>

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

:

DNSApache1.2 DNS

DNSDNSDNS )

IPDNS

HTTP/1.1 HostIP

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>FAQ

Support-FrequentlyAskedQuestions

Support

"Whycan'tI...?Whywon't...work?"WhattodoincaseofproblemsWhomdoIcontactforsupport?

"Whycan'tI...?Whywon't...work?"WhattodoincaseofproblemsIfyouarehavingtroublewithyourApacheserversoftware,youshouldtakethefollowingsteps:

Checktheerrorlog!Apachetriestobehelpfulwhenitencountersaproblem.Inmanycases,itwillprovidesomedetailsbywritingoneormessagestotheservererrorlog.Sometimesthisisenoughforyoutodiagnose&fixtheproblemyourself(suchasfilepermissionsorthelike).Thedefaultlocationoftheerrorlogis/usr/local/apache2/logs/error_log,butseetheErrorLogdirectiveinyourconfigfilesforthelocationonyourserver.

ChecktheFAQ!ThelatestversionoftheApacheFrequently-AskedQuestionslistcanalwaysbefoundatthemainApachewebsite.

ChecktheApachebugdatabaseMostproblemsthatgetreportedtoTheApacheGrouparerecordedinthebugdatabase.Pleasechecktheexistingreports,openandclosed,beforeaddingone.Ifyoufindthatyourissuehasalreadybeenreported,pleasedon'tadda"me,too"report.Iftheoriginalreportisn'tclosedyet,wesuggestthatyoucheckitperiodically.Youmightalsoconsidercontactingtheoriginalsubmitter,becausetheremaybeanemailexchangegoingonabouttheissuethatisn'tgettingrecordedinthedatabase.

AskinausersupportforumApachehasanactivecommunityofuserswhoarewillingtosharetheirknowledge.Participatinginthiscommunityisusuallythebestandfastestwaytogetanswerstoyourquestionsandproblems.

Usersmailinglist

#httpdonFreenodeIRCisavailableforusersupportissues.

USENETnewsgroups:

comp.infosystems.www.servers.unix[news][google]comp.infosystems.www.servers.ms-windows[news][google]comp.infosystems.www.authoring.cgi[news][google]

Ifallelsefails,reporttheprobleminthebugdatabaseIfyou'vegonethroughthosestepsabovethatareappropriateandhaveobtainednorelief,thenpleasedoletthehttpddevelopersknowabouttheproblembyloggingabugreport.

Ifyourprobleminvolvestheservercrashingandgeneratingacoredump,pleaseincludeabacktrace(ifpossible).Asanexample,

#cdServerRoot

#dbxhttpdcore

(dbx)where

(SubstitutetheappropriatelocationsforyourServerRootandyourhttpdandcorefiles.Youmayhavetousegdbinsteadofdbx.)

WhomdoIcontactforsupport?

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Withseveralmillionusersandfewerthanfortyvolunteerdevelopers,wecannotprovidepersonalsupportforApache.Forfreesupport,wesuggestparticipatinginauserforum.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>FAQ

ErrorMessages-FrequentlyAskedQuestions

ErrorMessages

Invalidargument:core_output_filter:writingdatatothenetworkAcceptExfailedPrematureendofscriptheaders

Invalidargument:core_output_filter:writingdatatothenetworkApacheusesthesendfilesyscallonplatformswhereitisavailableinordertospeedsendingofresponses.Unfortunately,onsomesystems,Apachewilldetectthepresenceofsendfileatcompile-time,evenwhenitdoesnotworkproperly.Thishappensmostfrequentlywhenusingnetworkorothernon-standardfile-system.

Symptomsofthisproblemincludetheabovemessageintheerrorlogandzero-lengthresponsestonon-zero-sizedfiles.Theproblemgenerallyoccursonlyforstaticfiles,sincedynamiccontentusuallydoesnotmakeuseofsendfile.

Tofixthisproblem,simplyusetheEnableSendfiledirectivetodisablesendfileforallorpartofyourserver.AlsoseetheEnableMMAP,whichcanhelpwithsimilarproblems.

AcceptExFailedIfyougeterrormessagesrelatedtotheAcceptExsyscallonwin32,seetheWin32DisableAcceptExdirective.

PrematureendofscriptheadersMostproblemswithCGIscriptsresultinthismessagewrittenintheerrorlogtogetherwithanInternalServerErrordeliveredtothebrowser.Aguidetohelpingdebugthistypeof

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

problemisavailableintheCGItutorial.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >SSL/TLS

SSL/TLS:

--A.Tanenbaum,"IntroductiontoComputerNetworks"

WebHTTPApacheSSL mod_ssl

TheOpenGroupResearchInstitute FrederickJ.HirschIntroducingSSLandCertificatesusingSSLeay WebSecurity:AMatterofTrust,WorldWideWebJournal,Volume2,Issue3,Summer1997 FrederickHirsch ()Engelschall(mod_ssl)[: Apache

SSL(:)([ AC96])

()

()

(CertificateAuthorityCA)(certificate)(authentication)

1

1:

() ( 2)

2:

CommonName() CNSSLURL

CN=www.example.com

OrganizationorCompany()

O O=ExampleJapanK.K.

OrganizationalUnit() OU OU=CustomerServiceCity/Locality() L L=SapporoState/Province() ST ST=HokkaidoCountry() C ISO C=JP

JP

ASN.1 [X208][PKCS] EncodingRules(DER)BasicEncodingRules Base64[ MIME] ASCII"PrivacyEnhancedMail")

PEM(example.crt)-----BEGINCERTIFICATE-----

MIIC7jCCAlegAwIBAgIBATANBgkqhkiG9w0BAQQFADCBqTELMAkGA1UEBhMCWFkx

FTATBgNVBAgTDFNuYWtlIERlc2VydDETMBEGA1UEBxMKU25ha2UgVG93bjEXMBUG

A1UEChMOU25ha2UgT2lsLCBMdGQxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhv

cml0eTEVMBMGA1UEAxMMU25ha2UgT2lsIENBMR4wHAYJKoZIhvcNAQkBFg9jYUBz

bmFrZW9pbC5kb20wHhcNOTgxMDIxMDg1ODM2WhcNOTkxMDIxMDg1ODM2WjCBpzEL

MAkGA1UEBhMCWFkxFTATBgNVBAgTDFNuYWtlIERlc2VydDETMBEGA1UEBxMKU25h

a2UgVG93bjEXMBUGA1UEChMOU25ha2UgT2lsLCBMdGQxFzAVBgNVBAsTDldlYnNl

cnZlciBUZWFtMRkwFwYDVQQDExB3d3cuc25ha2VvaWwuZG9tMR8wHQYJKoZIhvcN

AQkBFhB3d3dAc25ha2VvaWwuZG9tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB

gQDH9Ge/s2zcH+da+rPTx/DPRp3xGjHZ4GG6pCmvADIEtBtKBFAcZ64n+Dy7Np8b

vKR+yy5DGQiijsH1D/j8HlGE+q4TZ8OFk7BNBFazHxFbYI4OKMiCxdKzdif1yfaa

lWoANFlAzlSdbxeGVHoT0K+gT5w3UxwZKv2DLbCTzLZyPwIDAQABoyYwJDAPBgNV

HRMECDAGAQH/AgEAMBEGCWCGSAGG+EIBAQQEAwIAQDANBgkqhkiG9w0BAQQFAAOB

gQAZUIHAL4D09oE6Lv2k56Gp38OBDuILvwLg1v1KL8mQR+KFjghCrtpqaztZqcDt

2q2QoyulCgSzHbEGmi0EsdkPfg6mp0penssIFePYNI+/8u9HT4LuKMJX15hxBam7

dUHzICxBVC1lnHyYGjDuAMhe396lYAn8bCld1/L4NMGBCQ==

-----ENDCERTIFICATE-----

(CA)

Thawte VeriSign :

CRL)

SecureSocketsLayer(SSL)

SecureSocketsLayer(TCP/IP)(HTTP)SSL

SSL

4:SSL

SSLv2.0

VendorStandard(NetscapeCorp.)[ SSL2]

SSL -NSNavigator1.x/2.x-MSIE3.x-Lynx/2.8+OpenSSL

SSLv3.0

ExpiredInternetDraft(NetscapeCorp.)[ SSL3]

RSA-NSNavigator2.x/3.x/4.x-MSIE3.x/4.x-Lynx/2.8+OpenSSL

TLSv1.0

ProposedInternetStandard(IETF)[ TLS1]

MACHMACblockpadding3.0

-Lynx/2.8+OpenSSL

4SSLSSL3.0SSL3.0InternetEngineeringTaskForce(IETF)TransportLayerSecurity[TLS]

1

SSL

1:SSL

:

1.

2.

3.

4.

MessageAuthenticationCode(MAC)

Hellman

SSL () :

40-bitRC4128-bitRC4

CBC40bitRC240bitDES56bitDES168bitTriple-DESIdea(128bit)Fortezza(96bit)

CBC(CipherBlockChaining) EncryptionStandard)[AC96,ch12] DES403DES_EDE Idea RC2RSADSI

MD5(128-bit)SecureHashAlgorithm(SHA-1)(160-bit)

MessageAuthenticationCode(MAC)

:

SSLSSLSSLSSLSSL

2 SSL

2:SSL

SSL

3SSL SSL

3 :SSL

HTTPSSLHTTP HTTPHTTPS URL http https(443)mod_sslApache

[AC96]BruceSchneier,AppliedCryptography,2ndEdition,Wiley,1996.Seehttp://www.counterpane.com/forvariousothermaterialsbyBruceSchneier.

[X208]ITU-TRecommendationX.208,SpecificationofAbstractSyntaxNotationOne(ASN.1),1988.Seeforinstancehttp://www.itu.int/rec/recommendation.asp?type=items&lang=e&parent=T-REC-X.208-198811-I.

[X509]ITU-TRecommendationX.509,TheDirectory-AuthenticationFramework.Seeforinstancehttp://www.itu.int/rec/recommendation.asp?type=folders&lang=e&parent=T-REC-X.509.

[PKCS]PublicKeyCryptographyStandards(PKCS),RSALaboratoriesTechnicalNotes,Seehttp://www.rsasecurity.com/rsalabs/pkcs/.

[MIME]N.Freed,N.Borenstein,MultipurposeInternetMailExtensions(MIME)PartOne:FormatofInternetMessageBodies,RFC2045.Seeforinstancehttp://ietf.org/rfc/rfc2045.txt.

[SSL2]KippE.B.Hickman,TheSSLProtocol,1995.Seehttp://www.netscape.com/eng/security/SSL_2.html.

[SSL3]AlanO.Freier,PhilipKarlton,PaulC.Kocher,TheSSLProtocolVersion3.0,1996.Seehttp://www.netscape.com/eng/ssl3/draft302.txt.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

[TLS1]TimDierks,ChristopherAllen,TheTLSProtocolVersion1.0,1999.Seehttp://ietf.org/rfc/rfc2246.txt.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>SSL/TLS

SSL/TLSStrongEncryption:Compatibility

AllPCsarecompatible.Butsomeofthemaremorecompatiblethanothers.

--Unknown

HerewetalkaboutbackwardcompatibilitytootherSSLsolutions.Asyouperhapsknow,mod_sslisnottheonlyexistingSSLsolutionforApache.Actuallytherearefouradditionalmajorproductsavailableonthemarket:BenLaurie'sfreelyavailableApache-SSL(fromwheremod_sslwereoriginallyderivedin1998),RedHat'scommercialSecureWebServer(whichisbasedonmod_ssl),Covalent'scommercialRavenSSLModule(alsobasedonmod_ssl)andfinallyC2Net'scommercialproductStronghold(basedonadifferentevolutionbranchnamedSiouxuptoStronghold2.xandbasedonmod_sslsinceStronghold3.x).

Theideainmod_sslismainlythefollowing:becausemod_sslprovidesmostlyasupersetofthefunctionalityofallothersolutionswecaneasilyprovidebackwardcompatibilityformostofthecases.Actuallytherearethreecompatibilityareaswecurrentlyaddress:configurationdirectives,environmentvariablesandcustomlogfunctions.

ConfigurationDirectives

ForbackwardcompatibilitytotheconfigurationdirectivesofotherSSLsolutionswedoanon-the-flymapping:directiveswhichhaveadirectcounterpartinmod_sslaremappedsilentlywhileotherdirectivesleadtoawarningmessageinthelogfiles.ThecurrentlyimplementeddirectivemappingislistedinTable1.CurrentlyfullbackwardcompatibilityisprovidedonlyforApache-SSL1.xandmod_ssl2.0.x.CompatibilitytoSioux1.xandStronghold2.xisonlypartialbecauseofspecialfunctionalityintheseinterfaceswhichmod_ssl(still)doesn'tprovide.

Table1:ConfigurationDirectiveMappingOldDirective mod_sslDirectiveApache-SSL1.x&mod_ssl2.0.xcompatibility:SSLEnable SSLEngineon

SSLDisable SSLEngineoff

SSLLogFilefile SSLLogfileSSLRequiredCiphersspec SSLCipherSuitespecSSLRequireCipherc1... SSLRequire%

{SSL_CIPHER}in

{"c1",...}SSLBanCipherc1... SSLRequirenot(%

{SSL_CIPHER}in

{"c1",...})SSLFakeBasicAuth SSLOptions

+FakeBasicAuth

SSLCacheServerPathdir -SSLCacheServerPortinteger -

Apache-SSL1.xcompatibility:SSLExportClientCertificates SSLOptions

+ExportCertData

SSLCacheServerRunDirdir -

Sioux1.xcompatibility:SSL_CertFilefile SSLCertificateFilefileSSL_KeyFilefile SSLCertificateKeyFile

fileSSL_CipherSuitearg SSLCipherSuiteargSSL_X509VerifyDirarg SSLCACertificatePath

argSSL_Logfile SSLLogFilefileSSL_Connectflag SSLEngineflagSSL_ClientAutharg SSLVerifyClientargSSL_X509VerifyDeptharg SSLVerifyDepthargSSL_FetchKeyPhraseFromarg -

SSL_SessionDirdir -

SSL_Requireexpr -

SSL_CertFileTypearg -

SSL_KeyFileTypearg -

SSL_X509VerifyPolicyarg -

SSL_LogX509Attributesarg -

Stronghold2.xcompatibility:StrongholdAcceleratordir -

StrongholdKeydir -

StrongholdLicenseFiledir -

SSLFlagflag SSLEngineflagSSLSessionLockFilefile SSLMutexfileSSLCipherListspec SSLCipherSuitespecRequireSSL SSLRequireSSL

SSLErrorFilefile -

SSLRootdir -

SSL_CertificateLogDirdir -

AuthCertDirdir -

SSL_Groupname -

SSLProxyMachineCertPathdir -

SSLProxyMachineCertFilefile -

SSLProxyCACertificatePath

dir-

SSLProxyCACertificateFile

file-

SSLProxyVerifyDepthnumber -

SSLProxyCipherListspec -

EnvironmentVariables

Whenyouuse``SSLOptions+CompatEnvVars''additionalenvironmentvariablesaregenerated.Theyallcorrespondtoexistingofficialmod_sslvariables.ThecurrentlyimplementedvariablederivationislistedinTable2.

Table2:EnvironmentVariableDerivationOldVariable mod_sslVariableSSL_PROTOCOL_VERSION SSL_PROTOCOL

SSLEAY_VERSION SSL_VERSION_LIBRARY

HTTPS_SECRETKEYSIZE SSL_CIPHER_USEKEYSIZE

HTTPS_KEYSIZE SSL_CIPHER_ALGKEYSIZE

HTTPS_CIPHER SSL_CIPHER

HTTPS_EXPORT SSL_CIPHER_EXPORT

SSL_SERVER_KEY_SIZE SSL_CIPHER_ALGKEYSIZE

SSL_SERVER_CERTIFICATE SSL_SERVER_CERT

SSL_SERVER_CERT_START SSL_SERVER_V_START

SSL_SERVER_CERT_END SSL_SERVER_V_END

SSL_SERVER_CERT_SERIAL SSL_SERVER_M_SERIAL

SSL_SERVER_SIGNATURE_ALGORITHM SSL_SERVER_A_SIG

SSL_SERVER_DN SSL_SERVER_S_DN

SSL_SERVER_CN SSL_SERVER_S_DN_CN

SSL_SERVER_EMAIL SSL_SERVER_S_DN_Email

SSL_SERVER_O SSL_SERVER_S_DN_O

SSL_SERVER_OU SSL_SERVER_S_DN_OU

SSL_SERVER_C SSL_SERVER_S_DN_C

SSL_SERVER_SP SSL_SERVER_S_DN_SP

SSL_SERVER_L SSL_SERVER_S_DN_L

SSL_SERVER_IDN SSL_SERVER_I_DN

SSL_SERVER_ICN SSL_SERVER_I_DN_CN

SSL_SERVER_IEMAIL SSL_SERVER_I_DN_Email

SSL_SERVER_IO SSL_SERVER_I_DN_O

SSL_SERVER_IOU SSL_SERVER_I_DN_OU

SSL_SERVER_IC SSL_SERVER_I_DN_C

SSL_SERVER_ISP SSL_SERVER_I_DN_SP

SSL_SERVER_IL SSL_SERVER_I_DN_L

SSL_CLIENT_CERTIFICATE SSL_CLIENT_CERT

SSL_CLIENT_CERT_START SSL_CLIENT_V_START

SSL_CLIENT_CERT_END SSL_CLIENT_V_END

SSL_CLIENT_CERT_SERIAL SSL_CLIENT_M_SERIAL

SSL_CLIENT_SIGNATURE_ALGORITHM SSL_CLIENT_A_SIG

SSL_CLIENT_DN SSL_CLIENT_S_DN

SSL_CLIENT_CN SSL_CLIENT_S_DN_CN

SSL_CLIENT_EMAIL SSL_CLIENT_S_DN_Email

SSL_CLIENT_O SSL_CLIENT_S_DN_O

SSL_CLIENT_OU SSL_CLIENT_S_DN_OU

SSL_CLIENT_C SSL_CLIENT_S_DN_C

SSL_CLIENT_SP SSL_CLIENT_S_DN_SP

SSL_CLIENT_L SSL_CLIENT_S_DN_L

SSL_CLIENT_IDN SSL_CLIENT_I_DN

SSL_CLIENT_ICN SSL_CLIENT_I_DN_CN

SSL_CLIENT_IEMAIL SSL_CLIENT_I_DN_Email

SSL_CLIENT_IO SSL_CLIENT_I_DN_O

SSL_CLIENT_IOU SSL_CLIENT_I_DN_OU

SSL_CLIENT_IC SSL_CLIENT_I_DN_C

SSL_CLIENT_ISP SSL_CLIENT_I_DN_SP

SSL_CLIENT_IL SSL_CLIENT_I_DN_L

SSL_EXPORT SSL_CIPHER_EXPORT

SSL_KEYSIZE SSL_CIPHER_ALGKEYSIZE

SSL_SECKEYSIZE SSL_CIPHER_USEKEYSIZE

SSL_SSLEAY_VERSION SSL_VERSION_LIBRARY

SSL_STRONG_CRYPTO -

SSL_SERVER_KEY_EXP -

SSL_SERVER_KEY_ALGORITHM -

SSL_SERVER_KEY_SIZE -

SSL_SERVER_SESSIONDIR -

SSL_SERVER_CERTIFICATELOGDIR -

SSL_SERVER_CERTFILE -

SSL_SERVER_KEYFILE -

SSL_SERVER_KEYFILETYPE -

SSL_CLIENT_KEY_EXP -

SSL_CLIENT_KEY_ALGORITHM -

SSL_CLIENT_KEY_SIZE -

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

CustomLogFunctions

Whenmod_sslisbuiltintoApacheoratleastloaded(underDSOsituation)additionalfunctionsexistfortheCustomLogFormatofmod_log_configasdocumentedintheReferenceChapter.Besidethe``%{varname}x''eXtensionformatfunctionwhichcanbeusedtoexpandanyvariablesprovidedbyanymodule,anadditionalCryptography``%{name}c''cryptographyformatfunctionexistsforbackwardcompatibility.ThecurrentlyimplementedfunctioncallsarelistedinTable3.

Table3:CustomLogCryptographyFunctionFunctionCall Description%...{version}c SSLprotocolversion%...{cipher}c SSLcipher%...

{subjectdn}c

ClientCertificateSubjectDistinguishedName

%...{issuerdn}c ClientCertificateIssuerDistinguishedName

%...{errcode}c CertificateVerificationError(numerical)%...{errstr}c CertificateVerificationError(string)

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>SSL/TLS

SSL/TLSStrongEncryption:How-To

Thesolutionofthisproblemistrivialandisleftasanexerciseforthereader.

--Standardtextbookcookie

HowtosolveparticularsecurityconstraintsforanSSL-awarewebserverisnotalwaysobviousbecauseofthecoherencesbetweenSSL,HTTPandApache'swayofprocessingrequests.Thischaptergivesinstructionsonhowtosolvesuchtypicalsituations.Treatitasafirststeptofindoutthefinalsolution,butalwaystrytounderstandthestuffbeforeyouuseit.Nothingisworsethanusingasecuritysolutionwithoutknowingitsrestrictionsandcoherences.

CipherSuitesandEnforcedStrongSecurity

SSLv2onlyserverstrongencryptiononlyserverservergatedcryptographystrongerper-directoryrequirements

HowcanIcreatearealSSLv2-onlyserver?ThefollowingcreatesanSSLserverwhichspeaksonlytheSSLv2protocolanditsciphers.

httpd.confSSLProtocol-all+SSLv2

SSLCipherSuiteSSLv2:+HIGH:+MEDIUM:+LOW:+EXP

HowcanIcreateanSSLserverwhichacceptsstrongencryptiononly?Thefollowingenablesonlythestrongestciphers:

httpd.confSSLProtocolall-SSLv2

SSLCipherSuiteHIGH:!aNULL:!MD5

HowcanIcreateanSSLserverwhichacceptsstrongencryptiononly,butallowsexportbrowserstoupgradetostrongerencryption?ThisfacilityiscalledServerGatedCryptography(SGC)anddetailsyoucanfindintheREADME.GlobalIDdocumentinthemod_ssldistribution.Inshort:TheserverhasaGlobalIDservercertificate,signedbyaspecialCAcertificatefromVerisignwhichenablesstrongencryptioninexportbrowsers.Thisworksasfollowing:Thebrowserconnectswithanexportcipher,theserversendsitsGlobalIDcertificate,thebrowserverifiesitand

subsequentlyupgradestheciphersuitebeforeanyHTTPcommunicationtakesplace.Thequestionnowis:Howcanweallowthisupgrade,butenforcestrongencryption.Orinotherwords:Browsereitherhavetoinitiallyconnectwithstrongencryptionorhavetoupgradetostrongencryption,butarenotallowedtokeeptheexportciphers.Thefollowingdoesthetrick:

httpd.conf#allowallciphersfortheinitialhandshake,

#soexportbrowserscanupgradeviaSGCfacility

SSLCipherSuite

ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL

<Directory/usr/local/apache2/htdocs>

#butfinallydenyallbrowserswhichhaven'tupgraded

SSLRequire%{SSL_CIPHER_USEKEYSIZE}>=128

</Directory>

HowcanIcreateanSSLserverwhichacceptsalltypesofciphersingeneral,butrequiresastrongciphersforaccesstoaparticularURL?Obviouslyyoucannotjustuseaserver-wideSSLCipherSuitewhichrestrictsthecipherstothestrongvariants.Butmod_sslallowsyoutoreconfiguretheciphersuiteinper-directorycontextandautomaticallyforcesarenegotiationoftheSSLparameterstomeetthenewconfiguration.So,thesolutionis:

#beliberalingeneral

SSLCipherSuite

ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL

<Location/strong/area>

#buthttps://hostname/strong/area/andbelow

#requiresstrongciphers

SSLCipherSuiteHIGH:!aNULL:!MD5

</Location>

ClientAuthenticationandAccessControl

simplecertificate-basedclientauthenticationselectivecertificate-basedclientauthenticationparticularcertificate-basedclientauthenticationintranetvs.internetauthentication

HowcanIauthenticateclientsbasedoncertificateswhenIknowallmyclients?Whenyouknowyourusercommunity(i.e.aclosedusergroupsituation),asit'sthecaseforinstanceinanIntranet,youcanuseplaincertificateauthentication.AllyouhavetodoistocreateclientcertificatessignedbyyourownCAcertificateca.crtandthenverifytheclientsagainstthiscertificate.

httpd.conf#requireaclientcertificatewhichhastobedirectly

#signedbyourCAcertificateinca.crt

SSLVerifyClientrequire

SSLVerifyDepth1

SSLCACertificateFileconf/ssl.crt/ca.crt

HowcanIauthenticatemyclientsforaparticularURLbasedoncertificatesbutstillallowarbitraryclientstoaccesstheremainingpartsoftheserver?Forthisweagainusetheper-directoryreconfigurationfeatureofmod_ssl:

httpd.confSSLVerifyClientnone

SSLCACertificateFileconf/ssl.crt/ca.crt

<Location/secure/area>

SSLVerifyClientrequire

SSLVerifyDepth1

</Location>

HowcanIauthenticateonlyparticularclientsforasomeURLsbasedoncertificatesbutstillallowarbitraryclientstoaccesstheremainingpartsoftheserver?Thekeyistocheckforvariousingredientsoftheclientcertificate.UsuallythismeanstocheckthewholeorpartoftheDistinguishedName(DN)oftheSubject.Forthistwomethodsexists:Themod_authbasedvariantandtheSSLRequirevariant.Thefirstmethodisgoodwhentheclientsareoftotallydifferenttype,i.e.whentheirDNshavenocommonfields(usuallytheorganisation,etc.).Inthiscaseyou'vetoestablishapassworddatabasecontainingallclients.ThesecondmethodisbetterwhenyourclientsareallpartofacommonhierarchywhichisencodedintotheDN.Thenyoucanmatchthemmoreeasily.

Thefirstmethod:

httpd.confSSLVerifyClientnone

<Directory/usr/local/apache2/htdocs/secure/area>

SSLVerifyClientrequire

SSLVerifyDepth5

SSLCACertificateFileconf/ssl.crt/ca.crt

SSLCACertificatePathconf/ssl.crt

SSLOptions+FakeBasicAuth

SSLRequireSSL

AuthName"SnakeOilAuthentication"

AuthTypeBasic

AuthUserFile/usr/local/apache2/conf/httpd.passwd

requirevalid-user

</Directory>

ThepasswordusedinthisexampleistheDESencryptedstring"password".SeetheSSLOptionsdocsformoreinformation.

httpd.passwd

/C=DE/L=Munich/O=SnakeOil,Ltd./OU=Staff/CN=Foo:xxj31ZMTZzkVA

/C=US/L=S.F./O=SnakeOil,Ltd./OU=CA/CN=Bar:xxj31ZMTZzkVA

/C=US/L=L.A./O=SnakeOil,Ltd./OU=Dev/CN=Quux:xxj31ZMTZzkVA

Thesecondmethod:

httpd.confSSLVerifyClientnone

<Directory/usr/local/apache2/htdocs/secure/area>

SSLVerifyClientrequire

SSLVerifyDepth5

SSLCACertificateFileconf/ssl.crt/ca.crt

SSLCACertificatePathconf/ssl.crt

SSLOptions+FakeBasicAuth

SSLRequireSSL

SSLRequire%{SSL_CLIENT_S_DN_O}eq"SnakeOil,Ltd."\

and%{SSL_CLIENT_S_DN_OU}in{"Staff","CA","Dev"}

</Directory>

HowcanIrequireHTTPSwithstrongciphersandeitherbasicauthenticationorclientcertificatesforaccesstoasubareaontheIntranetwebsiteforclientscomingfromtheInternetbutstillallowplainHTTPaccessforclientsontheIntranet?LetusassumetheIntranetcanbedistinguishedthroughtheIPnetwork192.168.1.0/24andthesubareaontheIntranetwebsitehastheURL/subarea.ThenconfigurethefollowingoutsideyourHTTPSvirtualhost(soitappliestobothHTTPSandHTTP):

httpd.confSSLCACertificateFileconf/ssl.crt/company-ca.crt

<Directory/usr/local/apache2/htdocs>

#OutsidethesubareaonlyIntranetaccessisgranted

Orderdeny,allow

Denyfromall

Allowfrom192.168.1.0/24

</Directory>

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

<Directory/usr/local/apache2/htdocs/subarea>

#InsidethesubareaanyIntranetaccessisallowed

#butfromtheInternetonlyHTTPS+Strong-Cipher+Password

#orthealternativeHTTPS+Strong-Cipher+Client-Certificate

#IfHTTPSisused,makesureastrongcipherisused.

#Additionallyallowclientcertsasalternativetobasicauth.

SSLVerifyClientoptional

SSLVerifyDepth1

SSLOptions+FakeBasicAuth+StrictRequire

SSLRequire%{SSL_CIPHER_USEKEYSIZE}>=128

#ForceclientsfromtheInternettouseHTTPS

RewriteEngineon

RewriteCond%{REMOTE_ADDR}!^192\.168\.1\.[0-9]+$

RewriteCond%{HTTPS}!=on

RewriteRule.*-[F]

#AllowNetworkAccessand/orBasicAuth

Satisfyany

#NetworkAccessControl

Orderdeny,allow

Denyfromall

Allow192.168.1.0/24

#HTTPBasicAuthentication

AuthTypebasic

AuthName"ProtectedIntranetArea"

AuthUserFileconf/protected.passwd

Requirevalid-user

</Directory>

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>SSL/TLS

SSL/TLSStrongEncryption:FAQ

Thewisemandoesn'tgivetherightanswers,heposestherightquestions.

--ClaudeLevi-Strauss

Thischapterisacollectionoffrequentlyaskedquestions(FAQ)andcorrespondinganswersfollowingthepopularUSENETtradition.MostofthesequestionsoccurredontheNewsgroupcomp.infosystems.www.servers.unixorthemod_sslSupportMailingListmodssl-users@modssl.org.Theyarecollectedatthisplacetoavoidansweringthesamequestionsoverandover.

Pleasereadthischapteratleastoncewheninstallingmod_ssloratleastsearchforyourproblemherebeforesubmittingaproblemreporttotheauthor.

AboutTheModule

Whatisthehistoryofmod_ssl?mod_sslandWassenaarArrangement?

Whatisthehistoryofmod_ssl?Themod_sslv1packagewasinitiallycreatedinApril1998byRalfS.EngelschallviaportingBenLaurie'sApache-SSL1.17sourcepatchesforApache1.2.6toApache1.3b6.BecauseofconflictswithBenLaurie'sdevelopmentcycleitthenwasre-assembledfromscratchforApache1.3.0bymergingtheoldmod_ssl1.xwiththenewerApache-SSL1.18.Fromthispointonmod_sslliveditsownlifeasmod_sslv2.Thefirstpubliclyreleasedversionwasmod_ssl2.0.0fromAugust10th,1998.

AfterUSexportrestrictionsoncryptographicsoftwarewereloosened,mod_sslbecamepartoftheApacheHTTPServerwiththereleaseofApachehttpd2.

Ismod_sslaffectedbytheWassenaarArrangement?First,letusexplainwhatWassenaaranditsArrangementonExportControlsforConventionalArmsandDual-UseGoodsandTechnologiesis:Thisisainternationalregime,establishedin1995,tocontroltradeinconventionalarmsanddual-usegoodsandtechnology.ItreplacedthepreviousCoComregime.FurtherdetailsonboththeArrangementanditssignatoriesareavailableathttp://www.wassenaar.org/.

Inshort,theaimoftheWassenaarArrangementistopreventthebuildupofmilitarycapabilitiesthatthreatenregionalandinternationalsecurityandstability.TheWassenaarArrangementcontrolstheexportofcryptographyasadual-usegood,thatis,somethingthathasbothmilitaryandcivilianapplications.However,theWassenaarArrangementalsoprovidesan

exemptionfromexportcontrolsformass-marketsoftwareandfreesoftware.

InthecurrentWassenaarListofDualUseGoodsandTechnologiesAndMunitions,under“GENERALSOFTWARENOTE(GSN)”itsays“TheListsdonotcontrol"software"whichiseither:1.[...]2."inthepublicdomain".”Andunder“DEFINITIONSOFTERMSUSEDINTHESELISTS”wefind“Inthepublicdomain”definedas“"technology"or"software"whichhasbeenmadeavailablewithoutrestrictionsuponitsfurtherdissemination.Note:Copyrightrestrictionsdonotremove"technology"or"software"frombeing"inthepublicdomain".”

So,bothmod_sslandOpenSSLare“inthepublicdomain”forthepurposesoftheWassenaarArrangementandits“ListofDualUseGoodsandTechnologiesAndMunitionsList”,andthusnotaffectedbyitsprovisions.

Installation

WhydoIgetpermissionerrorsrelatedtoSSLMutexwhenIstartApache?Whydoesmod_sslstopwiththeerror"Failedtogeneratetemporary512bitRSAprivatekey"whenIstartApache?

WhydoIgetpermissionerrorsrelatedtoSSLMutexwhenIstartApache?Errorssuchas``mod_ssl:ChildcouldnotopenSSLMutexlockfile

/opt/apache/logs/ssl_mutex.18332(Systemerror

follows)[...]System:Permissiondenied(errno:

13)''areusuallycausedbyoverlyrestrictivepermissionsontheparentdirectories.Makesurethatallparentdirectories(here/opt,/opt/apacheand/opt/apache/logs)havethex-bitsetfor,atminimum,theUIDunderwhichApache'schildrenarerunning(seetheUserdirective).

Whydoesmod_sslstopwiththeerror"Failedtogeneratetemporary512bitRSAprivatekey"whenIstartApache?Cryptographicsoftwareneedsasourceofunpredictabledatatoworkcorrectly.Manyopensourceoperatingsystemsprovidea"randomnessdevice"thatservesthispurpose(usuallynamed/dev/random).Onothersystems,applicationshavetoseedtheOpenSSLPseudoRandomNumberGenerator(PRNG)manuallywithappropriatedatabeforegeneratingkeysorperformingpublickeyencryption.Asofversion0.9.5,theOpenSSLfunctionsthatneedrandomnessreportanerrorifthePRNGhasnotbeenseededwithatleast128bitsofrandomness.

Topreventthiserror,mod_sslhastoprovideenoughentropytothePRNGtoallowittoworkcorrectly.Thiscanbedoneviathe

SSLRandomSeeddirective.

Configuration

IsitpossibletoprovideHTTPandHTTPSfromthesameserver?WhichportdoesHTTPSuse?HowdoIspeakHTTPSmanuallyfortestingpurposes?WhydoestheconnectionhangwhenIconnecttomySSL-awareApacheserver?WhydoIget``ConnectionRefused''errors,whentryingtoaccessmynewlyinstalledApache+mod_sslserverviaHTTPS?WhyaretheSSL_XXXvariablesnotavailabletomyCGI&SSIscripts?HowcanIswitchbetweenHTTPandHTTPSinrelativehyperlinks?

IsitpossibletoprovideHTTPandHTTPSfromthesameserver?Yes.HTTPandHTTPSusedifferentserverports(HTTPbindstoport80,HTTPStoport443),sothereisnodirectconflictbetweenthem.Youcaneitherruntwoseparateserverinstancesboundtotheseports,oruseApache'selegantvirtualhostingfacilitytocreatetwovirtualservers,bothservedbythesameinstanceofApache-onerespondingoverHTTPtorequestsonport80,andtheotherrespondingoverHTTPStorequestsonport443.

WhichportdoesHTTPSuse?YoucanrunHTTPSonanyport,butthestandardsspecifyport443,whichiswhereanyHTTPScompliantbrowserwilllookbydefault.YoucanforceyourbrowsertolookonadifferentportbyspecifyingitintheURL.Forexample,ifyourserverissetuptoservepagesoverHTTPSonport8080,youcanaccessthemathttps://example.com:8080/

HowdoIspeakHTTPSmanuallyfortestingpurposes?Whileyouusuallyjustuse

$telnetlocalhost80

GET/HTTP/1.0

forsimpletestingofApacheviaHTTP,it'snotsoeasyforHTTPSbecauseoftheSSLprotocolbetweenTCPandHTTP.WiththehelpofOpenSSL'ss_clientcommand,however,youcandoasimilarcheckviaHTTPS:

$openssls_client-connectlocalhost:443-state-debug

GET/HTTP/1.0

BeforetheactualHTTPresponseyouwillreceivedetailedinformationabouttheSSLhandshake.ForamoregeneralcommandlineclientwhichdirectlyunderstandsbothHTTPandHTTPS,canperformGETandPOSToperations,canuseaproxy,supportsbyteranges,etc.youshouldhavealookattheniftycURLtool.Usingthis,youcancheckthatApacheisrespondingcorrectlytorequestsviaHTTPandHTTPSasfollows:

$curlhttp://localhost/

$curlhttps://localhost/

WhydoestheconnectionhangwhenIconnecttomySSL-awareApacheserver?ThiscanhappenwhenyoutrytoconnecttoaHTTPSserver(orvirtualserver)viaHTTP(eg,usinghttp://example.com/insteadofhttps://example.com).ItcanalsohappenwhentryingtoconnectviaHTTPStoaHTTPserver(eg,usinghttps://example.com/onaserverwhichdoesn'tsupportHTTPS,orwhichsupportsitonanon-standardport).Makesure

thatyou'reconnectingtoa(virtual)serverthatsupportsSSL.

WhydoIget``ConnectionRefused''messages,whentryingtoaccessmynewlyinstalledApache+mod_sslserverviaHTTPS?Thiserrorcanbecausedbyanincorrectconfiguration.PleasemakesurethatyourListendirectivesmatchyour<VirtualHost>directives.Ifallelsefails,pleasestartafresh,usingthedefaultconfigurationprovidedbymod_ssl.

WhyaretheSSL_XXXvariablesnotavailabletomyCGI&SSIscripts?Pleasemakesureyouhave``SSLOptions+StdEnvVars''enabledforthecontextofyourCGI/SSIrequests.

HowcanIswitchbetweenHTTPandHTTPSinrelativehyperlinks?Usually,toswitchbetweenHTTPandHTTPS,youhavetousefully-qualifiedhyperlinks(becauseyouhavetochangetheURLscheme).Usingmod_rewritehowever,youcanmanipulaterelativehyperlinks,toachievethesameeffect.

RewriteEngineon

RewriteRule^/(.*):SSL$https://%{SERVER_NAME}/$1[R,L]

RewriteRule^/(.*):NOSSL$http://%{SERVER_NAME}/$1[R,L]

Thisrewriterulesetletsyouusehyperlinksoftheform<ahref="document.html:SSL">,toswitchtoHTTPSinarelativelink.(ReplaceSSLwithNOSSLtoswitchtoHTTP.)

Certificates

WhatareRSAPrivateKeys,CSRsandCertificates?Isthereadifferenceonstartupbetweenanon-SSL-awareApacheandanSSL-awareApache?HowdoIcreateaself-signedSSLCertificatefortestingpurposes?HowdoIcreatearealSSLCertificate?HowdoIcreateandusemyownCertificateAuthority(CA)?HowcanIchangethepass-phraseonmyprivatekeyfile?HowcanIgetridofthepass-phrasedialogatApachestartuptime?HowdoIverifythataprivatekeymatchesitsCertificate?Whydoconnectionsfailwithan"alertbadcertificate"error?Whydoesmy2048-bitprivatekeynotwork?WhyisclientauthenticationbrokenafterupgradingfromSSLeayversion0.8to0.9?HowcanIconvertacertificatefromPEMtoDERformat?Whycan'tIfindthegetcaorgetverisignprogramsmentionedbyVerisign,forinstallingmyVerisigncertificate?CanIusetheServerGatedCryptography(SGC)facility(akaVerisignGlobalID)withmod_ssl?WhydobrowserscomplainthattheycannotverifymyVerisignGlobalIDservercertificate?

WhatareRSAPrivateKeys,CSRsandCertificates?AnRSAprivatekeyfileisadigitalfilethatyoucanusetodecryptmessagessenttoyou.Ithasapubliccomponentwhichyoudistribute(viayourCertificatefile)whichallowspeopletoencryptthosemessagestoyou.

ACertificateSigningRequest(CSR)isadigitalfilewhichcontainsyourpublickeyandyourname.YousendtheCSRtoaCertifyingAuthority(CA),whowillconvertitintoarealCertificate,bysigningit.

ACertificatecontainsyourRSApublickey,yourname,thenameoftheCA,andisdigitallysignedbytheCA.BrowsersthatknowtheCAcanverifythesignatureonthatCertificate,therebyobtainingyourRSApublickey.Thatenablesthemtosendmessageswhichonlyyoucandecrypt.

SeetheIntroductionchapterforageneraldescriptionoftheSSLprotocol.

Isthereadifferenceonstartupbetweenanon-SSL-awareApacheandanSSL-awareApache?Yes.Ingeneral,startingApachewithmod_sslbuilt-inisjustlikestartingApachewithoutit.However,ifyouhaveapassphraseonyourSSLprivatekeyfile,astartupdialogwillpopupwhichasksyoutoenterthepassphrase.

Havingtomanuallyenterthepassphrasewhenstartingtheservercanbeproblematic-forexample,whenstartingtheserverfromthesystembootscripts.Inthiscase,youcanfollowthestepsbelowtoremovethepassphrasefromyourprivatekey.Bearinmindthatdoingsobringsadditionalsecurityrisks-proceedwithcaution!

HowdoIcreateaself-signedSSLCertificatefortestingpurposes?1. MakesureOpenSSLisinstalledandinyourPATH.

2. Runthefollowingcommand,tocreateserver.keyandserver.crtfiles:$opensslreq-new-x509-nodes-out

server.crt-keyoutserver.key

Thesecanbeusedasfollowsinyourhttpd.conffile:

SSLCertificateFile/path/to/this/server.crt

SSLCertificateKeyFile/path/to/this/server.key

3. Itisimportantthatyouareawarethatthisserver.keydoesnothaveanypassphrase.Toaddapassphrasetothekey,youshouldrunthefollowingcommand,andenter&verifythepassphraseasrequested.$opensslrsa-des3-inserver.key-out

server.key.new

$mvserver.key.newserver.key

Pleasebackuptheserver.keyfile,andthepassphraseyouentered,inasecurelocation.

HowdoIcreatearealSSLCertificate?Hereisastep-by-stepdescription:

1. MakesureOpenSSLisinstalledandinyourPATH.

2. CreateaRSAprivatekeyforyourApacheserver(willbeTriple-DESencryptedandPEMformatted):

$opensslgenrsa-des3-outserver.key1024

Pleasebackupthisserver.keyfileandthepass-phraseyouenteredinasecurelocation.YoucanseethedetailsofthisRSAprivatekeybyusingthecommand:

$opensslrsa-noout-text-inserver.key

Ifnecessary,youcanalsocreateadecryptedPEMversion(notrecommended)ofthisRSAprivatekeywith:

$opensslrsa-inserver.key-out

server.key.unsecure

3. CreateaCertificateSigningRequest(CSR)withtheserverRSAprivatekey(outputwillbePEMformatted):

$opensslreq-new-keyserver.key-out

server.csr

MakesureyouentertheFQDN("FullyQualifiedDomainName")oftheserverwhenOpenSSLpromptsyouforthe"CommonName",i.e.whenyougenerateaCSRforawebsitewhichwillbelateraccessedviahttps://www.foo.dom/,enter"www.foo.dom"here.YoucanseethedetailsofthisCSRbyusing

$opensslreq-noout-text-inserver.csr

4. YounowhavetosendthisCertificateSigningRequest(CSR)toaCertifyingAuthority(CA)tobesigned.OncetheCSRhasbeensigned,youwillhavearealCertificate,whichcanbeusedbyApache.YoucanhaveaCSRsignedbyacommercialCA,oryoucancreateyourownCAtosignit.CommercialCAsusuallyaskyoutoposttheCSRintoawebform,payforthesigning,andthensendasignedCertificate,whichyoucanstoreinaserver.crtfile.FormoreinformationaboutcommercialCAsseethefollowinglocations:

1. Verisignhttp://digitalid.verisign.com/server/apacheNotice.htm

2. Thawte

http://www.thawte.com/

3. CertiSignCertificadoraDigitalLtda.http://www.certisign.com.br

4. IKSGmbHhttp://www.iks-jena.de/leistungen/ca/

5. UptimeCommerceLtd.http://www.uptimecommerce.com

6. BelSignNV/SAhttp://www.belsign.be

FordetailsonhowtocreateyourownCA,andusethistosignaCSR,seebelow.OnceyourCSRhasbeensigned,youcanseethedetailsoftheCertificateasfollows:

$opensslx509-noout-text-inserver.crt

5. Youshouldnowhavetwofiles:server.keyandserver.crt.Thesecanbeusedasfollowsinyourhttpd.conffile:

SSLCertificateFile/path/to/this/server.crt

SSLCertificateKeyFile/path/to/this/server.key

Theserver.csrfileisnolongerneeded.

HowdoIcreateandusemyownCertificateAuthority(CA)?TheshortansweristousetheCA.shorCA.plscriptprovidedbyOpenSSL.Unlessyouhaveagoodreasonnotto,youshouldusetheseforpreference.Ifyoucannot,youcancreateaself-signedCertificateasfollows:

1. CreateaRSAprivatekeyforyourserver(willbeTriple-DESencryptedandPEMformatted):

$opensslgenrsa-des3-outserver.key1024

Pleasebackupthishost.keyfileandthepass-phraseyouenteredinasecurelocation.YoucanseethedetailsofthisRSAprivatekeybyusingthecommand:$opensslrsa-noout-text-inserver.key

Ifnecessary,youcanalsocreateadecryptedPEMversion(notrecommended)ofthisRSAprivatekeywith:

$opensslrsa-inserver.key-out

server.key.unsecure

2. Createaself-signedCertificate(X509structure)withtheRSAkeyyoujustcreated(outputwillbePEMformatted):

$opensslreq-new-x509-nodes-sha1-days

365-keyserver.key-outserver.crt

ThissignstheserverCSRandresultsinaserver.crtfile.YoucanseethedetailsofthisCertificateusing:

$opensslx509-noout-text-inserver.crt

HowcanIchangethepass-phraseonmyprivatekeyfile?Yousimplyhavetoreaditwiththeoldpass-phraseandwriteitagain,specifyingthenewpass-phrase.Youcanaccomplishthis

withthefollowingcommands:

$opensslrsa-des3-inserver.key-out

server.key.new

$mvserver.key.newserver.key

Thefirsttimeyou'reaskedforaPEMpass-phrase,youshouldentertheoldpass-phrase.Afterthat,you'llbeaskedagaintoenterapass-phrase-thistime,usethenewpass-phrase.Ifyouareaskedtoverifythepass-phrase,you'llneedtoenterthenewpass-phraseasecondtime.

HowcanIgetridofthepass-phrasedialogatApachestartuptime?Thereasonthisdialogpopsupatstartupandeveryre-startisthattheRSAprivatekeyinsideyourserver.keyfileisstoredinencryptedformatforsecurityreasons.Thepass-phraseisneededtodecryptthisfile,soitcanbereadandparsed.Removingthepass-phraseremovesalayerofsecurityfromyourserver-proceedwithcaution!

1. RemovetheencryptionfromtheRSAprivatekey(whilekeepingabackupcopyoftheoriginalfile):

$cpserver.keyserver.key.org

$opensslrsa-inserver.key.org-out

server.key

2. Makesuretheserver.keyfileisonlyreadablebyroot:

$chmod400server.key

Nowserver.keycontainsanunencryptedcopyofthekey.Ifyou

pointyourserveratthisfile,itwillnotpromptyouforapass-phrase.HOWEVER,ifanyonegetsthiskeytheywillbeabletoimpersonateyouonthenet.PLEASEmakesurethatthepermissionsonthisfilearesuchthatonlyrootorthewebserverusercanreadit(preferablygetyourwebservertostartasrootbutrunasanotheruser,andhavethekeyreadableonlybyroot).

Asanalternativeapproachyoucanusethe``SSLPassPhraseDialogexec:/path/to/program''facility.Bearinmindthatthisisneithermorenorlesssecure,ofcourse.

HowdoIverifythataprivatekeymatchesitsCertificate?Aprivatekeycontainsaseriesofnumbers.Twoofthesenumbersformthe"publickey",theothersarepartofthe"privatekey".The"publickey"bitsareincludedwhenyougenerateaCSR,andsubsequentlyformpartoftheassociatedCertificate.

TocheckthatthepublickeyinyourCertificatematchesthepublicportionofyourprivatekey,yousimplyneedtocomparethesenumbers.ToviewtheCertificateandthekeyrunthecommands:

$opensslx509-noout-text-inserver.crt

$opensslrsa-noout-text-inserver.key

The`modulus'andthe`publicexponent'portionsinthekeyandtheCertificatemustmatch.Asthepublicexponentisusually65537andit'sdifficulttovisuallycheckthatthelongmodulusnumbersarethesame,youcanusethefollowingapproach:

$opensslx509-noout-modulus-inserver.crt|

opensslmd5

$opensslrsa-noout-modulus-inserver.key|

opensslmd5

Thisleavesyouwithtworathershorternumberstocompare.Itis,intheory,possiblethatthesenumbersmaybethesame,withoutthemodulusnumbersbeingthesame,butthechancesofthisareoverwhelminglyremote.

ShouldyouwishtochecktowhichkeyorcertificateaparticularCSRbelongsyoucanperformthesamecalculationontheCSRasfollows:

$opensslreq-noout-modulus-inserver.csr|

opensslmd5

Whydoconnectionsfailwithan"alertbadcertificate"error?ErrorssuchasOpenSSL:error:14094412:SSLroutines:SSL3_READ_BYTES:sslv3alertbad

certificateintheSSLlogfile,areusuallycausedbyabrowserwhichisunabletohandletheservercertificate/private-key.Forexample,NetscapeNavigator3.xisunabletohandleRSAkeylengthsnotequalto1024bits.

Whydoesmy2048-bitprivatekeynotwork?TheprivatekeysizesforSSLmustbeeither512or1024bits,forcompatibilitywithcertainwebbrowsers.Akeysizeof1024bitsisrecommendedbecausekeyslargerthan1024bitsareincompatiblewithsomeversionsofNetscapeNavigatorandMicrosoftInternetExplorer,andwithotherbrowsersthatuseRSA'sBSAFEcryptographytoolkit.

WhyisclientauthenticationbrokenafterupgradingfromSSLeayversion0.8to0.9?TheCAcertificatesunderthepathyouconfiguredwithSSLCACertificatePatharefoundbySSLeaythroughhash

symlinks.Thesehashvaluesaregeneratedbythe`opensslx509-noout-hash'command.However,thealgorithmusedtocalculatethehashforacertificatechangedbetweenSSLeay0.8and0.9.Youwillneedtoremovealloldhashsymlinksandcreatenewonesafterupgrading.UsetheMakefileprovidedbymod_ssl.

HowcanIconvertacertificatefromPEMtoDERformat?ThedefaultcertificateformatforSSLeay/OpenSSLisPEM,whichissimplyBase64encodedDER,withheaderandfooterlines.Forsomeapplications(e.g.MicrosoftInternetExplorer)youneedthecertificateinplainDERformat.YoucanconvertaPEMfilecert.pemintothecorrespondingDERfilecert.derusingthefollowingcommand:$opensslx509-incert.pem-outcert.der-outformDER

Whycan'tIfindthegetcaorgetverisignprogramsmentionedbyVerisign,forinstallingmyVerisigncertificate?VerisignhasneverprovidedspecificinstructionsforApache+mod_ssl.TheinstructionsprovidedareforC2Net'sStronghold(acommercialApachebasedserverwithSSLsupport).

Toinstallyourcertificate,allyouneedtodoistosavethecertificatetoafile,andgivethenameofthatfiletotheSSLCertificateFiledirective.Youwillalsoneedtogiveitthekeyfile.Formoreinformation,seetheSSLCertificateKeyFiledirective.

CanIusetheServerGatedCryptography(SGC)

facility(akaVerisignGlobalID)withmod_ssl?Yes.mod_sslhasincludedsupportfortheSGCfacilitysinceversion2.1.Nospecialconfigurationisrequired-justusetheGlobalIDasyourservercertificate.Thestepupoftheclientsisthenautomaticallyhandledbymod_sslatrun-time.

WhydobrowserscomplainthattheycannotverifymyVerisignGlobalIDservercertificate?VerisignusesanintermediateCAcertificatebetweentherootCAcertificate(whichisinstalledinthebrowsers)andtheservercertificate(whichyouinstalledontheserver).YoushouldhavereceivedthisadditionalCAcertificatefromVerisign.Ifnot,complaintothem.Then,configurethiscertificatewiththeSSLCertificateChainFiledirective.ThisensuresthattheintermediateCAcertificateissenttothebrowser,fillingthegapinthecertificatechain.

TheSSLProtocol

WhydoIgetlotsofrandomSSLprotocolerrorsunderheavyserverload?Whydoesmywebserverhaveahigherload,nowthatitservesSSLencryptedtraffic?WhydoHTTPSconnectionstomyserversometimestakeupto30secondstoestablishaconnection?WhatSSLCiphersaresupportedbymod_ssl?WhydoIget``nosharedcipher''errors,whentryingtouseAnonymousDiffie-Hellman(ADH)ciphers?WhydoIgeta'nosharedciphers'errorwhenconnectingtomynewlyinstalledserver?Whycan'tIuseSSLwithname-based/non-IP-basedvirtualhosts?WhyisitnotpossibletouseName-BasedVirtualHostingtoidentifydifferentSSLvirtualhosts?HowdoIgetSSLcompressionworking?WhenIuseBasicAuthenticationoverHTTPSthelockiconinNetscapebrowsersstaysunlockedwhenthedialogpopsup.Doesthismeantheusername/passwordisbeingsentunencrypted?WhydoIgetI/OerrorswhenconnectingviaHTTPStoanApache+mod_sslserverwithMicrosoftInternetExplorer(MSIE)?WhydoIgetI/Oerrors,orthemessage"Netscapehasencounteredbaddatafromtheserver",whenconnectingviaHTTPStoanApache+mod_sslserverwithNetscapeNavigator?

WhydoIgetlotsofrandomSSLprotocolerrorsunderheavyserverload?Therecanbeanumberofreasonsforthis,butthemainoneisproblemswiththeSSLsessionCachespecifiedbythe

SSLSessionCachedirective.TheDBMsessioncacheisthemostlikelysourceoftheproblem,sousingtheSHMsessioncache(ornocacheatall)mayhelp.

Whydoesmywebserverhaveahigherload,nowthatitservesSSLencryptedtraffic?SSLusesstrongcryptographicencryption,whichnecessitatesalotofnumbercrunching.WhenyourequestawebpageviaHTTPS,everything(eventheimages)isencryptedbeforeitistransferred.SoincreasedHTTPStrafficleadstoloadincreases.

WhydoHTTPSconnectionstomyserversometimestakeupto30secondstoestablishaconnection?Thisisusuallycausedbya/dev/randomdeviceforSSLRandomSeedwhichblockstheread(2)calluntilenoughentropyisavailabletoservicetherequest.MoreinformationisavailableinthereferencemanualfortheSSLRandomSeeddirective.

WhatSSLCiphersaresupportedbymod_ssl?Usually,anySSLcipherssupportedbytheversionofOpenSSLinuse,arealsosupportedbymod_ssl.WhichciphersareavailablecandependonthewayyoubuiltOpenSSL.Typically,atleastthefollowingciphersaresupported:

1. RC4withMD5

2. RC4withMD5(exportversionrestrictedto40-bitkey)

3. RC2withMD5

4. RC2withMD5(exportversionrestrictedto40-bitkey)

5. IDEAwithMD5

6. DESwithMD5

7. Triple-DESwithMD5

Todeterminetheactuallistofciphersavailable,youshouldrunthefollowing:

$opensslciphers-v

WhydoIget``nosharedcipher''errors,whentryingtouseAnonymousDiffie-Hellman(ADH)ciphers?Bydefault,OpenSSLdoesnotallowADHciphers,forsecurityreasons.Pleasebesureyouareawareofthepotentialside-effectsifyouchoosetoenabletheseciphers.

InordertouseAnonymousDiffie-Hellman(ADH)ciphers,youmustbuildOpenSSLwith``-DSSL_ALLOW_ADH'',andthenadd``ADH''intoyourSSLCipherSuite.

WhydoIgeta'nosharedciphers'errorwhenconnectingtomynewlyinstalledserver?EitheryouhavemadeamistakewithyourSSLCipherSuitedirective(compareitwiththepre-configuredexampleinhttpd.conf-dist)oryouchosetouseDSA/DHalgorithmsinsteadofRSAwhenyougeneratedyourprivatekeyandignoredoroverlookedthewarnings.IfyouhavechosenDSA/DH,thenyourservercannotcommunicateusingRSA-basedSSLciphers(atleastuntilyouconfigureanadditionalRSA-basedcertificate/keypair).ModernbrowserslikeNSorIEcanonlycommunicateoverSSLusingRSAciphers.Theresultisthe"nosharedciphers"error.Tofixthis,regenerateyourservercertificate/keypair,usingtheRSAalgorithm.

Whycan'tIuseSSLwithname-based/non-IP-basedvirtualhosts?Thereasonisverytechnical,andasomewhat"chickenandegg"problem.TheSSLprotocollayerstaysbelowtheHTTPprotocollayerandencapsulatesHTTP.WhenanSSLconnection(HTTPS)isestablishedApache/mod_sslhastonegotiatetheSSLprotocolparameterswiththeclient.Forthis,mod_sslhastoconsulttheconfigurationofthevirtualserver(forinstanceithastolookfortheciphersuite,theservercertificate,etc.).ButinordertogotothecorrectvirtualserverApachehastoknowtheHostHTTPheaderfield.Todothis,theHTTPrequestheaderhastoberead.ThiscannotbedonebeforetheSSLhandshakeisfinished,buttheinformationisneededinordertocompletetheSSLhandshakephase.Bingo!

WhyisitnotpossibletouseName-BasedVirtualHostingtoidentifydifferentSSLvirtualhosts?Name-BasedVirtualHostingisaverypopularmethodofidentifyingdifferentvirtualhosts.ItallowsyoutousethesameIPaddressandthesameportnumberformanydifferentsites.WhenpeoplemoveontoSSL,itseemsnaturaltoassumethatthesamemethodcanbeusedtohavelotsofdifferentSSLvirtualhostsonthesameserver.

Itcomesasratherashocktolearnthatitisimpossible.

ThereasonisthattheSSLprotocolisaseparatelayerwhichencapsulatestheHTTPprotocol.SotheSSLsessionisaseparatetransaction,thattakesplacebeforetheHTTPsessionhasbegun.TheserverreceivesanSSLrequestonIPaddressXandportY(usually443).SincetheSSLrequestdoesnotcontainanyHost:field,theserverhasnowaytodecidewhichSSLvirtualhosttouse.Usually,itwilljustusethefirstoneitfinds,whichmatchestheportandIPaddressspecified.

Youcan,ofcourse,useName-BasedVirtualHostingtoidentifymanynon-SSLvirtualhosts(allonport80,forexample)andthenhaveasingleSSLvirtualhost(onport443).Butifyoudothis,youmustmakesuretoputthenon-SSLportnumberontheNameVirtualHostdirective,e.g.

NameVirtualHost192.168.1.1:80

Otherworkaroundsolutionsinclude:

UsingseparateIPaddressesfordifferentSSLhosts.UsingdifferentportnumbersfordifferentSSLhosts.

HowdoIgetSSLcompressionworking?AlthoughSSLcompressionnegotiationwasdefinedinthespecificationofSSLv2andTLS,ittookuntilMay2004forRFC3749todefineDEFLATEasanegotiablestandardcompressionmethod.

OpenSSL0.9.8startedtosupportthisbydefaultwhencompiledwiththezliboption.Ifboththeclientandtheserversupportcompression,itwillbeused.However,mostclientsstilltrytoinitiallyconnectwithanSSLv2Hello.AsSSLv2didnotincludeanarrayofpreferedcompressionalgorithmsinitshandshake,compressioncannotbenegotiatedwiththeseclients.IftheclientdisablessupportforSSLv2,eitheranSSLv3orTLSHellomaybesent,dependingonwhichSSLlibraryisused,andcompressionmaybesetup.YoucanverifywhetherclientsmakeuseofSSLcompressionbyloggingthe%{SSL_COMPRESS_METHOD}xvariable.

WhenIuseBasicAuthenticationoverHTTPSthelockiconinNetscapebrowsersstaysunlockedwhenthedialogpopsup.Doesthismeanthe

username/passwordisbeingsentunencrypted?No,theusername/passwordistransmittedencrypted.TheiconinNetscapebrowsersisnotactuallysynchronizedwiththeSSL/TLSlayer.Itonlytogglestothelockedstatewhenthefirstpartoftheactualwebpagedataistransferred,whichmayconfusepeople.TheBasicAuthenticationfacilityispartoftheHTTPlayer,whichisabovetheSSL/TLSlayerinHTTPS.BeforeanyHTTPdatacommunicationtakesplaceinHTTPS,theSSL/TLSlayerhasalreadycompleteditshandshakephase,andswitchedtoencryptedcommunication.Sodon'tbeconfusedbythisicon.

WhydoIgetI/OerrorswhenconnectingviaHTTPStoanApache+mod_sslserverwithMicrosoftInternetExplorer(MSIE)?ThefirstreasonisthattheSSLimplementationinsomeMSIEversionshassomesubtlebugsrelatedtotheHTTPkeep-alivefacilityandtheSSLclosenotifyalertsonsocketconnectionclose.AdditionallytheinteractionbetweenSSLandHTTP/1.1featuresareproblematicinsomeMSIEversions.YoucanworkaroundtheseproblemsbyforcingApachenottouseHTTP/1.1,keep-aliveconnectionsorsendtheSSLclosenotifymessagestoMSIEclients.ThiscanbedonebyusingthefollowingdirectiveinyourSSL-awarevirtualhostsection:

SetEnvIfUser-Agent".*MSIE.*"\

nokeepalivessl-unclean-shutdown\

downgrade-1.0force-response-1.0

Further,someMSIEversionshaveproblemswithparticularciphers.Unfortunately,itisnotpossibletoimplementaMSIE-specificworkaroundforthis,becausetheciphersareneededasearlyastheSSLhandshakephase.SoaMSIE-specificSetEnvIfwon'tsolvetheseproblems.Instead,youwillhavetomakemoredrasticadjustmentstotheglobalparameters.Before

youdecidetodothis,makesureyourclientsreallyhaveproblems.Ifnot,donotmakethesechanges-theywillaffectallyourclients,MSIEorotherwise.

Thenextproblemisthat56bitexportversionsofMSIE5.xbrowsershaveabrokenSSLv3implementation,whichinteractsbadlywithOpenSSLversionsgreaterthan0.9.4.Youcanacceptthisandrequireyourclientstoupgradetheirbrowsers,youcandowngradetoOpenSSL0.9.4(notadvised),oryoucanworkaroundthis,acceptingthatyourworkaroundwillaffectotherbrowserstoo:

SSLProtocolall-SSLv3

willcompletelydisablestheSSLv3protocolandallowthosebrowserstowork.Abetterworkaroundistodisableonlythosecipherswhichcausetrouble.

SSLCipherSuite

ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP

ThisalsoallowsthebrokenMSIEversionstowork,butonlyremovesthenewer56bitTLSciphers.

AnotherproblemwithMSIE5.xclientsisthattheyrefusetoconnecttoURLsoftheformhttps://12.34.56.78/(whereIP-addressesareusedinsteadofthehostname),iftheserverisusingtheServerGatedCryptography(SGC)facility.Thiscanonlybeavoidedbyusingthefullyqualifieddomainname(FQDN)ofthewebsiteinhyperlinksinstead,becauseMSIE5.xhasanerrorinthewayithandlestheSGCnegotiation.

AndfinallythereareversionsofMSIEwhichseemtorequirethatanSSLsessioncanbereused(atotallynonstandard-conformingbehaviour,ofcourse).ConnectingwiththoseMSIEversionsonly

workifaSSLsessioncacheisused.So,asawork-around,makesureyouareusingasessioncache(seetheSSLSessionCachedirective).

WhydoIgetI/Oerrors,orthemessage"Netscapehasencounteredbaddatafromtheserver",whenconnectingviaHTTPStoanApache+mod_sslserverwithNetscapeNavigator?Thisusuallyoccurswhenyouhavecreatedanewservercertificateforagivendomain,buthadpreviouslytoldyourbrowsertoalwaysaccepttheoldservercertificate.Onceyoucleartheentryfortheoldcertificatefromyourbrowser,everythingshouldbefine.Netscape'sSSLimplementationiscorrect,sowhenyouencounterI/OerrorswithNetscapeNavigatoritisusuallycausedbytheconfiguredcertificates.

mod_sslSupport

Whatinformationresourcesareavailableincaseofmod_sslproblems?Whatsupportcontactsareavailableincaseofmod_sslproblems?WhatinformationshouldIprovidewhenwritingabugreport?Ihadacoredump,canyouhelpme?HowdoIgetabacktrace,tohelpfindthereasonformycoredump?

Whatinformationresourcesareavailableincaseofmod_sslproblems?Thefollowinginformationresourcesareavailable.Incaseofproblemsyoushouldsearchherefirst.

AnswersintheUserManual'sF.A.Q.List(this)http://httpd.apache.org/docs/2.0/ssl/ssl_faq.htmlFirstchecktheF.A.Q.(thistext).Ifyourproblemisacommonone,itmayhavebeenansweredseveraltimesbefore,andbeenincludedinthisdoc.

Postingsfromthemodssl-usersSupportMailingListhttp://www.modssl.org/support/

Searchforyourprobleminthearchivesofthemodssl-usersmailinglist.You'reprobablynotthefirstpersontohavehadthisproblem!

Whatsupportcontactsareavailableincaseofmod_sslproblems?Thefollowinglistsallsupportpossibilitiesformod_ssl,inorderofpreference.Pleasegothroughthesepossibilitiesinthisorder-don'tjustpicktheoneyoulikethelookof.

1. SendaProblemReporttothemodssl-usersSupportMailing

Listmodssl-users@modssl.orgThisisthepreferredwayofsubmittingyourproblemreport,becausethisway,otherscanseetheproblem,andlearnfromanyanswers.Youmustsubscribetothelistfirst,butyoucantheneasilydiscussyourproblemwithboththeauthorandthewholemod_sslusercommunity.

2. SendaProblemReporttotheApachehttpdUsersSupportMailingListusers@httpd.apache.orgThisisthesecondwayofsubmittingyourproblemreport.Again,youmustsubscribetothelistfirst,butyoucantheneasilydiscussyourproblemwiththewholeApachehttpdusercommunity.

3. WriteaProblemReportintheBugDatabasehttp://httpd.apache.org/bug_report.htmlThisisthelastwayofsubmittingyourproblemreport.Youshouldonlydothisifyou'vealreadypostedtothemailinglists,andhadnosuccess.Pleasefollowtheinstructionsontheabovepagecarefully.

WhatinformationshouldIprovidewhenwritingabugreport?Youshouldalwaysprovideatleastthefollowinginformation:

ApacheandOpenSSLversioninformationTheApacheversioncanbedeterminedbyrunninghttpd-v.TheOpenSSLversioncanbedeterminedbyrunningopensslversion.Alternatively,ifyouhaveLynxinstalled,youcanrunthecommandlynx-mime_headerhttp://localhost/|grepServertogatherthisinformationinasinglestep.

ThedetailsonhowyoubuiltandinstalledApache+mod_ssl+OpenSSL

Forthisyoucanprovidealogfileofyourterminalsessionwhichshowstheconfigurationandinstallsteps.Ifthisisnotpossible,youshouldatleastprovidetheconfigurecommandlineyouused.

IncaseofcoredumpspleaseincludeaBacktraceIfyourApache+mod_ssl+OpenSSLdumpsitscore,pleaseattachastack-frame``backtrace''(seebelowforinformationonhowtogetthis).Thisinformationisrequiredinordertofindareasonforyourcoredump.

AdetaileddescriptionofyourproblemDon'tlaugh,wereallymeanit!Manyproblemreportsdon'tincludeadescriptionofwhattheactualproblemis.Withoutthis,it'sverydifficultforanyonetohelpyou.So,it'sinyourowninterest(youwanttheproblembesolved,don'tyou?)toincludeasmuchdetailaspossible,please.Ofcourse,youshouldstillincludealltheessentialsabovetoo.

Ihadacoredump,canyouhelpme?Ingeneralno,atleastnotunlessyouprovidemoredetailsaboutthecodelocationwhereApachedumpedcore.Whatisusuallyalwaysrequiredinordertohelpyouisabacktrace(seenextquestion).Withoutthisinformationitismostlyimpossibletofindtheproblemandhelpyouinfixingit.

HowdoIgetabacktrace,tohelpfindthereasonformycoredump?Followingarethestepsyouwillneedtocomplete,togetabacktrace:

1. Makesureyouhavedebuggingsymbolsavailable,atleastin

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Apache.OnplatformswhereyouuseGCC/GDB,youwillhavetobuildApache+mod_sslwith``OPTIM="-g-ggdb3"''togetthis.Onotherplatformsatleast``OPTIM="-g"''isneeded.

2. Starttheserverandtrytoreproducethecore-dump.Forthisyoumaywanttouseadirectivelike``CoreDumpDirectory/tmp''tomakesurethatthecore-dumpfilecanbewritten.Thisshouldresultina/tmp/coreor/tmp/httpd.corefile.Ifyoudon'tgetoneofthese,tryrunningyourserverunderanon-rootUID.Manymodernkernelsdonotallowaprocesstodumpcoreafterithasdoneasetuid()(unlessitdoesanexec())forsecurityreasons(therecanbeprivilegedinformationleftoverinmemory).Ifnecessary,youcanrun/path/to/httpd-XmanuallytoforceApachetonotfork.

3. Analyzethecore-dump.Forthis,rungdb/path/to/httpd/tmp/httpd.coreorasimilarcommand.InGDB,allyouhavetodothenistoenterbt,andvoila,yougetthebacktrace.Forotherdebuggersconsultyourlocaldebuggermanual.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >How-To/

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

mod_auth

mod_access

Allow

AuthGroupFile

AuthName

AuthType

AuthUserFile

Deny

Options

Require

( <Directory>

.htaccess

AllowOverride

AllowOverrideAuthConfig

/usr/local/apache/passwd

Apache htpasswdApache

htpasswd-c/usr/local/apache/passwd/passwordsrbowen

htpasswd

#htpasswd-c/usr/local/apache/passwd/passwordsrbowen

Newpassword:mypassword

Re-typenewpassword:mypassword

Addingpasswordforuserrbowen

htpasswd /usr/local/apache/bin/htpasswd

/usr/local/apache/htdocs/secret/usr/local/apache/htdocs/secret/.htaccesshttpd.conf<Directory /usr/local/apache/apache/htdocs/secret>

AuthTypeBasic

AuthName"RestrictedFiles"

AuthUserFile/usr/local/apache/passwd/passwords

Requireuserrbowen

AuthTypeBasic mod_auth_digest Digest

AuthName Realm(:) Realm

"RestrictedFiles" "RestrictedFiles"

Realm

AuthUserFile htpasswd mod_auth_dbm AuthDBMUserFileApache

Require

( rbowen)

GroupName:rbowendpittssungorshersey

htpasswd/usr/local/apache/passwd/passwordsdpitts

.htaccess

AuthTypeBasic

AuthName"ByInvitationOnly"

AuthUserFile/usr/local/apache/passwd/passwords

AuthGroupFile/usr/local/apache/passwd/groups

RequiregroupGroupName

GroupName password

Requirevalid-user

requireuserrbowen AuthUserFile

Basic

?

Allow Deny

Allowfromaddress

addressIP (IP)

Denyfrom205.252.46.165

IP

Denyfromhost.example.com

Denyfrom192.101.205

Denyfromcyberthugs.commoreidiots.com

Denyfromke

Order Deny Allow

Orderdeny,allow

Denyfromall

Allowfromdev.example.com

Allow

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

mod_auth

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >How-To/

ApacheTutorial:CGI

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

mod_alias

mod_cgi

AddHandler

Options

ScriptAlias

CGI(CommonGatewayInterface)

CGIApache

CGICGI Apache

ScriptAliasScriptAlias CGIApache

ScriptAlias:

ScriptAlias/cgi-bin//usr/local/apache2/cgi-bin/

Apache httpd.conf

Alias Alias ScriptAliasAlias ScriptAlias ScriptAlias

/cgi-bin/CGIApache

URL http://dev.rcbowen.com/cgi-bin/test.plApache /usr/local/apache2/cgi-bin/test.pl Apache

ScriptAliasCGICGI ScriptAliasUserDir

CGI AddHandler

Options ExecCGI

CGIOptions Options CGI:

<Directory/usr/local/apache2/htdocs/somedir>

Options+ExecCGI

</Directory>

CGI ApacheCGIplCGI :

AddHandlercgi-script.cgi.pl

.htaccessfiles

.htaccess httpd.confCGI

User.cgiCGI

<Directory/home/*/public_html>

Options+ExecCGI

AddHandlercgi-script.cgi

</Directory>

cgi-bin CGI

<Directory/home/*/public_html/cgi-bin>

OptionsExecCGI

SetHandlercgi-script

</Directory>

CGI

CGI

CGIMIME-type

Content-type:text/html

HTML

CGI

CGI1CGI first.pl

#!/usr/bin/perl

print"Content-type:text/html\n\n";

print"Hello,World.";

Perl 12content-type World."

http://www.example.com/cgi-bin/first.pl

Hello,World.1

!

CGI :

CGI!

CGI"POSTMethodNotAllowed"CGIApache

"Forbidden" Apache

"InternalServerError"Apache "Prematureendofscriptheaders" CGI HTTP

-:

chmoda+xfirst.pl

CGI CGI

( perl)CGI1:

#!/usr/bin/perl

CGI CGI

cd/usr/local/apache2/cgi-bin

./first.pl

(perl Apache

Content-Type HTTPendofscriptheaders CGI

Suexecsuexec scriptheaders

suexec apachectl-V SUEXEC_BIN Apachesuexecsuexec

suexec suexec suexec suexec-Vsuexec

?

CGI

CGI WebSite)CGI

CGI

PerlCGI Apache

#!/usr/bin/perl

print"Content-type:text/html\n\n";

foreach$key(keys%ENV){

print"$key-->$ENV{$key}<br>";

}

STDINSTDOUT (STDIN)( STDOUT)

CGI POST STDIN

(=)(&)

name=Rich%20Bowen&city=Lexington&state=KY&sidekick=Squirrel%20Monkey

URL QUERY_STRING

GET POST FORM METHOD

CGI

CGI/

CGI

PerlCGI CPAN

CCGI

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

CGICGI Usenet HTMLWritersGuide -servershttp://www.hwg.org/lists/hwg-servers/

CGI

CGI

Apache CGIApache

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >How-To/

Apache:ServerSideIncludes

HTML

mod_include

mod_cgi

mod_expires

Options

XBitHack

AddType

SetOutputFilter

BrowserMatchNoCase

SSIServerSideIncludes SSISSI

SSISSI

SSI?

SSI(ServerSideIncludes)HTML HTML

SSI

SSI

SSI httpd.conf .htaccess:

Options+Includes

SSI ApacheOptions

SSI Apache

AddTypetext/html.shtml

AddOutputFilterINCLUDES.shtml

SSI

XBitHack:

XBitHackon

XBitHack SSIApachechmod

chmod+xpagename.html

.htmlSSIApacheXBitHack SSI

Windows

ApacheSSI HTTP

1. XBitHackFull

2. mod_expires

SSI

SSI:

<!--#elementattribute=valueattribute=value...-->

HTMLSSI

element

<!--#echovar="DATE_LOCAL"-->

echo CGI

config timefmt

<!--#configtimefmt="%A%B%d,%Y"-->

Todayis<!--#echovar="DATE_LOCAL"-->

Thisdocumentlastmodified<!--#flastmodfile="index.html"-->

timefmt

CGI``'' CGISSI

<!--#includevirtual="/cgi-bin/counter.pl"-->

SSIHTML

? SSI

<!--#configtimefmt="%A%B%d,%Y"-->

Thisfilelastmodified<!--#flastmodfile="ssi.shtml"-->

ssi.shtml

<!--#configtimefmt="%D"-->

Thisfilelastmodified<!--#echovar="LAST_MODIFIED"-->

timefmt strftime

file/

<!--#includevirtual="/footer.html"-->

LAST_MODIFIED

?

config config

SSI

[anerroroccurredwhileprocessingthisdirective]

config errmsg:

<!--#configerrmsg="[Itappearsthatyoudon'tknowhowtouse

SSI]"-->

SSI

config sizefmt abbrev

CGISSI Win32DOS)

<pre>

<!--#execcmd="ls"-->

</pre>

Windows

<pre>

<!--#execcmd="dir"-->

</pre>

Windows

exec ``''IncludesNOEXEC SSI exec

SSI

ApacheSSI

Apache1.2 Apache1.2

set

<!--#setvar="name"value="Rich"-->

( LAST_MODIFIED

<!--#setvar="modified"value="$LAST_MODIFIED"-->

($)

<!--#setvar="cost"value="\$100"-->

<!--#setvar="date"value="${DATE_LOCAL}_${DATE_GMT}"-->

endif

:

<!--#ifexpr="test_condition"-->

<!--#elifexpr="test_condition"-->

<!--#else-->

<!--#endif-->

test_condition ``''

:

BrowserMatchNoCasemacintoshMac

BrowserMatchNoCaseMSIEInternetExplorer

Macintosh

SSI:

<!--#ifexpr="${Mac}&&${InternetExplorer}"-->

Apologetictextgoeshere

<!--#else-->

CoolJavaScriptcodegoeshere

<!--#endif-->

MacIE JavaScriptMacIE

( )

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

SSICGI

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >How-To/

Apache:.htaccess

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

.htaccess

.htaccess

core

mod_auth

mod_cgi

mod_include

mod_mime

AccessFileName

AllowOverride

Options

AddHandler

SetHandler

AuthType

AuthName

AuthUserFile

AuthGroupFile

Require

.htaccess/

.htaccess()

:

.htaccess AccessFileName:

AccessFileName.config

.htaccess AllowOverride

AddDefaultCharset .htaccessFileInfo .htaccess FileInfo

:

: ,,,.htaccess: FileInfo

.htaccess ".htaccess"

.htaccess()

.htaccess

.htaccess rootISP

.htaccess .htaccess

.htaccess

AllowOverride .htaccessApache.htaccess .htaccess

Apache /www/htdocs/example Apache

/.htaccess

/www/.htaccess

/www/htdocs/.htaccess

/www/htdocs/example/.htaccess

.htaccess /www/htdocs/example<Directory/www/htdocs/example> :

/www/htdocs/example .htaccess:

/www/htdocs/example.htaccessAddTypetext/example.exm

httpd.conffile<Directory/www/htdocs/example>

AddTypetext/example.exm

</Directory>

AllowOverride none .htaccess

AllowOverrideNone

.htaccess .htaccess .htaccess .htaccess

:

/www/htdocs/example1 .htaccess:

Options+ExecCGI

(: .htaccess" Options")

/www/htdocs/example1/example2 .htaccess

OptionsIncludes

.htaccess /www/htdocs/example1/example2

CGI OptionsIncludes

.htaccess

.htaccess

"AllowOverrideAuthConfig"

.htaccess:

AuthTypeBasic

AuthName"PasswordRequired"

AuthUserFile/www/passwords/password.file

AuthGroupFile/www/passwords/group.file

RequireGroupadmins

AllowOverrideAuthConfig

SSI

.htaccess SSI

Options+Includes

AddTypetext/htmlshtml

AddHandlerserver-parsedshtml

AllowOverrideOptions

SSI SSI

CGI

CGI :

Options+ExecCGI

AddHandlercgi-scriptcgipl

CGI :

Options+ExecCGI

SetHandlercgi-script

AllowOverrideOptions

CGI CGI

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

.htaccess

AllowOverride.htaccess

Apache

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >How-To/

UserDir "username" UserDir

URL

mod_userdir UserDir

DirectoryMatch

AllowOverride

UserDir

UserDir

:

UserDirpublic_html

URLhttp://example.com/~rbowen/file.html/home/rbowen/public_html/file.html

:

UserDir/var/html

URLhttp://example.com/~rbowen/file.html/var/html/rbowen/file.html

(*) :

UserDir/var/www/*/docs

URLhttp://example.com/~rbowen/file.html/var/www/rbowen/docs/file.html

UserDir :

UserDirenabled

UserDirdisabledrootjrofish

dissabled UserDir

UserDirdisabled

UserDirenabledrbowenkrietz

UserDir

CGI

cgi-bin <Directory>CGI

<Directory/home/*/public_html/cgi-bin/>

OptionsExecCGI

SetHandlercgi-script

</Directory>

UserDir public_html CGI

http://example.com/~rbowen/cgi-bin/example.cgi

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

.htaccess

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>MiscellaneousDocumentation

ApacheTutorials

Warning:

Thisdocumenthasnotbeenfullyupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

Thefollowingdocumentsgiveyoustep-by-stepinstructionsonhowtoaccomplishcommontaskswiththeApacheHTTPserver.ManyofthesedocumentsarelocatedatexternalsitesandarenottheworkoftheApacheSoftwareFoundation.Copyrighttodocumentsonexternalsitesisownedbytheauthorsortheirassignees.PleaseconsulttheofficialApacheServerdocumentationtoverifywhatyoureadonexternalsites.

Installation&GettingStarted

GettingStartedwithApache1.3(ApacheToday)ConfiguringYourApacheServerInstallation(ApacheToday)Getting,Installing,andRunningApache(onUnix)(O'ReillyNetworkApacheDevCenter)MaximumApache:GettingStarted(CNETBuilder.com)HowtoBuildtheApacheofYourDreams(DeveloperShed)

BasicConfiguration

AnAmbleThroughApacheConfiguration(O'ReillyNetworkApacheDevCenter)Using.htaccessFileswithApache(ApacheToday)SettingUpVirtualHosts(ApacheToday)MaximumApache:ConfigureApache(CNETBuilder.com)GettingMoreOutofApache(DeveloperShed)

CGIandSSI

DynamicContentwithCGI(ApacheToday)TheIdiot'sGuidetoSolvingPerlCGIProblems(CPAN)ExecutingCGIScriptsasOtherUsers(LinuxPlanet)CGIProgrammingFAQ(WebDesignGroup)IntroductiontoServerSideIncludesPart1-Part2(ApacheToday)AdvancedSSITechniques(ApacheToday)SettingupCGIandSSIwithApache(CNETBuilder.com)

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

OtherFeatures

ContentNegotiationExplained(Apacheweek)UsingApacheImagemaps(Apacheweek)KeepingYourImagesfromAdorningOtherSites(ApacheToday)LanguageNegotiationNotes(AlanJ.Flavell)

Ifyouhaveapointertoanaccurateandwell-writtentutorialnotincludedhere,pleaseletusknowbysubmittingittotheApacheBugDatabase.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>PlatformSpecificNotes

UsingApachewithMicrosoftWindows

Thisdocumentexplainshowtoinstall,configureandrunApache2.0underMicrosoftWindows.Ifyoufindanybugs,orwishtocontributeinotherways,pleaseuseourbugreportingpage.

ThisdocumentassumesthatyouareinstallingabinarydistributionofApache.IfyouwanttocompileApacheyourself(possiblytohelpwithdevelopmentortrackingdownbugs),seeCompilingApacheforMicrosoftWindows.

BecauseofthecurrentversioningpoliciesonMicrosoftWindowsoperatingsystemfamilies,thisdocumentassumesthefollowing:

WindowsNT:ThismeansallversionsofWindowsthatarebasedontheWindowsNTkernel.IncludesWindowsNT,Windows2000,WindowsXPandWindows.NetServer2003.Windows9x:Thismeansolder,consumer-orientedversionsofWindows.IncludesWindows95(alsoOSR2),Windows98andWindowsME.

OperatingSystemRequirements

TheprimaryWindowsplatformforrunningApache2.0isWindowsNT.Thebinaryinstalleronlyworkswiththex86familyofprocessors,suchasIntelandAMDprocessors.RunningApacheonWindows9xisnotthoroughlytested,anditisneverrecommendedonproductionsystems.

Onalloperatingsystems,TCP/IPnetworkingmustbeinstalledandworking.IfrunningonWindows95,theWinsock2upgrademustbeinstalled.Winsock2forWindows95canbedownloadedfromhere.

OnWindowsNT4.0,installingServicePack6isstronglyrecommended,asServicePack4createdknownissueswithTCP/IPandWinsockintegritythatwereresolvedinlaterServicePacks.

DownloadingApacheforWindows

InformationonthelatestversionsofApachecanbefoundonthewebsiteoftheApachewebserverathttp://httpd.apache.org/download.cgi.Thereyouwillfindthecurrentrelease,aswellasmorerecentalphaorbetatestversions,andalistofHTTPandFTPmirrorsfromwhichyoucandownloadtheApachewebserver.Pleaseuseamirrorneartoyouforafastandreliabledownload.

ForWindowsinstallationsyoushoulddownloadtheversionofApacheforWindowswiththe.msiextension.ThisisasingleMicrosoftInstallerfile,whichcontainsaready-to-runversionofApache.Thereisaseparate.zipfile,whichcontainsonlythesourcecode.YoucancompileApacheyourselfwiththeMicrosoftVisualC++(VisualStudio)tools.

InstallingApacheforWindows

YouneedMicrosoftInstaller1.2orabovefortheinstallationtowork.OnWindows9xyoucanupdateyourMicrosoftInstallertoversion2.0hereandonWindowsNT4.0and2000theversion2.0updatecanbefoundhere.WindowsXPdoesnotneedthisupdate.

NotethatyoucannotinstalltwoversionsofApache2.0onthesamecomputerwiththebinaryinstaller.Youcan,however,installaversionofthe1.3seriesandaversionofthe2.0seriesonthesamecomputerwithoutproblems.Ifyouneedtohavetwodifferent2.0versionsonthesamecomputer,youhavetocompileandinstallApachefromthesource.

RuntheApache.msifileyoudownloadedabove.Theinstallationwillaskyouforthesethings:

1. NetworkDomain.EntertheDNSdomaininwhichyourserverisorwillberegisteredin.Forexample,ifyourserver'sfullDNSnameisserver.mydomain.net,youwouldtypemydomain.nethere.

2. ServerName.Yourserver'sfullDNSname.Fromtheexampleabove,youwouldtypeserver.mydomain.nethere.

3. Administrator'sEmailAddress.Entertheserveradministrator'sorwebmaster'semailaddresshere.Thisaddresswillbedisplayedalongwitherrormessagestotheclientbydefault.

4. ForwhomtoinstallApacheSelectforAllUsers,onPort80,asaService-Recommendedifyou'dlikeyournewApachetolistenatport80forincomingtraffic.Itwillrunasaservice(thatis,Apachewillrunevenifnooneis

loggedinontheserveratthemoment)SelectonlyfortheCurrentUser,onPort8080,whenstarted

Manuallyifyou'dliketoinstallApacheforyourpersonalexperimentingorifyoualreadyhaveanotherWWWserverrunningonport80.

5. Theinstallationtype.SelectTypicalforeverythingexceptthesourcecodeandlibrariesformoduledevelopment.WithCustomyoucanspecifywhattoinstall.Afullinstallwillrequireabout13megabytesoffreediskspace.Thisdoesnotincludethesizeofyourwebsite(s).

6. Wheretoinstall.ThedefaultpathisC:\ProgramFiles\ApacheGroupunderwhichadirectorycalledApache2willbecreatedbydefault.

Duringtheinstallation,Apachewillconfigurethefilesintheconfsubdirectorytoreflectthechoseninstallationdirectory.However,ifanyoftheconfigurationfilesinthisdirectoryalreadyexist,theywillnotbeoverwritten.Instead,thenewcopyofthecorrespondingfilewillbeleftwiththeextension.default.So,forexample,ifconf\httpd.confalreadyexists,itwillberenamedasconf\httpd.conf.default.Aftertheinstallationyoushouldmanuallychecktoseewhatnewsettingsareinthe.defaultfile,andifnecessary,updateyourexistingconfigurationfile.

Also,ifyoualreadyhaveafilecalledhtdocs\index.html,itwillnotbeoverwritten(andnoindex.html.defaultwillbeinstalledeither).ThismeansitshouldbesafetoinstallApacheoveranexistinginstallation,althoughyouwouldhavetostoptheexistingrunningserverbeforedoingtheinstallation,andthenstartthenewoneaftertheinstallationisfinished.

AfterinstallingApache,youmustedittheconfigurationfilesinthe

confsubdirectoryasrequired.ThesefileswillbeconfiguredduringtheinstallationsothatApacheisreadytoberunfromthedirectoryitwasinstalledinto,withthedocumentsserverfromthesubdirectoryhtdocs.TherearelotsofotheroptionswhichyoushouldsetbeforeyoureallystartusingApache.However,togetstartedquickly,thefilesshouldworkasinstalled.

CustomizingApacheforWindows

Apacheisconfiguredbythefilesintheconfsubdirectory.ThesearethesamefilesusedtoconfiguretheUnixversion,butthereareafewdifferentdirectivesforApacheonWindows.Seethedirectiveindexforalltheavailabledirectives.

ThemaindifferencesinApacheforWindowsare:

BecauseApacheforWindowsismultithreaded,itdoesnotuseaseparateprocessforeachrequest,asApachedoesonUnix.InsteadthereareusuallyonlytwoApacheprocessesrunning:aparentprocess,andachildwhichhandlestherequests.Withinthechildprocesseachrequestishandledbyaseparatethread.

Theprocessmanagementdirectivesarealsodifferent:

MaxRequestsPerChild:LiketheUnixdirective,thiscontrolshowmanyrequestsasinglechildprocesswillservebeforeexiting.However,unlikeonUnix,asingleprocessservesalltherequestsatonce,notjustone.Ifthisisset,itisrecommendedthataveryhighnumberisused.Therecommendeddefault,MaxRequestsPerChild0,causesthechildprocesstoneverexit.

Warning:Theserverconfigurationfileisrereadwhenanewchildprocessisstarted.Ifyouhavemodifiedhttpd.conf,thenewchildmaynotstartoryoumayreceiveunexpectedresults.

ThreadsPerChild:Thisdirectiveisnew.Ittellstheserverhowmanythreadsitshoulduse.Thisisthemaximumnumberofconnectionstheservercanhandleatonce,sobesuretosetthisnumberhighenoughforyoursiteifyougetalotof

hits.TherecommendeddefaultisThreadsPerChild50.

ThedirectivesthatacceptfilenamesasargumentsmustuseWindowsfilenamesinsteadofUnixones.However,becauseApacheusesUnix-stylenamesinternally,youmustuseforwardslashes,notbackslashes.Driveletterscanbeused;ifomitted,thedrivewiththeApacheexecutablewillbeassumed.

Whilefilenamesaregenerallycase-insensitiveonWindows,URLsarestilltreatedinternallyascase-sensitivebeforetheyaremappedtothefilesystem.Forexample,the<Location>,Alias,andProxyPassdirectivesallusecase-sensitivearguments.Forthisreason,itisparticularlyimportanttousethe<Directory>directivewhenattemptingtolimitaccesstocontentinthefilesystem,sincethisdirectiveappliestoanycontentinadirectory,regardlessofhowitisaccessed.IfyouwishtoassurethatonlylowercaseisusedinURLs,youcanusesomethinglike:

RewriteEngineOn

RewriteMaplowercaseint:tolower

RewriteCond%{REQUEST_URI}[A-Z]

RewriteRule(.*)${lowercase:$1}[R,L]

ApacheforWindowscontainstheabilitytoloadmodulesatruntime,withoutrecompilingtheserver.IfApacheiscompilednormally,itwillinstallanumberofoptionalmodulesinthe\Apache2\modulesdirectory.Toactivatetheseorothermodules,thenewLoadModuledirectivemustbeused.Forexample,toactivatethestatusmodule,usethefollowing(inadditiontothestatus-activatingdirectivesinaccess.conf):

LoadModulestatus_modulemodules/mod_status.so

Informationoncreatingloadablemodulesisalsoavailable.

ApachecanalsoloadISAPI(InternetServerApplicationProgrammingInterface)extensions(i.e.internetserverapplications),suchasthoseusedbyMicrosoftIISandotherWindowsservers.Moreinformationisavailable.NotethatApachecannotloadISAPIFilters.

WhenrunningCGIscripts,themethodApacheusestofindtheinterpreterforthescriptisconfigurableusingtheScriptInterpreterSourcedirective.

Sinceitisoftendifficulttomanagefileswithnameslike.htaccessinWindows,youmayfinditusefultochangethenameofthisper-directoryconfigurationfileusingtheAccessFilenamedirective.

AnyerrorsduringApachestartupareloggedintotheWindowseventlogwhenrunningonWindowsNT.ThismechanismactsasabackupforthosesituationswhereApachecannotevenaccessthenormallyusederror.logfile.YoucanviewtheWindowseventlogbyusingtheEventViewerapplicationonWindowsNT4.0,andtheEventViewerMMCsnap-inonnewerversionsofWindows.

NotethatthereisnostartuperrorloggingonWindows9xbecausenoWindowseventlogexistsonthoseoperatingsystems.

RunningApacheasaService

ApachecanberunasaserviceonWindowsNT.ThereissomehighlyexperimentalsupportforsimilarbehavioronWindows9x.

YoucaninstallApacheasaserviceautomaticallyduringtheinstallation.Ifyouchosetoinstallforallusers,theinstallationwillcreateanApacheserviceforyou.Ifyouspecifytoinstallforyourselfonly,youcanmanuallyregisterApacheasaserviceaftertheinstallation.YouhavetobeamemberoftheAdministratorsgroupfortheserviceinstallationtosucceed.

ApachecomeswithautilitycalledtheApacheServiceMonitor.WithityoucanseeandmanagethestateofallinstalledApacheservicesonanymachineonyournetwork.TobeabletomanageanApacheservicewiththemonitor,youhavetofirstinstalltheservice(eitherautomaticallyviatheinstallationormanually).

YoucaninstallApacheasaWindowsNTserviceasfollowsfromthecommandpromptattheApachebinsubdirectory:

httpd-kinstall

Ifyouneedtospecifythenameoftheserviceyouwanttoinstall,usethefollowingcommand.YouhavetodothisifyouhaveseveraldifferentserviceinstallationsofApacheonyourcomputer.

httpd-kinstall-n"MyServiceName"

Ifyouneedtohavespecificallynamedconfigurationfilesfordifferentservices,youmustusethis:

httpd-kinstall-n"MyServiceName"-f"c:\files\my.conf"

Ifyouusethefirstcommandwithoutanyspecialparametersexcept-kinstall,theservicewillbecalledApache2andthe

configurationwillbeassumedtobeconf\httpd.conf.

RemovinganApacheserviceiseasy.Justuse:

httpd-kuninstall

ThespecificApacheservicetobeuninstalledcanbespecifiedbyusing:

httpd-kuninstall-n"MyServiceName"

Normalstarting,restartingandshuttingdownofanApacheserviceisusuallydoneviatheApacheServiceMonitor,byusingcommandslikeNETSTARTApache2andNETSTOPApache2orvianormalWindowsservicemanagement.BeforestartingApacheasaservicebyanymeans,youshouldtesttheservice'sconfigurationfilebyusing:

httpd-n"MyServiceName"-t

YoucancontrolanApacheservicebyitscommandlineswitches,too.TostartaninstalledApacheserviceyou'llusethis:

httpd-kstart

TostopanApacheserviceviathecommandlineswitches,usethis:

httpd-kstop

or

httpd-kshutdown

Youcanalsorestartarunningserviceandforceittorereaditsconfigurationfilebyusing:

httpd-krestart

Bydefault,allApacheservicesareregisteredtorunasthesystemuser(theLocalSystemaccount).TheLocalSystemaccounthasnoprivilegestoyournetworkviaanyWindows-securedmechanism,includingthefilesystem,namedpipes,DCOM,orsecureRPC.Ithas,however,wideprivilegeslocally.

NevergrantanynetworkprivilegestotheLocalSystemaccount!IfyouneedApachetobeabletoaccessnetworkresources,createaseparateaccountforApacheasnotedbelow.

YoumaywanttocreateaseparateaccountforrunningApacheservice(s).Especially,ifyouhavetoaccessnetworkresourcesviaApache,thisisstronglyrecommended.

1. Createanormaldomainuseraccount,andbesuretomemorizeitspassword.

2. Grantthenewly-createduseraprivilegeofLogonasaserviceandActaspartoftheoperatingsystem.OnWindowsNT4.0theseprivilegesaregrantedviaUserManagerforDomains,butonWindows2000andXPyouprobablywanttouseGroupPolicyforpropagatingthesesettings.YoucanalsomanuallysettheseviatheLocalSecurityPolicyMMCsnap-in.

3. ConfirmthatthecreatedaccountisamemberoftheUsersgroup.

4. Granttheaccountreadandexecute(RX)rightstoalldocumentandscriptfolders(htdocsandcgi-binfor

example).

5. Granttheaccountchange(RWXD)rightstotheApachelogsdirectory.

6. Granttheaccountreadandexecute(RX)rightstotheApache.exebinaryexecutable.

ItisusuallyagoodpracticetogranttheusertheApacheservicerunsasreadandexecute(RX)accesstothewholeApache2directory,exceptthelogssubdirectory,wheretheuserhastohaveatleastchange(RWXD)rights.

Ifyouallowtheaccounttologinasauserandasaservice,thenyoucanlogonwiththataccountandtestthattheaccounthastheprivilegestoexecutethescripts,readthewebpages,andthatyoucanstartApacheinaconsolewindow.Ifthisworks,andyouhavefollowedthestepsabove,Apacheshouldexecuteasaservicewithnoproblems.

Errorcode2186isagoodindicationthatyouneedtoreviewthe"LogOnAs"configurationfortheservice,sinceApachecannotaccessarequirednetworkresource.Also,paycloseattentiontotheprivilegesoftheuserApacheisconfiguredtorunas.

WhenstartingApacheasaserviceyoumayencounteranerrormessagefromtheWindowsServiceControlManager.Forexample,ifyoutrytostartApachebyusingtheServicesappletintheWindowsControlPanel,youmaygetthefollowingmessage:

CouldnotstarttheApache2serviceon\\COMPUTER

Error1067;Theprocessterminatedunexpectedly.

YouwillgetthisgenericerrorifthereisanyproblemwithstartingtheApacheservice.Inordertoseewhatisreallycausingthe

problemyoushouldfollowtheinstructionsforRunningApacheforWindowsfromtheCommandPrompt.

ThereissomesupportforApacheonWindows9xtobehaveinasimilarmannerasaserviceonWindowsNT.Itishighlyexperimental.Itisnotofproduction-classreliability,anditsfutureisnotguaranteed.Itcanbemostlyregardedasariskythingtoplaywith-proceedwithcaution!

Therearesomedifferencesbetweenthetwokindsofservicesyoushouldbeawareof:

Apachewillattempttostartandifsuccessfulitwillruninthebackground.Ifyourunthecommand

httpd-n"MyServiceName"-kstart

viaashortcutonyourdesktop,forexample,theniftheservicestartssuccessfully,aconsolewindowwillflashupbutitimmediatelydisappears.IfApachedetectsanyerrorsonstartupsuchasincorrectentriesinthehttpd.confconfigurationfile,theconsolewindowwillremainvisible.Thiswilldisplayanerrormessagewhichwillbeusefulintrackingdownthecauseoftheproblem.

Windows9xdoesnotsupportNETSTARTorNETSTOPcommands.YoumustcontroltheApacheserviceonthecommandpromptviathe-kswitches.

ApacheandWindows9xoffernosupportforrunningApacheasaspecificuserwithnetworkprivileges.Infact,Windows9xoffersnosecurityonthelocalmachine,either.ThisisthesimplereasonbecauseofwhichtheApacheSoftwareFoundationneverendorsesuseofaWindows9x-basedsystemasapublicApacheserver.Theprimitivesupportfor

Windows9xexistsonlytoassisttheuserindevelopingwebcontentandlearningtheApacheserver,andperhapsasanintranetserveronasecured,privatenetwork.

OnceyouhaveconfirmedthatApacherunscorrectlyasaconsoleapplicationyoucaninstall,controlanduninstallthepseudo-servicewiththesamecommandsasonWindowsNT.YoucanalsousetheApacheServiceMonitortomanageWindows9xpseudo-services.

RunningApacheasaConsoleApplication

RunningApacheasaserviceisusuallytherecommendedwaytouseit,butitissometimeseasiertoworkfromthecommandline(onWindows9xrunningApachefromthecommandlineistherecommendedwayduetothelackofreliableservicesupport.)

TorunApachefromthecommandlineasaconsoleapplication,usethefollowingcommand:

httpd

Apachewillexecute,andwillremainrunninguntilitisstoppedbypressingControl-C.

YoucanalsorunApacheviatheshortcutStartApacheinConsoleplacedtoStartMenu-->Programs-->ApacheHTTPServer2.0.xx-->ControlApacheServerduringtheinstallation.ThiswillopenaconsolewindowandstartApacheinsideit.Ifyoudon'thaveApacheinstalledasaservice,thewindowwillremainvisibleuntilyoustopApachebypressingControl-CintheconsolewindowwhereApacheisrunningin.Theserverwillexitinafewseconds.However,ifyoudohaveApacheinstalledasaservice,theshortcutstartstheservice.IftheApacheserviceisrunningalready,theshortcutdoesn'tdoanything.

YoucantellarunningApachetostopbyopeninganotherconsolewindowandentering:

httpd-kshutdown

ThisshouldbepreferredoverpressingControl-CbecausethisletsApacheendanycurrentoperationsandcleanupgracefully.

YoucanalsotellApachetorestart.Thisforcesittorereadtheconfigurationfile.Anyoperationsinprogressareallowedto

completewithoutinterruption.TorestartApache,use:

httpd-krestart

NoteforpeoplefamiliarwiththeUnixversionofApache:thesecommandsprovideaWindowsequivalenttokill-TERMpidandkill-USR1pid.Thecommandlineoptionused,-k,waschosenasareminderofthekillcommandusedonUnix.

IftheApacheconsolewindowclosesimmediatelyorunexpectedlyafterstartup,opentheCommandPromptfromtheStartMenu-->Programs.ChangetothefoldertowhichyouinstalledApache,typethecommandapache,andreadtheerrormessage.Thenchangetothelogsfolder,andreviewtheerror.logfileforconfigurationmistakes.IfyouacceptedthedefaultswhenyouinstalledApache,thecommandswouldbe:

c:

cd"\ProgramFiles\ApacheGroup\Apache2\bin"

httpd

ThenwaitforApachetostop,orpressControl-C.Thenenterthefollowing:

cd..\logs

more<error.log

WhenworkingwithApacheitisimportanttoknowhowitwillfindtheconfigurationfile.Youcanspecifyaconfigurationfileonthecommandlineintwoways:

-fspecifiesanabsoluteorrelativepathtoaparticularconfigurationfile:

httpd-f"c:\myserverfiles\anotherconfig.conf"

or

httpd-ffiles\anotherconfig.conf

-nspecifiestheinstalledApacheservicewhoseconfigurationfileistobeused:

httpd-n"MyServiceName"

Inbothofthesecases,theproperServerRootshouldbesetintheconfigurationfile.

Ifyoudon'tspecifyaconfigurationfilewith-for-n,Apachewillusethefilenamecompiledintotheserver,suchasconf\httpd.conf.Thisbuilt-inpathisrelativetotheinstallationdirectory.YoucanverifythecompiledfilenamefromavaluelabelledasSERVER_CONFIG_FILEwheninvokingApachewiththe-Vswitch,likethis:

httpd-V

ApachewillthentrytodetermineitsServerRootbytryingthefollowing,inthisorder:

1. AServerRootdirectiveviathe-Ccommandlineswitch.

2. The-dswitchonthecommandline.

3. Currentworkingdirectory.

4. Aregistryentrywhichwascreatedifyoudidabinaryinstallation.

5. Theserverrootcompiledintotheserver.Thisis/apachebydefault,youcanverifyitbyusingapache-Vandlookingfor

avaluelabelledasHTTPD_ROOT.

Duringtheinstallation,aversion-specificregistrykeyiscreatedintheWindowsregistry.Thelocationofthiskeydependsonthetypeoftheinstallation.IfyouchosetoinstallApacheforallusers,thekeyislocatedundertheHKEY_LOCAL_MACHINEhive,likethis(theversionnumberswillofcoursevarybetweendifferentversionsofApache:

HKEY_LOCAL_MACHINE\SOFTWARE\ApacheGroup\Apache\2.0.43

Correspondingly,ifyouchosetoinstallApacheforthecurrentuseronly,thekeyislocatedundertheHKEY_CURRENT_USERhive,thecontentsofwhicharedependentoftheusercurrentlyloggedon:

HKEY_CURRENT_USER\SOFTWARE\ApacheGroup\Apache\2.0.43

Thiskeyiscompiledintotheserverandcanenableyoutotestnewversionswithoutaffectingthecurrentversion.Ofcourse,youmusttakecarenottoinstallthenewversioninthesamedirectoryasanotherversion.

Ifyoudidnotdoabinaryinstall,Apachewillinsomescenarioscomplainaboutthemissingregistrykey.Thiswarningcanbeignorediftheserverwasotherwiseabletofinditsconfigurationfile.

ThevalueofthiskeyistheServerRootdirectorywhichcontainstheconfsubdirectory.WhenApachestartsitreadsthehttpd.conffilefromthatdirectory.IfthisfilecontainsaServerRootdirectivewhichcontainsadifferentdirectoryfromtheoneobtainedfromtheregistrykeyabove,Apachewillforgettheregistrykeyandusethedirectoryfromtheconfigurationfile.IfyoucopytheApachedirectoryorconfigurationfilestoanew

locationitisvitalthatyouupdatetheServerRootdirectiveinthehttpd.conffiletoreflectthenewlocation.

Copyright2013TheApacheSoftwareFoundation.

TestingtheInstallation

AfterstartingApache(eitherinaconsolewindoworasaservice)itwillbelisteningonport80(unlessyouchangedtheListendirectiveintheconfigurationfilesorinstalledApacheonlyforthecurrentuser).Toconnecttotheserverandaccessthedefaultpage,launchabrowserandenterthisURL:

http://localhost/

ApacheshouldrespondwithawelcomepageandalinktotheApachemanual.Ifnothinghappensoryougetanerror,lookintheerror.logfileinthelogssubdirectory.Ifyourhostisnotconnectedtothenet,orifyouhaveseriousproblemswithyourDNS(DomainNameService)configuration,youmayhavetousethisURL:

http://127.0.0.1/

IfyouhappentoberunningApacheonanalternateport,youneedtoexplicitlyputthatintheURL:

http://127.0.0.1:8080/

Onceyourbasicinstallationisworking,youshouldconfigureitproperlybyeditingthefilesintheconfsubdirectory.Again,ifyouchangetheconfigurationoftheWindowsNTserviceforApache,firstattempttostartitfromthecommandlinetomakesurethattheservicestartswithnoerrors.

BecauseApachecannotsharethesameportwithanotherTCP/IPapplication,youmayneedtostop,uninstallorreconfigurecertainotherservicesbeforerunningApache.TheseconflictingservicesincludeotherWWWserversandsomefirewallimplementations.

LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>PlatformSpecificNotes

CompilingApacheforMicrosoftWindows

TherearemanyimportantpointsbeforeyoubegincompilingApache.SeeUsingApachewithMicrosoftWindowsbeforeyoubegin.

Requirements

CompilingApacherequiresthefollowingenvironmenttobeproperlyinstalled:

DiskSpace

Makesureyouhaveatleast50MBoffreediskspaceavailable.AfterinstallationApacherequiresapproximately10MBofdiskspace,plusspaceforlogandcachefiles,whichcangrowrapidly.Theactualdiskspacerequirementswillvaryconsiderablybasedonyourchosenconfigurationandanythird-partymodulesorlibraries.

MicrosoftVisualC++5.0orhigher.

Apachecanbebuiltusingthecommandlinetools,orfromwithintheVisualStudioIDEWorkbench.ThecommandlinebuildrequirestheenvironmenttoreflectthePATH,INCLUDE,LIBandothervariablesthatcanbeconfiguredwiththevcvars32batchfile:

"c:\ProgramFiles\DevStudio\VC\Bin\vcvars32.bat"

TheWindowsPlatformSDK.

VisualC++5.0buildsrequireanupdatedMicrosoftWindowsPlatformSDKtoenablesomeApachefeatures.Forcommandlinebuilds,thePlatformSDKenvironmentispreparedbythesetenvbatchfile:

"c:\ProgramFiles\PlatformSDK\setenv.bat"

ThePlatformSDKfilesdistributedwithVisualC++6.0andlateraresufficient,sousersoflaterversionmayskipthisrequirement.

NotethattheWindowsPlatformSDKupdateisrequiredtoenableallsupportedmod_isapifeatures.Withoutarecentupdate,ApachewillissuewarningsunderMSVC++5.0thatsomemod_isapifeatureswillbedisabled.Lookfortheupdateathttp://msdn.microsoft.com/downloads/sdks/platform/platform.asp

Theawkutility(awk,gawkorsimilar).

ToinstallApachewithinthebuildsystem,severalfilesaremodifiedusingtheawk.exeutility.awkwaschosensinceitisaverysmalldownload(comparedwithPerlorWSH/VB)andaccomplishesthetaskofgeneratingfiles.BrianKernighan'shttp://cm.bell-labs.com/cm/cs/who/bwk/sitehasacompilednativeWin32binary,http://cm.bell-labs.com/cm/cs/who/bwk/awk95.exewhichyoumustsavewiththenameawk.exeratherthanawk95.exe.

NotethatDeveloperStudioIDEwillonlyfindawk.exefromtheToolsmenuOptions...Directoriestab(theProjects-VC++DirectoriespaneinDeveloperStudio7.0)listingExecutablefilepaths.Addthepathforawk.exetothislist,andyoursystemPATHenvironmentvariable,asneeded.

AlsonotethatifyouareusingCygwin(http://www.cygwin.com/)theawkutilityisnamedgawk.exeandthatthefileawk.exeisreallyasymlinktothegawk.exefile.TheWindowscommandshelldoesnotrecognizesymlinks,andbecauseofthatbuildingInstallBinwillfail.Aworkaroundistodeleteawk.exefromthecygwininstallationandrenamegawk.exetoawk.exe.

[Optional]OpenSSLlibraries(formod_sslandab.exewithsslsupport)

Caution:therearesignificantrestrictionsandprohibitionsontheuseanddistributionofstrongcryptographyandpatentedintellectualpropertythroughouttheworld.OpenSSLincludesstrongcryptographycontrolledbybothexportregulationsanddomesticlaw,aswellasintellectualpropertyprotectedbypatent,intheUnitedStatesandelsewhere.NeithertheApacheSoftwareFoundationnortheOpenSSLprojectcanprovidelegaladviseregardingpossession,use,ordistributionofthecodeprovidedbytheOpenSSLproject.Consultyourownlegalcounsel,youareresponsibleforyourownactions.

OpenSSLmustbeinstalledintoasrclibsubdirectorynamedopenssl,obtainedfromhttp://www.openssl.org/source/,inordertocompilemod_sslortheabsproject(ab.exewithSSLsupport.)ToprepareOpenSSLforbothreleaseanddebugbuildsofApache,anddisablethepatentprotectedfeaturesinOpenSSL,youmightusethefollowingbuildcommands:

perlConfigureVC-WIN32

perlutil\mkfiles.pl>MINFO

perlutil\mk1mf.pldllno-asmno-mdc2no-rc5no-ideaVC-

WIN32>makefile.rel

perlutil\mk1mf.pldlldebugno-asmno-mdc2no-rc5no-idea

VC-WIN32>makefile.dbg

perlutil\mkdef.pl32libeayno-asmno-mdc2no-rc5no-idea

>ms\libeay32.def

perlutil\mkdef.pl32ssleayno-asmno-mdc2no-rc5no-idea

>ms\ssleay32.def

nmake-fmakefile.rel

nmake-fmakefile.dbg

Note;youcanusethescriptsinthems\subdirectory,however,it'srathertrickytoforcems\do_masm.bat,forexample,toperformthepatentencumberancesasmentionedabove.Patchestoaddthe$*argumentlisttotheappropriate.batlinesinthesescriptsaren'tincorporated,thusfar.

[Optional]zlibsources(formod_deflate)

Zlibmustbeinstalledintoasrclibsubdirectorynamedzlib,howeverthosesourcesneednotbecompiled.Thebuildsystemwillcompilethecompressionsourcesdirectlyintothemod_deflatemodule.Zlibcanbeobtainedfromhttp://www.zlib.net/--mod_deflateisconfirmedtobuildcorrectlywithversion1.1.4.Tousealaterversionofzlib,upgradetoApacheHTTPServerrelease2.2orlater.

Command-LineBuild

First,unpacktheApachedistributionintoanappropriatedirectory.Openacommand-linepromptandcdtothatdirectory.

ThemasterApachemakefileinstructionsarecontainedintheMakefile.winfile.TocompileApacheonWindowsNT,simplyuseoneofthefollowingcommandstocompiledthereleaseordebugbuild,respectively:

nmake/fMakefile.win_apacher

nmake/fMakefile.win_apached

EithercommandwillcompileApache.Thelatterwillincludedebugginginformationintheresultingfiles,makingiteasiertofindbugsandtrackdownproblems.

DeveloperStudioWorkspaceIDEBuild

ApachecanalsobecompiledusingVC++'sVisualStudiodevelopmentenvironment.Tosimplifythisprocess,aVisualStudioworkspace,Apache.dsw,isprovided.Thisworkspaceexposestheentirelistofworking.dspprojectsthatarerequiredforthecompleteApachebinaryrelease.Itincludesdependenciesbetweentheprojectstoassurethattheyarebuiltintheappropriateorder.

OpentheApache.dswworkspace,andselectInstallBin(ReleaseorDebugbuild,asdesired)astheActiveProject.InstallBincausesallrelatedprojecttobebuilt,andtheninvokesMakefile.wintomovethecompiledexecutablesanddlls.YoumaypersonalizetheINSTDIR=choicebychangingInstallBin'sSettings,Generaltab,Buildcommandlineentry.INSTDIRdefaultstothe/Apache2directory.Ifyouonlywantatestcompile(withoutinstalling)youmaybuildtheBuildBinprojectinstead.

The.dspprojectfilesaredistributedinVisualC++6.0format.VisualC++5.0(97)willrecognizethem.VisualC++7.0(.net)mustconvertApache.dswplusthe.dspfilesintoanApache.slnplus.msprojfiles,besureyoureconvertthe.msprojfileifanyofthesource.dspfileschange!Thisisreallytrivial,justopenApache.dswintheVC++7.0IDEonceagain.

VisualC++7.0(.net)usersshouldalsousetheBuildmenu,ConfigurationManagerdialogtouncheckboththeDebugandReleaseSolutionmodulesabs,mod_sslandmod_deflate.ThesemodulesarebuiltbyinvokingnmakeortheIDEdirectlywiththeBinBuildtargettobuildthosemodulesexplicitly,onlyifthesrclibdirectoriesopenssland/orzlibexist.

Exported.makfilesposeagreaterhassle,buttheyarerequired

forVisualC++5.0userstobuildmod_ssl,abs(abwithSSLsupport)and/ormod_deflate.VC++7.0(.net)usersalsobenefit,nmakebuildsarefasterthanbinenvbuilds.BuildtheentireprojectfromwithintheVC++5.0or6.0IDE,thenusetheProjectMenuExportforallmakefiles.Youmustbuildtheprojectsfirstinordertocreatealldynamicauto-generatedtargets,sothatdependenciescanbeparsedcorrectly.Runthefollowingcommandtofixthepathssotheywillbuildanywhere:

perlsrclib\apr\build\fixwin32mak.pl

Youmusttypethiscommandfromthetopleveldirectoryofthehttpdsourcetree.Every.makand.depprojectfilewithinthecurrentdirectoryandbelowwillbecorrected,andthetimestampsadjustedtoreflectthe.dsp.

Ifyoucontributebackapatchthatrevisesprojectfiles,wemustcommitprojectfilesinVisualStudio6.0format.Changesshouldbesimple,withminimalcompilationandlinkageflagsthatwillberecognizedbyallVC++5.0through7.0environments.

ProjectComponents

TheApache.dswworkspaceandmakefile.winnmakescriptbothbuildthe.dspprojectsoftheApacheserverinthefollowingsequence:

1. srclib\apr\apr.dsp

2. srclib\apr\libapr.dsp

3. srclib\apr-util\uri\gen_uri_delims.dsp

4. srclib\apr-util\xml\expat\lib\xml.dsp

5. srclib\apr-util\aprutil.dsp

6. srclib\apr-util\libaprutil.dsp

7. srclib\pcre\dftables.dsp

8. srclib\pcre\pcre.dsp

9. srclib\pcre\pcreposix.dsp

10. server\gen_test_char.dsp

11. libhttpd.dsp

12. Apache.dsp

Inaddition,themodules\subdirectorytreecontainsprojectfilesforthemajorityofthemodules.

Thesupport\directorycontainsprojectfilesforadditionalprogramsthatarenotpartoftheApacheruntime,butareusedbytheadministratortotestApacheandmaintainpasswordandlogfiles.Windows-specificsupportprojectsarebrokenoutinthesupport\win32\directory.

1. support\ab.dsp

2. support\htdigest.dsp

3. support\htpasswd.dsp

4. support\logresolve.dsp

5. support\rotatelogs.dsp

6. support\win32\ApacheMonitor.dsp

7. support\win32\wintty.dsp

OnceApachehasbeencompiled,itneedstobeinstalledinitsserverrootdirectory.Thedefaultisthe\Apache2directory,ofthesamedrive.

Tobuildandinstallallthefilesintothedesiredfolderdirautomatically,useoneofthefollowingnmakecommands:

nmake/fMakefile.wininstallrINSTDIR=dir

nmake/fMakefile.wininstalldINSTDIR=dir

ThedirargumenttoINSTDIRgivestheinstallationdirectory;itcanbeomittedifApacheistobeinstalledinto\Apache2.

Thiswillinstallthefollowing:

dir\bin\Apache.exe-Apacheexecutabledir\bin\ApacheMonitor.exe-Servicemonitortaskbariconutilitydir\bin\htdigest.exe-Digestauthpasswordfileutilitydir\bin\htdbm.exe-SDBMauthdatabasepasswordfileutilitydir\bin\htpasswd.exe-Basicauthpasswordfileutilitydir\bin\logresolve.exe-Logfilednsnamelookuputilitydir\bin\rotatelogs.exe-Logfilecyclingutility

dir\bin\wintty.exe-Consolewindowutilitydir\bin\libapr.dll-ApachePortableRuntimesharedlibrarydir\bin\libaprutil.dll-ApacheUtilityRuntimesharedlibrarydir\bin\libhttpd.dll-ApacheCorelibrarydir\modules\mod_*.so-LoadableApachemodulesdir\conf-Configurationdirectorydir\logs-Emptyloggingdirectorydir\include-Clanguageheaderfilesdir\lib-Linklibraryfiles

WarningaboutbuildingApachefromthedevelopmenttree

Noteonlythe.dspfilesaremaintainedbetweenreleasebuilds.The.makfilesareNOTregenerated,duetothetremendouswasteofreviewer'stime.Therefore,youcannotrelyontheNMAKEcommandsabovetobuildrevised.dspprojectfilesunlessyouthenexportall.makfilesyourselffromtheproject.ThisisunnecessaryifyoubuildfromwithintheMicrosoftDeveloperStudioenvironment.

AlsonoteitisveryworthwhiletobuildtheBuildBintargetproject(orthecommandline_apacheror_apachedtarget)priortoexportingthemakefiles.Manyfilesareautogeneratedinthebuildprocess.Onlyafullbuildprovidesallofthedependentfilesrequiredtobuildproperdependencytreesforcorrectbuildbehavior.

Inordertocreatedistribution.makfiles,alwaysreviewthegenerated.mak(or.dep)dependenciesforPlatformSDKorothergarbageincludes.TheDevStudio\SharedIDE\bin\

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

(VC5)orDevStudio\Common\MSDev98\bin\(VC6)directorycontainsthesysincl.datfile,whichmustlistallexceptions.Updatethisfile(includingbothforwardandbackslashedpaths,suchasbothsys/time.handsys\time.h)toincludesuchdependencies.Includinglocal-installpathsinadistributed.makfilewillcausethebuildtofailcompletely.Anddon'tforgettorunsrclib/apr/build/fixwin32mak.plinordertofixabsolutepathswithinthe.makfiles.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>PlatformSpecificNotes

UsingApacheWithNovellNetWare

Thisdocumentexplainshowtoinstall,configureandrunApache2.0underNovellNetWare6.0andabove.Ifyoufindanybugs,orwishtocontributeinotherways,pleaseuseourbugreportingpage.

Thebugreportingpageanddev-httpdmailinglistarenotprovidedtoanswerquestionsaboutconfigurationorrunningApache.Beforeyousubmitabugreportorrequest,firstconsultthisdocument,theFrequentlyAskedQuestionspageandtheotherrelevantdocumentationtopics.Ifyoustillhaveaquestionorproblem,postittothenovell.devsup.webservernewsgroup,wheremanyApacheusersaremorethanwillingtoanswernewandobscurequestionsaboutusingApacheonNetWare.

MostofthisdocumentassumesthatyouareinstallingApachefromabinarydistribution.IfyouwanttocompileApacheyourself(possiblytohelpwithdevelopment,ortotrackdownbugs),seethesectiononCompilingApacheforNetWarebelow.

Requirements

Apache2.0isdesignedtorunonNetWare6.0servicepack3andabove.IfyouarerunningaservicepacklessthanSP3,youmustinstallthelatestNetWareLibrariesforC(LibC).

NetWareservicepacksareavailablehere.

Apache2.0forNetWarecanalsoberuninaNetWare5.1environmentaslongasthelatestservicepackorthelatestversionoftheNetWareLibrariesforC(LibC)hasbeeninstalled.WARNING:Apache2.0forNetWarehasnotbeentargetedforortestedinthisenvironment.

DownloadingApacheforNetWare

InformationonthelatestversionofApachecanbefoundontheApachewebserverathttp://www.apache.org/.Thiswilllistthecurrentrelease,anymorerecentalphaorbeta-testreleases,togetherwithdetailsofmirrorwebandanonymousftpsites.BinarybuildsofthelatestreleasesofApache2.0forNetWarecanbedownloadedfromhere.

InstallingApacheforNetWare

ThereisnoApacheinstallprogramforNetWarecurrently.IfyouarebuildingApache2.0forNetWarefromsource,youwillneedtocopythefilesovertotheservermanually.

FollowthesestepstoinstallApacheonNetWarefromthebinarydownload(assumingyouwillinstalltosys:/apache2):

UnzipthebinarydownloadfiletotherootoftheSYS:volume(maybeinstalledtoanyvolume)Editthehttpd.conffilesettingServerRootandServerNamealongwithanyfilepathvaluestoreflectyourcorrectserversettingsAddSYS:/APACHE2tothesearchpath,forexample:

SEARCHADDSYS:\APACHE2

FollowthesestepstoinstallApacheonNetWaremanuallyfromyourownbuildsource(assumingyouwillinstalltosys:/apache2):

CreateadirectorycalledApache2onaNetWarevolumeCopyAPACHE2.NLM,APRLIB.NLMtoSYS:/APACHE2CreateadirectoryunderSYS:/APACHE2calledBINCopyHTDIGEST.NLM,HTPASSWD.NLM,HTDBM.NLM,LOGRES.NLM,ROTLOGS.NLMtoSYS:/APACHE2/BINCreateadirectoryunderSYS:/APACHE2calledCONFCopytheHTTPD-STD.CONFfiletotheSYS:/APACHE2/CONFdirectoryandrenametoHTTPD.CONFCopytheMIME.TYPES,CHARSET.CONVandMAGICfilestoSYS:/APACHE2/CONFdirectoryCopyallfilesandsubdirectoriesin\HTTPD-2.0\DOCS\ICONStoSYS:/APACHE2/ICONS

Copyallfilesandsubdirectoriesin\HTTPD-2.0\DOCS\MANUALtoSYS:/APACHE2/MANUALCopyallfilesandsubdirectoriesin\HTTPD-2.0\DOCS\ERRORtoSYS:/APACHE2/ERRORCopyallfilesandsubdirectoriesin\HTTPD-2.0\DOCS\DOCROOTtoSYS:/APACHE2/HTDOCSCreatethedirectorySYS:/APACHE2/LOGSontheserverCreatethedirectorySYS:/APACHE2/CGI-BINontheserverCreatethedirectorySYS:/APACHE2/MODULESandcopyallnlmmodulesintothemodulesdirectoryEdittheHTTPD.CONFfilesearchingforall@@Value@@markersandreplacingthemwiththeappropriatesettingAddSYS:/APACHE2tothesearchpath,forexample:

SEARCHADDSYS:\APACHE2

ApachemaybeinstalledtoothervolumesbesidesthedefaultSYSvolume.

Duringthebuildprocess,addingthekeyword"install"tothemakefilecommandlinewillautomaticallyproduceacompletedistributionpackageunderthesubdirectoryDIST.InstallApachebysimplycopyingthedistributionthatwasproducedbythemakfilestotherootofaNetWarevolume(see:CompilingApacheforNetWarebelow).

RunningApacheforNetWare

TostartApachejusttypeapacheattheconsole.ThiswillloadapacheintheOSaddressspace.IfyouprefertoloadApacheinaprotectedaddressspaceyoumayspecifytheaddressspacewiththeloadstatementasfollows:

loadaddressspace=apache2apache2

ThiswillloadApacheintoanaddressspacecalledapache2.RunningmultipleinstancesofApacheconcurrentlyonNetWareispossiblebyloadingeachinstanceintoitsownprotectedaddressspace.

AfterstartingApache,itwillbelisteningtoport80(unlessyouchangedtheListendirectiveintheconfigurationfiles).Toconnecttotheserverandaccessthedefaultpage,launchabrowserandentertheserver'snameoraddress.Thisshouldrespondwithawelcomepage,andalinktotheApachemanual.Ifnothinghappensoryougetanerror,lookintheerror_logfileinthelogsdirectory.

Onceyourbasicinstallationisworking,youshouldconfigureitproperlybyeditingthefilesintheconfdirectory.

TounloadApacherunningintheOSaddressspacejusttypethefollowingattheconsole:

unloadapache2

or

apache2shutdown

Ifapacheisrunninginaprotectedaddressspacespecifytheaddressspaceintheunloadstatement:

unloadaddressspace=apache2apache2

WhenworkingwithApacheitisimportanttoknowhowitwillfindtheconfigurationfiles.Youcanspecifyaconfigurationfileonthecommandlineintwoways:

-fspecifiesapathtoaparticularconfigurationfile

apache2-f"vol:/myserver/conf/my.conf"

apache-ftest/test.conf

Inthesecases,theproperServerRootshouldbesetintheconfigurationfile.

Ifyoudon'tspecifyaconfigurationfilenamewith-f,Apachewillusethefilenamecompiledintotheserver,usuallyconf/httpd.conf.InvokingApachewiththe-VswitchwilldisplaythisvaluelabeledasSERVER_CONFIG_FILE.ApachewillthendetermineitsServerRootbytryingthefollowing,inthisorder:

AServerRootdirectiveviaa-Cswitch.The-dswitchonthecommandline.CurrentworkingdirectoryTheserverrootcompiledintotheserver.

Theserverrootcompiledintotheserverisusuallysys:/apache2.invokingapachewiththe-VswitchwilldisplaythisvaluelabeledasHTTPD_ROOT.

Apache2.0forNetWareincludesasetofcommandlinedirectivesthatcanbeusedtomodifyordisplayinformationabouttherunninginstanceofthewebserver.Thesedirectivesareonly

availablewhileApacheisrunning.EachofthesedirectivesmustbeprecededbythekeywordAPACHE2.

RESTARTInstructsApachetoterminateallrunningworkerthreadsastheybecomeidle,rereadtheconfigurationfileandrestarteachworkerthreadbasedonthenewconfiguration.

VERSIONDisplaysversioninformationaboutthecurrentlyrunninginstanceofApache.

MODULESDisplaysalistofloadedmodulesbothbuilt-inandexternal.

DIRECTIVESDisplaysalistofallavailabledirectives.

SETTINGSEnablesordisablesthethreadstatusdisplayontheconsole.Whenenabled,thestateofeachrunningthreadsisdisplayedontheApacheconsolescreen.

SHUTDOWNTerminatestherunninginstanceoftheApachewebserver.

HELPDescribeseachoftheruntimedirectives.

BydefaultthesedirectivesareissuedagainsttheinstanceofApacherunningintheOSaddressspace.Toissueadirectiveagainstaspecificinstancerunninginaprotectedaddressspace,includethe-pparameteralongwiththenameoftheaddressspace.Formoreinformationtype"apache2Help"onthecommandline.

ConfiguringApacheforNetWare

Apacheisconfiguredbyreadingconfigurationfilesusuallystoredintheconfdirectory.ThesearethesameasfilesusedtoconfiguretheUnixversion,butthereareafewdifferentdirectivesforApacheonNetWare.SeetheApachedocumentationforalltheavailabledirectives.

ThemaindifferencesinApacheforNetWareare:

BecauseApacheforNetWareismultithreaded,itdoesnotuseaseparateprocessforeachrequest,asApachedoesonsomeUniximplementations.Insteadthereareonlythreadsrunning:aparentthread,andmultiplechildorworkerthreadswhichhandletherequests.

Thereforethe"process"-managementdirectivesaredifferent:

MaxRequestsPerChild-LiketheUnixdirective,thiscontrolshowmanyrequestsaworkerthreadwillservebeforeexiting.Therecommendeddefault,MaxRequestsPerChild0,causesthethreadtocontinueservicingrequestindefinitely.ItisrecommendedonNetWare,unlessthereissomespecificreason,thatthisdirectivealwaysremainsetto0.

StartThreads-Thisdirectivetellstheserverhowmanythreadsitshouldstartinitially.TherecommendeddefaultisStartThreads50.

MinSpareThreads-Thisdirectiveinstructstheservertospawnadditionalworkerthreadsifthenumberofidlethreadseverfallsbelowthisvalue.TherecommendeddefaultisMinSpareThreads10.

MaxSpareThreads-Thisdirectiveinstructstheservertobeginterminatingworkerthreadsifthenumberofidlethreads

everexceedsthisvalue.TherecommendeddefaultisMaxSpareThreads100.

MaxThreads-Thisdirectivelimitsthetotalnumberofworkthreadstoamaximumvalue.TherecommendeddefaultisThreadsPerChild250.

ThreadStackSize-Thisdirectivetellstheserverwhatsizeofstacktousefortheindividualworkerthread.TherecommendeddefaultisThreadStackSize65536.

ThedirectivesthatacceptfilenamesasargumentsmustuseNetWarefilenamesinsteadofUnixnames.However,becauseApacheusesUnix-stylenamesinternally,forwardslashesmustbeusedratherthanbackslashes.Itisrecommendedthatallrootedfilepathsbeginwithavolumename.Ifomitted,ApachewillassumetheSYS:volumewhichmaynotbecorrect.

ApacheforNetWarehastheabilitytoloadmodulesatruntime,withoutrecompilingtheserver.IfApacheiscompilednormally,itwillinstallanumberofoptionalmodulesinthe\Apache2\modulesdirectory.Toactivatethese,orothermodules,theLoadModuledirectivemustbeused.Forexample,toactivethestatusmodule,usethefollowing:

LoadModulestatus_modulemodules/status.nlm

Informationoncreatingloadablemodulesisalsoavailable.

AdditionalNetWarespecificdirectives:CGIMapExtension-ThisdirectivemapsaCGIfileextensiontoascriptinterpreter.

SecureListen-EnablesSSLencryptionforaspecifiedport.

NWSSLTrustedCerts-Addstrustedcertificatesthatareusedtocreatesecureconnectionstoproxiedservers.

NWSSLUpgradeable-Allowaconnectioncreatedonthespecifiedaddress/porttobeupgradedtoanSSLconnection.

CompilingApacheforNetWare

CompilingApacherequiresMetroWerksCodeWarrior6.xorhigher.OnceApachehasbeenbuilt,itcanbeinstalledtotherootofanyNetWarevolume.Thedefaultisthesys:/Apache2directory.

Beforerunningtheserveryoumustfillouttheconfdirectory.CopythefileHTTPD-STD.CONFfromthedistributionconfdirectoryandrenameittoHTTPD.CONF.EdittheHTTPD.CONFfilesearchingforall@@Value@@markersandreplacingthemwiththeappropriatesetting.Copyovertheconf/magicandconf/mime.typesfilesaswell.Alternatively,acompletedistributioncanbebuiltbyincludingthekeywordinstallwheninvokingthemakefiles.

Requirements:ThefollowingdevelopmenttoolsarerequiredtobuildApache2.0forNetWare:

MetrowerksCodeWarrior6.0orhigherwiththeNetWarePDK3.0orhigher.NetWareLibrariesforC(LibC)LDAPLibrariesforCZLIBCompressionLibrarysourcecodeAWKutility(awk,gawkorsimilar).AWKcanbedownloadedfromhttp://developer.novell.com/ndk/apache.htm.Theutilitymustbefoundinyourwindowspathandmustbenamedawk.exe.Tobuildusingthemakefiles,youwillneedGNUmakeversion3.78.1(GMake)availableathttp://developer.novell.com/ndk/apache.htm.

BuildingApacheusingtheNetWaremakefiles:

SettheenvironmentvariableNOVELLLIBCtothelocationoftheNetWareLibrariesforCSDK,forexample:

SetNOVELLLIBC=c:\novell\ndk\libc

SettheenvironmentvariableMETROWERKStothelocationwhereyouinstalledtheMetrowerksCodeWarriorcompiler,forexample:

SetMETROWERKS=C:\ProgramFiles\Metrowerks\CodeWarrior

IfyouinstalledtothedefaultlocationC:\ProgramFiles\Metrowerks\CodeWarrior,youdon'tneedtosetthis.SettheenvironmentvariableLDAPSDKtothelocationwhereyouinstalledtheLDAPLibrariesforC,forexample:

SetLDAPSDK=c:\Novell\NDK\cldapsdk\NetWare\libc

SettheenvironmentvariableZLIBSDKtothelocationwhereyouinstalledthesourcecodefortheZLibLibrary,forexample:

SetZLIBSDK=D:\NOVELL\zlib

SettheenvironmentvariableAP_WORKtothefullpathofthe\httpd-2.0directory.SettheenvironmentvariableAPR_WORKtothefullpathofthe\httpd-2.0\srclib\aprdirectory.MakesurethatthepathtotheAWKutilityandtheGNUmakeutility(gmake.exe)havebeenincludedinthesystem'sPATHenvironmentvariable.Downloadthesourcecodeandunziptoanappropriate

directoryonyourworkstation.Changedirectoryto\httpd-2.0\srclib\apr-util\uriandbuildGENURI.nlmbyrunning"gmake-fnwgnumakefile".CopythefileGENURI.nlmtotheSYS:volumeofaNetWareserverandrunusingthefollowingcommand:

SYS:\genuri>sys:\uri_delims.h

Copythefileuri_delims.htothedirectory\httpd-2.0\srclib\apr-util\urionthebuildmachine.Changedirectoryto\httpd-2.0\srclib\aprandbuildAPRbyrunning"gmake-fnwgnumakefile"Changedirectoryto\httpd-2.0\srclib\pcreandbuildDFTABLES.nlmbyrunning"gmake-fnwgnumakefile"Changedirectoryto\httpd-2.0\serverandbuildGENCHARS.nlmbyrunning"gmake-fnwgnumakefile"CopythefilesGENCHARS.nlmandDFTABLES.nlmfromtheirrespectivedirectoriestotheSYS:volumeofaNetWareserverandrunthemusingthefollowingcommands:

SYS:\genchars>sys:\test_char.h

SYS:\dftables>sys:\chartables.c

Copythefilestest_char.handchartables.ctothedirectory\httpd-2.0\os\netwareonthebuildmachine.Changedirectoryto\httpd-2.0andbuildApachebyrunning"gmake-fnwgnumakefile".Youcancreateadistributiondirectorybyaddinganinstallparametertothecommand,forexample:

gmake-fnwgnumakefileinstall

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Additionalmakeoptionsgmake-fnwgnumakefile

Buildsreleaseversionsofallofthebinariesandcopiesthemtoa\releasedestinationdirectory.

gmake-fnwgnumakefileDEBUG=1

Buildsdebugversionsofallofthebinariesandcopiesthemtoa\debugdestinationdirectory.

gmake-fnwgnumakefileinstall

CreatesacompleteApachedistributionwithbinaries,docsandadditionalsupportfilesina\dist\Apache2directory.

gmake-fnwgnumakefileinstalldev

Sameasinstallbutalsocreatesa\liband\includedirectoryinthedestinationdirectoryandcopiesheadersandimportfiles.

gmake-fnwgnumakefileclean

Cleansallobjectfilesandbinariesfromthe\releaseor\debugbuildareasdependingonwhetherDEBUGhasbeendefined.

gmake-fnwgnumakefileclobber_all

Sameascleanandalsodeletesthedistributiondirectoryifitexists.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>PlatformSpecificNotes

RunningaHigh-PerformanceWebServeronHPUX

Date:Wed,05Nov199716:59:34-0800

From:RickJones<raj@cup.hp.com>

Reply-To:raj@cup.hp.com

Organization:NetworkPerformance

Subject:HP-UXtuningtips

HerearesometuningtipsforHP-UXtoaddtothetuningpage.

ForHP-UX9.X:Upgradeto10.20ForHP-UX10.[00|01|10]:Upgradeto10.20

ForHP-UX10.20:

InstallthelatestcumulativeARPATransportPatch.ThiswillallowyoutoconfigurethesizeoftheTCPconnectionlookuphashtable.Thedefaultis256bucketsandmustbesettoapoweroftwo.Thisisaccomplishedwithadbagainstthe*disc*imageofthekernel.Thevariablenameistcp_hash_size.Noticethatit'scriticallyimportantthatyouuse"W"towritea32bitquantity,not"w"towritea16bitvaluewhenpatchingthediscimagebecausethetcp_hash_sizevariableisa32bitquantity.

Howtopickthevalue?Examinetheoutputofftp://ftp.cup.hp.com/dist/networking/tools/connhistandseehowmanytotalTCPconnectionsexistonthesystem.Youprobablywantthatnumberdividedbythehashtablesizetobereasonablysmall,saylessthan10.FolkscanlookatHP'sSPECweb96disclosuresforsomecommonsettings.Thesecanbefoundathttp://www.specbench.org/.IfanHP-UXsystemwasperformingat1000SPECweb96connectionspersecond,theTIME_WAITtimeof60secondswouldmean60,000TCP"connections"beingtracked.

Folkscanchecktheirlistenqueuedepthswithftp://ftp.cup.hp.com/dist/networking/misc/listenq.

IffolksarerunningApacheonaPA-8000basedsystem,theyshouldconsider"chatr'ing"theApacheexecutabletohavealargepagesize.Thiswouldbe"chatr+piL<BINARY>".TheGIDoftherunningexecutablemusthaveMLOCKprivileges.Setprivgrp(1m)shouldbeconsultedforassigningMLOCK.ThechangecanbevalidatedbyrunningGlanceandexaminingthememoryregionsoftheserver(s)tomakesurethattheyshowanon-trivialfractionofthetextsegmentbeinglocked.

IffolksarerunningApacheonMPsystems,theymightconsiderwritingasmallprogramthatusesmpctl()tobindprocessestoprocessors.Asimplepid%numcpualgorithmisprobablysufficient.Thismightevengointothesourcecode.

IffolksareconcernedaboutthenumberofFIN_WAIT_2connections,theycanusenettunetoshrinkthevalueoftcp_keepstart.However,theyshouldbecarefulthere-certainlydonotmakeitlessthanohtwotofourminutes.Iftcp_hash_sizehasbeensetwell,itisprobablyOKtolettheFIN_WAIT_2'stakelongertotimeout(perhapseventhedefaulttwohours)-theywillnotonaveragehaveabigimpactonperformance.

Thereareotherthingsthatcouldgointothecodebase,butthatmightbeleftforanotheremail.Feelfreetodropmeamessageifyouorothersareinterested.

sincerely,

rickjones

http://www.cup.hp.com/netperf/NetperfPage.html

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>PlatformSpecificNotes

TheApacheEBCDICPort

Warning:Thisdocumenthasnotbeenupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

OverviewoftheApacheEBCDICPort

Version1.3oftheApacheHTTPServeristhefirstversionwhichincludesaporttoa(non-ASCII)mainframemachinewhichusestheEBCDICcharactersetasitsnativecodeset.

(ItistheSIEMENSfamilyofmainframesrunningtheBS2000/OSDoperatingsystem.ThismainframeOSnowadaysfeaturesaSVR4-derivedPOSIXsubsystem).

Theportwasstartedinitiallyto

provethefeasibilityofportingtheApacheHTTPservertothisplatformfinda"worthyandcapable"successorforthevenerableCERN-3.0daemon(whichwasportedacoupleofyearsago),andtoprovethatApache'spreforkingprocessmodelcanonthisplatformeasilyoutperformtheaccept-fork-servemodelusedbyCERNbyafactorof5ormore.

Thisdocumentservesasarationaletodescribesomeofthedesigndecisionsoftheporttothismachine.

DesignGoals

OneobjectiveoftheEBCDICportwastomaintainenoughbackwardscompatibilitywiththe(EBCDIC)CERNservertomakethetransitiontothenewserverattractiveandeasy.ThisrequiredtheadditionofaconfigurablemethodtodefinewhetheraHTMLdocumentwasstoredinASCII(theonlyformatacceptedbytheoldserver)orinEBCDIC(thenativedocumentformatinthePOSIXsubsystem,andthereforetheonlyrealisticformatinwhichtheotherPOSIXtoolslikegreporsedcouldoperateonthedocuments).Thecurrentsolutiontothisisa"pseudo-MIME-format"whichisinterceptedandinterpretedbytheApacheserver(seebelow).Futureversionsmightsolvetheproblembydefiningan"ebcdic-handler"foralldocumentswhichmustbeconverted.

TechnicalSolution

SinceallApacheinputandoutputisbasedupontheBUFFdatatypeanditsmethods,theeasiestsolutionwastoaddtheconversiontotheBUFFhandlingroutines.Theconversionmustbesettableatanytime,soaBUFFflagwasaddedwhichdefineswhetheraBUFFobjecthascurrentlyenabledconversionornot.ThisflagismodifiedatseveralpointsintheHTTPprotocol:

setbeforearequestisreceived(becausetherequestandtherequestheaderlinesarealwaysinASCIIformat)set/unsetwhentherequestbodyisreceived-dependingonthecontenttypeoftherequestbody(becausetherequestbodymaycontainASCIItextorabinaryfile)setbeforeareplyheaderissent(becausetheresponseheaderlinesarealwaysinASCIIformat)set/unsetwhentheresponsebodyissent-dependingonthecontenttypeoftheresponsebody(becausetheresponsebodymaycontaintextorabinaryfile)

PortingNotes

1. Therelevantchangesinthesourceare#ifdef'edintotwocategories:

#ifdefCHARSET_EBCDIC

CodewhichisneededforanyEBCDICbasedmachine.Thisincludescharactertranslations,differencesincontiguityofthetwocharactersets,flagswhichindicatewhichpartoftheHTTPprotocolhastobeconvertedandwhichpartdoesn'tetc.

#ifdef_OSD_POSIX

CodewhichisneededfortheSIEMENSBS2000/OSDmainframeplatformonly.ThisdealswithincludefiledifferencesandsocketimplementationtopicswhichareonlyrequiredontheBS2000/OSDplatform.

2. ThepossibilitytotranslatebetweenASCIIandEBCDICatthesocketlevel(onBS2000POSIX,thereisasocketoptionwhichsupportsthis)wasintentionallynotchosen,becausethebytestreamattheHTTPprotocollevelconsistsofamixtureofprotocolrelatedstringsandnon-protocolrelatedrawfiledata.HTTPprotocolstringsarealwaysencodedinASCII(theGETrequest,anyHeader:lines,thechunkinginformationetc.)whereasthefiletransferparts(i.e.,GIFimages,CGIoutputetc.)shouldusuallybejust"passedthrough"bytheserver.Thisseparationbetween"protocolstring"and"rawdata"isreflectedintheservercodebyfunctionslikebgets()orrvputs()forstrings,andfunctionslikebwrite()forbinarydata.Aglobaltranslationofeverythingwouldthereforebeinadequate.

(Inthecaseoftextfilesofcourse,provisionsmustbemadesothatEBCDICdocumentsarealwaysservedinASCII)

3. Thisportthereforefeaturesabuilt-inprotocollevelconversionfortheserver-internalstrings(whichthecompilertranslatedtoEBCDICstrings)andthusforallserver-generateddocuments.ThehardcodedASCIIescapes\012and\015whichareubiquitousintheservercodeareanexception:theyarealreadythebinaryencodingoftheASCII\nand\randmustnotbeconvertedtoASCIIasecondtime.Thisexceptionisonlyrelevantforserver-generatedstrings;andexternalEBCDICdocumentsarenotexpectedtocontainASCIInewlinecharacters.

4. ByexaminingthecallhierarchyfortheBUFFmanagementroutines,Iaddedan"ebcdic/asciiconversionlayer"whichwouldbecrossedoneveryputs/write/get/gets,andaconversionflagwhichallowedenabling/disablingtheconversionson-the-fly.Usually,adocumentcrossesthislayertwicefromitsoriginsource(afileorCGIoutput)toitsdestination(therequestingclient):file->Apache,andApache->client.

TheservercannowreadtheheaderlinesofaCGI-scriptoutputinEBCDICformat,andthenfindoutthattheremainderofthescript'soutputisinASCII(likeinthecaseoftheoutputofaWWWCounterprogram:thedocumentbodycontainsaGIFimage).AllheaderprocessingisdoneinthenativeEBCDICformat;theserverthendetermines,basedonthetypeofdocumentbeingserved,whetherthedocumentbody(exceptforthechunkinginformation,ofcourse)isinASCIIalreadyormustbeconvertedfromEBCDIC.

5. ForTextdocuments(MIMEtypestext/plain,text/htmletc.),animplicittranslationtoASCIIcanbeused,or(iftheusersprefertostoresomedocumentsinrawASCIIformforfasterserving,orbecausethefilesresideonaNFS-mounteddirectorytree)canbeservedwithoutconversion.

Example:

toservefileswiththesuffix.ahtmlasarawASCIItext/htmldocumentwithoutimplicitconversion(andsuffix.asciiasASCIItext/plain),usethedirectives:

AddTypetext/x-ascii-html.ahtml

AddTypetext/x-ascii-plain.ascii

Similarly,anytext/fooMIMEtypecanbeservedas"rawASCII"byconfiguringaMIMEtype"text/x-ascii-foo"foritusingAddType.

6. Non-textdocumentsarealwaysserved"binary"withoutconversion.Thisseemstobethemostsensiblechoicefor,.e.g.,GIF/ZIP/AUfiletypes.Thisofcourserequirestheusertocopythemtothemainframehostusingthe"rcp-b"binaryswitch.

7. Serverparsedfilesarealwaysassumedtobeinnative(i.e.,EBCDIC)formatasusedonthemachine,andareconvertedafterprocessing.

8. ForCGIoutput,theCGIscriptdetermineswhetheraconversionisneededornot:bysettingtheappropriateContent-Type,textfilescanbeconverted,orGIFoutputcanbepassedthroughunmodified.Anexampleforthelattercaseisthewwwcountprogramwhichweportedaswell.

DocumentStorageNotes

BinaryFilesAllfileswithaContent-Type:whichdoesnotstartwithtext/areregardedasbinaryfilesbytheserverandarenotsubjecttoanyconversion.ExamplesforbinaryfilesareGIFimages,gzip-compressedfilesandthelike.

WhenexchangingbinaryfilesbetweenthemainframehostandaUnixmachineorWindowsPC,besuretousetheftp"binary"(TYPEI)command,orusethercp-bcommandfromthemainframehost(the-bswitchisnotsupportedinunixrcp's).

TextDocumentsThedefaultassumptionoftheserveristhatTextFiles(i.e.,allfileswhoseContent-Type:startswithtext/)arestoredinthenativecharactersetofthehost,EBCDIC.

ServerSideIncludedDocumentsSSIdocumentsmustcurrentlybestoredinEBCDIConly.NoprovisionismadetoconvertitfromASCIIbeforeprocessing.

ApacheModules'Status

Module Status Notescore +mod_access +mod_actions +mod_alias +mod_asis +mod_auth +mod_auth_anon +mod_auth_dbm ? withownlibdb.amod_autoindex +mod_cern_meta ?mod_cgi +mod_digest +mod_dir +mod_so - nosharedlibsmod_env +mod_example - (testbedonly)mod_expires +mod_headers +mod_imap +mod_include +mod_info +mod_log_agent +mod_log_config +mod_log_referer +mod_mime +mod_mime_magic ? notportedyetmod_negotiation +

mod_proxy +mod_rewrite + untestedmod_setenvif +mod_speling +mod_status +mod_unique_id +mod_userdir +mod_usertrack ? untested

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ThirdPartyModules'Status

Module Status Notesmod_jserv - JAVAstillbeingported.mod_php3 + mod_php3runsfine,withLDAPandGD

andFreeTypelibraries.mod_put ? untestedmod_session - untested

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

httpd-ApacheHypertextTransferProtocolServer

httpdistheApacheHyperTextTransferProtocol(HTTP)serverprogram.Itisdesignedtoberunasastandalonedaemonprocess.Whenusedlikethisitwillcreateapoolofchildprocessesorthreadstohandlerequests.

Ingeneral,httpdshouldnotbeinvokeddirectly,butrathershouldbeinvokedviaapachectlonUnix-basedsystemsorasaserviceonWindowsNT,2000andXPandasaconsoleapplicationonWindows9xandME.

SeealsoStartingApacheStoppingApacheConfigurationFilesPlatform-specificDocumentationapachectl

Synopsishttpd[-dserverroot][-fconfig][-C

directive][-cdirective][-Dparameter][-

elevel][-Efile][-k

start|restart|graceful|stop][-Rdirectory][

-h][-l][-L][-S][-t][-v][-V][

-X]

OnWindowssystems,thefollowingadditionalargumentsareavailable:

httpd[-kinstall|config|uninstall][-nname]

[-w]

Options

-dserverroot

SettheinitialvaluefortheServerRootdirectivetoserverroot.ThiscanbeoverriddenbytheServerRootdirectiveintheconfigurationfile.Thedefaultis/usr/local/apache2.

-fconfig

Usesthedirectivesinthefileconfigonstartup.Ifconfigdoesnotbeginwitha/,thenitistakentobeapathrelativetotheServerRoot.Thedefaultisconf/httpd.conf.

-kstart|restart|graceful|stop

Signalshttpdtostart,restart,orstop.SeeStoppingApacheformoreinformation.

-Cdirective

Processtheconfigurationdirectivebeforereadingconfigfiles.

-cdirective

Processtheconfigurationdirectiveafterreadingconfigfiles.

-Dparameter

Setsaconfigurationparameterwhichcanbeusedwith<IfDefine>sectionsintheconfigurationfilestoconditionallyskiporprocesscommandsatserverstartupandrestart.

-elevel

SetstheLogLeveltolevelduringserverstartup.Thisisusefulfortemporarilyincreasingtheverbosityoftheerrormessagestofindproblemsduringstartup.

-Efile

Senderrormessagesduringserverstartuptofile.

-Rdirectory

WhentheserveriscompiledusingtheSHARED_CORErule,

thisspecifiesthedirectoryforthesharedobjectfiles.

-h

Outputashortsummaryofavailablecommandlineoptions.

-l

Outputalistofmodulescompiledintotheserver.ThiswillnotlistdynamicallyloadedmodulesincludedusingtheLoadModuledirective.

-L

Outputalistofdirectivestogetherwithexpectedargumentsandplaceswherethedirectiveisvalid.

-S

Showthesettingsasparsedfromtheconfigfile(currentlyonlyshowsthevirtualhostsettings).

-t

Runsyntaxtestsforconfigurationfilesonly.Theprogramimmediatelyexitsafterthesesyntaxparsingtestswitheitherareturncodeof0(SyntaxOK)orreturncodenotequalto0(SyntaxError).If-DDUMP_VHOSTSisalsoset,detailsofthevirtualhostconfigurationwillbeprinted.

-v

Printtheversionofhttpd,andthenexit.

-V

Printtheversionandbuildparametersofhttpd,andthenexit.

-X

Runhttpdindebugmode.Onlyoneworkerwillbestartedandtheserverwillnotdetachfromtheconsole.

ThefollowingargumentsareavailableonlyontheWindowsplatform:

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

-kinstall|config|uninstall

InstallApacheasaWindowsNTservice;changestartupoptionsfortheApacheservice;anduninstalltheApacheservice.

-nname

ThenameoftheApacheservicetosignal.

-w

Keeptheconsolewindowopenonerrorsothattheerrormessagecanberead.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

ab-ApacheHTTPserverbenchmarkingtool

abisatoolforbenchmarkingyourApacheHypertextTransferProtocol(HTTP)server.ItisdesignedtogiveyouanimpressionofhowyourcurrentApacheinstallationperforms.ThisespeciallyshowsyouhowmanyrequestspersecondyourApacheinstallationiscapableofserving.

Seealsohttpd

Synopsisab[-Aauth-username:password][-cconcurrency

][-Ccookie-name=value][-d][-ecsv-file]

[-ggnuplot-file][-h][-Hcustom-header][

-i][-k][-nrequests][-pPOST-file][-P

proxy-auth-username:password][-q][-s][-S

][-ttimelimit][-Tcontent-type][-v

verbosity][-V][-w][-x<table>-attributes

][-Xproxy[:port]][-y<tr>-attributes][-z

<td>-attributes][http://]hostname[:port]/path

Options

-Aauth-username:password

SupplyBASICAuthenticationcredentialstotheserver.Theusernameandpasswordareseparatedbyasingle:andsentonthewirebase64encoded.Thestringissentregardlessofwhethertheserverneedsit(i.e.,hassentan401authenticationneeded).

-cconcurrency

Numberofmultiplerequeststoperformatatime.Defaultisonerequestatatime.

-Ccookie-name=value

AddaCookie:linetotherequest.Theargumentistypicallyintheformofaname=valuepair.Thisfieldisrepeatable.

-d

Donotdisplaythe"percentageservedwithinXX[ms]table".(legacysupport).

-ecsv-file

WriteaCommaseparatedvalue(CSV)filewhichcontainsforeachpercentage(from1%to100%)thetime(inmilliseconds)ittooktoservethatpercentageoftherequests.Thisisusuallymoreusefulthanthe'gnuplot'file;astheresultsarealready'binned'.

-ggnuplot-file

Writeallmeasuredvaluesoutasa'gnuplot'orTSV(Tabseparatevalues)file.ThisfilecaneasilybeimportedintopackageslikeGnuplot,IDL,Mathematica,IgororevenExcel.Thelabelsareonthefirstlineofthefile.

-h

Displayusageinformation.

-Hcustom-header

Appendextraheaderstotherequest.Theargumentis

typicallyintheformofavalidheaderline,containingacolon-separatedfield-valuepair(i.e.,"Accept-Encoding:zip/zop;8bit").

-i

DoHEADrequestsinsteadofGET.

-k

EnabletheHTTPKeepAlivefeature,i.e.,performmultiplerequestswithinoneHTTPsession.DefaultisnoKeepAlive.

-nrequests

Numberofrequeststoperformforthebenchmarkingsession.Thedefaultistojustperformasinglerequestwhichusuallyleadstonon-representativebenchmarkingresults.

-pPOST-file

FilecontainingdatatoPOST.

-Pproxy-auth-username:password

SupplyBASICAuthenticationcredentialstoaproxyen-route.Theusernameandpasswordareseparatedbyasingle:andsentonthewirebase64encoded.Thestringissentregardlessofwhethertheproxyneedsit(i.e.,hassentan407proxyauthenticationneeded).

-q

Whenprocessingmorethan150requests,aboutputsaprogresscountonstderrevery10%or100requestsorso.The-qflagwillsuppressthesemessages.

-s

Whencompiledin(ab-hwillshowyou)usetheSSLprotectedhttpsratherthanthehttpprotocol.Thisfeatureisexperimentalandveryrudimentary.Youprobablydonotwanttouseit.

-S

Donotdisplaythemedianandstandarddeviationvalues,nordisplaythewarning/errormessageswhentheaverageandmedianaremorethanoneortwotimesthestandarddeviationapart.Anddefaulttothemin/avg/maxvalues.(legacysupport).

-ttimelimit

Maximumnumberofsecondstospendforbenchmarking.Thisimpliesa-n50000internally.Usethistobenchmarktheserverwithinafixedtotalamountoftime.Perdefaultthereisnotimelimit.

-Tcontent-type

Content-typeheadertouseforPOSTdata.

-vverbosity

Setverbositylevel-4andaboveprintsinformationonheaders,3andaboveprintsresponsecodes(404,200,etc.),2andaboveprintswarningsandinfo.

-V

Displayversionnumberandexit.

-w

PrintoutresultsinHTMLtables.Defaulttableistwocolumnswide,withawhitebackground.

-x<table>-attributes

Stringtouseasattributesfor<table>.Attributesareinserted<tablehere>.

-Xproxy[:port]

Useaproxyserverfortherequests.

-y<tr>-attributes

Stringtouseasattributesfor<tr>.

-z<td>-attributes

Stringtouseasattributesfor<td>.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Bugs

Therearevariousstaticallydeclaredbuffersoffixedlength.Combinedwiththelazyparsingofthecommandlinearguments,theresponseheadersfromtheserverandotherexternalinputs,thismightbiteyou.

ItdoesnotimplementHTTP/1.xfully;onlyacceptssome'expected'formsofresponses.Theratherheavyuseofstrstr(3)showsuptopinprofile,whichmightindicateaperformanceproblem;i.e.,youwouldmeasuretheabperformanceratherthantheserver's.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

apachectl-ApacheHTTPServerControlInterface

apachectlisafrontendtotheApacheHyperTextTransferProtocol(HTTP)server.ItisdesignedtohelptheadministratorcontrolthefunctioningoftheApachehttpddaemon.

Theapachectlscriptcanoperateintwomodes.First,itcanactasasimplefront-endtothehttpdcommandthatsimplysetsanynecessaryenvironmentvariablesandtheninvokeshttpd,passingthroughanycommandlinearguments.Second,apachectlcanactasaSysVinitscript,takingsimpleone-wordargumentslikestart,restart,andstop,andtranslatingthemintoappropriatesignalstohttpd.

IfyourApacheinstallationusesnon-standardpaths,youwillneedtoedittheapachectlscripttosettheappropriatepathstothehttpdbinary.Youcanalsospecifyanynecessaryhttpdcommandlinearguments.Seethecommentsinthescriptfordetails.

Theapachectlscriptreturnsa0exitvalueonsuccess,and>0ifanerroroccurs.Formoredetails,viewthecommentsinthescript.

SeealsoStartingApacheStoppingApacheConfigurationFilesPlatformDocshttpd

Synopsis

Whenactinginpass-throughmode,apachectlcantakealltheargumentsavailableforthehttpdbinary.

apachectl[httpd-argument]

WhenactinginSysVinitmode,apachectltakessimple,one-wordcommands,definedbelow.

apachectlcommand

Options

OnlytheSysVinit-styleoptionsaredefinedhere.Otherargumentsaredefinedonthehttpdmanualpage.

start

StarttheApachehttpddaemon.Givesanerrorifitisalreadyrunning.Thisisequivalenttoapachectl-kstart.

stop

StopstheApachehttpddaemon.Thisisequivalenttoapachectl-kstop.

restart

RestartstheApachehttpddaemon.Ifthedaemonisnotrunning,itisstarted.Thiscommandautomaticallycheckstheconfigurationfilesasinconfigtestbeforeinitiatingtherestarttomakesurethedaemondoesn'tdie.Thisisequivalenttoapachectl-krestart.

fullstatus

Displaysafullstatusreportfrommod_status.Forthistowork,youneedtohavemod_statusenabledonyourserverandatext-basedbrowsersuchaslynxavailableonyoursystem.TheURLusedtoaccessthestatusreportcanbesetbyeditingtheSTATUSURLvariableinthescript.

status

Displaysabriefstatusreport.Similartothefullstatusoption,exceptthatthelistofrequestscurrentlybeingservedisomitted.

graceful

GracefullyrestartstheApachehttpddaemon.Ifthedaemonisnotrunning,itisstarted.Thisdiffersfromanormalrestartinthatcurrentlyopenconnectionsarenotaborted.Asideeffect

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

isthatoldlogfileswillnotbeclosedimmediately.Thismeansthatifusedinalogrotationscript,asubstantialdelaymaybenecessarytoensurethattheoldlogfilesareclosedbeforeprocessingthem.ThiscommandautomaticallycheckstheconfigurationfilesasinconfigtestbeforeinitiatingtherestarttomakesureApachedoesn'tdie.Thisisequivalenttoapachectl-kgraceful.

configtest

Runaconfigurationfilesyntaxtest.ItparsestheconfigurationfilesandeitherreportsSyntaxOkordetailedinformationabouttheparticularsyntaxerror.Thisisequivalenttoapachectl-t.

Thefollowingadditionaloptionisavailable,butdeprecated.

startssl

Thisisequivalenttoapachectl-kstart-DSSL.Werecommendthatyouusethatcommandexplicitly,oryouadjustyourhttpd.conftoremovethe<IfDefine>sectionsothatSSLwillalwaysbeavailable.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

apxs-APacheeXtenSiontool

apxsisatoolforbuildingandinstallingextensionmodulesfortheApacheHyperTextTransferProtocol(HTTP)server.Thisisachievedbybuildingadynamicsharedobject(DSO)fromoneormoresourceorobjectfileswhichthencanbeloadedintotheApacheserverunderruntimeviatheLoadModuledirectivefrommod_so.

SotousethisextensionmechanismyourplatformhastosupporttheDSOfeatureandyourApachehttpdbinaryhastobebuiltwiththemod_somodule.Theapxstoolautomaticallycomplainsifthisisnotthecase.Youcancheckthisyourselfbymanuallyrunningthecommand

$httpd-l

Themodulemod_soshouldbepartofthedisplayedlist.IftheserequirementsarefulfilledyoucaneasilyextendyourApacheserver'sfunctionalitybyinstallingyourownmoduleswiththeDSOmechanismbythehelpofthisapxstool:

$apxs-i-a-cmod_foo.c

gcc-fpic-DSHARED_MODULE-I/path/to/apache/include-cmod_foo.c

ld-Bshareable-omod_foo.somod_foo.o

cpmod_foo.so/path/to/apache/modules/mod_foo.so

chmod755/path/to/apache/modules/mod_foo.so

[activatingmodule`foo'in/path/to/apache/etc/httpd.conf]

$apachectlrestart

/path/to/apache/sbin/apachectlrestart:httpdnotrunning,trying

tostart

[TueMar3111:27:551998][debug]mod_so.c(303):loadedmodule

foo_module

/path/to/apache/sbin/apachectlrestart:httpdstarted

$_

TheargumentsfilescanbeanyCsourcefile(.c),aobjectfile(.o)orevenalibraryarchive(.a).Theapxstoolautomaticallyrecognizes

theseextensionsandautomaticallyusedtheCsourcefilesforcompilationwhilejustusingtheobjectandarchivefilesforthelinkingphase.Butwhenusingsuchpre-compiledobjectsmakesuretheyarecompiledforpositionindependentcode(PIC)tobeabletousethemforadynamicallyloadedsharedobject.ForinstancewithGCCyoualwaysjusthavetouse-fpic.ForotherCcompilersconsultitsmanualpageoratwatchfortheflagsapxsusestocompiletheobjectfiles.

FormoredetailsaboutDSOsupportinApachereadthedocumentationofmod_soorperhapsevenreadthesrc/modules/standard/mod_so.csourcefile.

Seealsoapachectl

httpd

Synopsisapxs-g[-Sname=value]-nmodname

apxs-q[-Sname=value]query...

apxs-c[-Sname=value][-odsofile][-I

incdir][-Dname=value][-Llibdir][-l

libname][-Wc,compiler-flags][-Wl,linker-

flags]files...

apxs-i[-Sname=value][-nmodname][-a][

-A]dso-file...

apxs-e[-Sname=value][-nmodname][-a][

-A]dso-file...

Options

CommonOptions-nmodname

Thisexplicitlysetsthemodulenameforthe-i(install)and-g(templategeneration)option.Usethistoexplicitlyspecifythemodulename.Foroption-gthisisrequired,foroption-itheapxstooltriestodeterminethenamefromthesourceor(asafallback)atleastbyguessingitfromthefilename.

QueryOptions-q

Performsaqueryforapxs'sknowledgeaboutcertainsettings.Thequeryparameterscanbeoneormoreofthefollowingstrings:CC,CFLAGS,CFLAGS_SHLIB,INCLUDEDIR,LD_SHLIB,LDFLAGS_SHLIB,LIBEXECDIR,LIBS_SHLIB,SBINDIR,SYSCONFDIR,TARGET.Usethisformanuallydeterminingsettings.Forinstanceuse

INC=-I`apxs-qINCLUDEDIR`

insideyourownMakefilesifyouneedmanualaccesstoApache'sCheaderfiles.

ConfigurationOptions-Sname=value

Thisoptionchangestheapxssettingsdescribedabove.

TemplateGenerationOptions-g

Thisgeneratesasubdirectoryname(seeoption-n)andtheretwofiles:Asamplemodulesourcefilenamedmod_name.c

whichcanbeusedasatemplateforcreatingyourownmodulesorasaquickstartforplayingwiththeapxsmechanism.AndacorrespondingMakefileforeveneasierbuildandinstallingofthismodule.

DSOCompilationOptions-c

Thisindicatesthecompilationoperation.ItfirstcompilestheCsourcefiles(.c)offilesintocorrespondingobjectfiles(.o)andthenbuildsadynamicallysharedobjectindsofilebylinkingtheseobjectfilesplustheremainingobjectfiles(.oand.a)offiles.Ifno-ooptionisspecifiedtheoutputfileisguessedfromthefirstfilenameinfilesandthususuallydefaultstomod_name.so.

-odsofile

Explicitlyspecifiesthefilenameofthecreateddynamicallysharedobject.Ifnotspecifiedandthenamecannotbeguessedfromthefileslist,thefallbacknamemod_unknown.soisused.

-Dname=value

Thisoptionisdirectlypassedthroughtothecompilationcommand(s).Usethistoaddyourowndefinestothebuildprocess.

-Iincdir

Thisoptionisdirectlypassedthroughtothecompilationcommand(s).Usethistoaddyourownincludedirectoriestosearchtothebuildprocess.

-Llibdir

Thisoptionisdirectlypassedthroughtothelinkercommand.Usethistoaddyourownlibrarydirectoriestosearchtothebuildprocess.

-llibname

Thisoptionisdirectlypassedthroughtothelinkercommand.Usethistoaddyourownlibrariestosearchtothebuildprocess.

-Wc,compiler-flags

Thisoptionpassescompiler-flagsasadditionalflagstothecompilercommand.Usethistoaddlocalcompiler-specificoptions.

-Wl,linker-flags

Thisoptionpasseslinker-flagsasadditionalflagstothelinkercommand.Usethistoaddlocallinker-specificoptions.

DSOInstallationandConfigurationOptions-i

Thisindicatestheinstallationoperationandinstallsoneormoredynamicallysharedobjectsintotheserver'smodulesdirectory.

-a

ThisactivatesthemodulebyautomaticallyaddingacorrespondingLoadModulelinetoApache'shttpd.confconfigurationfile,orbyenablingitifitalreadyexists.

-A

Sameasoption-abutthecreatedLoadModuledirectiveisprefixedwithahashsign(#),i.e.,themoduleisjustpreparedforlateractivationbutinitiallydisabled.

-e

Thisindicatestheeditingoperation,whichcanbeusedwiththe-aand-Aoptionssimilarlytothe-ioperationtoeditApache'shttpd.confconfigurationfilewithoutattemptingtoinstallthemodule.

Examples

AssumeyouhaveanApachemodulenamedmod_foo.cavailablewhichshouldextendApache'sserverfunctionality.ToaccomplishthisyoufirsthavetocompiletheCsourceintoasharedobjectsuitableforloadingintotheApacheserverunderruntimeviathefollowingcommand:

$apxs-cmod_foo.c

gcc-fpic-DSHARED_MODULE-I/path/to/apache/include-c

mod_foo.c

ld-Bshareable-omod_foo.somod_foo.o

$_

ThenyouhavetoupdatetheApacheconfigurationbymakingsureaLoadModuledirectiveispresenttoloadthissharedobject.Tosimplifythisstepapxsprovidesanautomaticwaytoinstallthesharedobjectinits"modules"directoryandupdatingthehttpd.conffileaccordingly.Thiscanbeachievedbyrunning:

$apxs-i-amod_foo.c

cpmod_foo.so/path/to/apache/modules/mod_foo.so

chmod755/path/to/apache/modules/mod_foo.so

[activatingmodule`foo'in/path/to/apache/etc/httpd.conf]

$_

Thiswayalinenamed

LoadModulefoo_modulemodules/mod_foo.so

isaddedtotheconfigurationfileifstillnotpresent.Ifyouwanttohavethisdisabledperdefaultusethe-Aoption,i.e.

$apxs-i-Amod_foo.c

ForaquicktestoftheapxsmechanismyoucancreateasampleApachemoduletemplateplusacorrespondingMakefilevia:

Copyright2013TheApacheSoftwareFoundation.

$apxs-g-nfoo

Creating[DIR]foo

Creating[FILE]foo/Makefile

Creating[FILE]foo/mod_foo.c

$_

ThenyoucanimmediatelycompilethissamplemoduleintoasharedobjectandloaditintotheApacheserver:

$cdfoo

$makeallreload

apxs-cmod_foo.c

gcc-fpic-DSHARED_MODULE-I/path/to/apache/include-c

mod_foo.c

ld-Bshareable-omod_foo.somod_foo.o

apxs-i-a-n"foo"mod_foo.so

cpmod_foo.so/path/to/apache/modules/mod_foo.so

chmod755/path/to/apache/modules/mod_foo.so

[activatingmodule`foo'in/path/to/apache/etc/httpd.conf]

apachectlrestart

/path/to/apache/sbin/apachectlrestart:httpdnotrunning,

tryingtostart

[TueMar3111:27:551998][debug]mod_so.c(303):loadedmodule

foo_module

/path/to/apache/sbin/apachectlrestart:httpdstarted

$_

YoucanevenuseapxstocompilecomplexmodulesoutsidetheApachesourcetree,likePHP3:

$cdphp3

$./configure--with-shared-apache=../apache-1.3

$apxs-c-olibphp3.somod_php3.clibmodphp3-so.a

gcc-fpic-DSHARED_MODULE-I/tmp/apache/include-cmod_php3.c

ld-Bshareable-olibphp3.somod_php3.olibmodphp3-so.a

$_

becauseapxsautomaticallyrecognizedCsourcefilesandobjectfiles.OnlyCsourcefilesarecompiledwhileremainingobjectfilesareusedforthelinkingphase.

LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

configure-Configurethesourcetree

TheconfigurescriptconfiguresthesourcetreeforcompilingandinstallingtheApacheHTTPServeronyourparticularplatform.Variousoptionsallowthecompilationofaservercorrespondingtoyourpersonalrequirements.

Thisscript,includedintherootdirectoryofthesourcedistribution,isforcompilationonUnixandUnix-likesystemsonly.Forotherplatforms,seetheplatformdocumentation.

SeealsoCompilingandInstalling

Synopsis

Youshouldcalltheconfigurescriptfromwithintherootdirectoryofthedistribution.

./configure[OPTION]...[VAR=VALUE]...

Toassignenvironmentvariables(e.g.CC,CFLAGS...),specifythemasVAR=VALUE.Seebelowfordescriptionsofsomeoftheusefulvariables.

Options

ConfigurationoptionsInstallationdirectoriesSystemtypesOptionalfeaturesOptionsforsupportprograms

ConfigurationoptionsThefollowingoptionsinfluencethebehaviorofconfigureitself.

-C

--config-cache

Thisisanaliasfor--cache-file=config.cache

--cache-file=FILE

ThetestresultswillbecachedinfileFILE.Thisoptionisdisabledbydefault.

-h

--help[short|recursive]

Outputthehelpandexit.Withtheargumentshortonlyoptionsspecifictothispackagewilldisplayed.Theargumentrecursivedisplaystheshorthelpofalltheincludedpackages.

-n

--no-create

Theconfigurescriptisrunnormallybutdoesnotcreateoutputfiles.Thisisusefultocheckthetestresultsbeforegeneratingmakefilesforcompilation.

-q

--quiet

Donotprintchecking...messagesduringtheconfigure

process.

--srcdir=DIR

DefinesdirectoryDIRtobethesourcefiledirectory.Defaultisthedirectory,whereconfigureislocated,ortheparentdirectory...

--silent

Sameas--quiet

-V

--versionDisplaycopyrightinformationandexit.

InstallationdirectoriesTheseoptionsdefinetheinstallationdirectory.Theinstallationtreedependsontheselectedlayout.

--prefix=PREFIX

Installarchitecture-independentfilesinPREFIX.Bydefaulttheinstallationdirectoryissetto/usr/local/apache2.

--exec-prefix=EPREFIX

Installarchitecture-dependentfilesinEPREFIX.BydefaulttheinstallationdirectoryissettothePREFIXdirectory.

Bydefault,makeinstallwillinstallallthefilesin/usr/local/apache2/bin,/usr/local/apache2/libetc.Youcanspecifyaninstallationprefixotherthan/usr/local/apache2using--prefix,forinstance--prefix=$HOME.

Defineadirectorylayout--enable-layout=LAYOUT

Configurethesourcecodeandbuildscriptstoassumean

installationtreebasedonthelayoutLAYOUT.ThisallowsyoutoseparatelyspecifythelocationsforeachtypeoffilewithintheApacheHTTPServerinstallation.Theconfig.layoutfilecontainsseveralexampleconfigurations,andyoucanalsocreateyourowncustomconfigurationfollowingtheexamples.Thedifferentlayoutsinthisfilearegroupedinto<LayoutFOO>...</Layout>sectionsandreferredtobynameasinFOO.ThedefaultlayoutisApache.

FinetuningoftheinstallationdirectoriesForbettercontroloftheinstallationdirectories,usetheoptionsbelow.Pleasenotethatthedirectorydefaultsaresetbyautoconfandbeoverwrittenbythecorrespondinglayoutsetting.

--bindir=DIR

InstalluserexecutablesinDIR.Theuserexecutablesaresupportingprogramslikehtpasswd,dbmmanage,etc.whichareusefulforsiteadministrators.BydefaultDIRissettoEPREFIX/bin.

--datadir=DIR

Installread-onlyarchitecture-independentdatainDIR.BydefaultdatadirissettoPREFIX/share.Thisoptionisofferedbyautoconfandcurrentlyunused.

--includedir=DIR

InstallCheaderfilesinDIR.BydefaultincludedirissettoEPREFIX/include.

--infodir=DIR

InstallinfodocumentationinDIR.BydefaultinfodirissettoPREFIX/info.Thisoptioniscurrentlyunused.

--libdir=DIR

InstallobjectcodelibrariesinDIR.BydefaultlibdirissettoEPREFIX/lib.

--libexecdir=DIR

Installtheprogramexecutables(i.e.,sharedmodules)inDIR.BydefaultlibexecdirissettoEPREFIX/libexec.

--localstatedir=DIR

Installmodifiablesingle-machinedatainDIR.BydefaultlocalstatedirissettoPREFIX/var.Thisoptionisofferedbyautoconfandcurrentlyunused.

--mandir=DIR

InstallthemandocumentationinDIR.BydefaultmandirissettoEPREFIX/man.

--oldincludedir=DIR

InstallCheaderfilesfornon-gccinDIR.Bydefaultoldincludedirissetto/usr/include.Thisoptionisofferedbyautoconfandcurrentlyunused.

--sbindir=DIR

InstallthesystemadministratorexecutablesinDIR.Thoseareserverprogramslikehttpd,apachectl,suexec,etc.whichareneccessarytoruntheApacheHTTPServer.BydefaultsbindirissettoEPREFIX/sbin.

--sharedstatedir=DIR

Installmodifiablearchitecture-independentdatainDIR.BydefaultsharedstatedirissettoPREFIX/com.Thisoptionisofferedbyautoconfandcurrentlyunused.

--sysconfdir=DIR

Installread-onlysingle-machinedataliketheserverconfigurationfileshttpd.conf,mime.types,etc.inDIR.BydefaultsysconfdirissettoPREFIX/conf.

SystemtypesTheseoptionsareusedtocross-compiletheApacheHTTPServer

torunonanothersystem.Innormalcases,whenbuildingandrunningtheserveronthesamesystem,theseoptionsarenotused.

--build=BUILD

Definesthesystemtypeofthesystemonwhichthetoolsarebeingbuilt.Itdefaultstotheresultofthescriptconfig.guess.

--host=HOST

Definesthesystemtypeofthesystemonwhichtheserverwillrun.HOSTdefaultstoBUILD.

--target=TARGET

ConfigureforbuildingcompilersforthesystemtypeTARGET.ItdefaultstoHOST.ThisoptionisofferedbyautoconfandnotnecessaryfortheApacheHTTPServer.

OptionalFeaturesTheseoptionsareusedtofinetunethefeaturesyourHTTPserverwillhave.

GeneralsyntaxGenerallyyoucanusethefollowingsyntaxtoenableordisableafeature:

--disable-FEATURE

DonotincludeFEATURE.Thisisthesameas--enable-FEATURE=no.

--enable-FEATURE[=ARG]

IncludeFEATURE.ThedefaultvalueforARGisyes.

--enable-MODULE=shared

ThecorrespondingmodulewillbebuildasDSOmodule.

--enable-MODULE=static

Bydefaultenabledmodulesarelinkedstatically.Youcanforcethisexplicitly.

Noteconfigurewillnotcomplainabout--enable-fooeveniffoodoesn'texist,soyouneedtotypecarefully.

ModulesenabledbydefaultSomemodulesarecompiledbydefaultandhavetobedisabledexplicitly.Usethefollowingoptionstoremovediscretemodulesfromthecompilationprocess.

--disable-actions

Disableactiontriggeringonrequests,whichisprovidedbymod_actions.

--disable-alias

Disablethemappingofrequeststodifferentpartsofthefilesystem,whichisprovidedbymod_alias.

--disable-asis

Disablesupportforas-isfiletypes,whichisprovidedbymod_asis.

--disable-auth

Disableuser-basedaccesscontrolprovidedbymod_auth.ThismoduleprovidesforHTTPBasicAuthentication,wheretheusernamesandpasswordsarestoredinplaintextfiles.

--disable-autoindex

Disablethedirectorylistingfunctionalityprovidedbymod_autoindex.

--disable-access

Disablehost-basedaccesscontrolprovidedbymod_access.

--disable-cgi

mod_cgi,whichprovidessupportforCGIscripts,isenabledbydefaultwhenusinganon-threadedMPM.UsethisoptiontodisableCGIsupport.

--disable-cgid

WhenusingthethreadedMPMsworkerorperchildsupportforCGIscriptsisprovidedbymod_cgidbydefault.TodisableCGIsupportusethisoption.

--disable-charset-lite

Disablecharactersettranslationprovidedbymod_charset_lite.ThismodulewillbeinstalledbydefaultonlyonEBCDICsystems.

--disable-dir

Disabledirectoryrequesthandlingprovidedbymod_dir.

--disable-env

Disablesettingandclearingofenvironmentvariables,whichisprovidedbymod_env.

--disable-http

DisabletheHTTPprotocolhandling.Thehttpmoduleisabasicone,enablingtheservertofunctionasanHTTPserver.Itisonlyusefultodisableitifyouwanttouseanotherprotocolmoduleinstead.Don'tdisablethismoduleunlessyouarereallysurewhatyouaredoing.Note:Thismodulewillalwaysbelinkedstatically.

--disable-imap

Disablesupportforserverbasedimagemaps,whichprovidedbymod_imap.

--disable-include

DisableServerSideIncludesprovidedbymod_include.

--disable-log-config

Disabletheloggingconfigurationprovidedby

mod_log_config.Youwon'tbeabletologrequeststotheserverwithoutthismodule.

--disable-mime

mod_mimeassociatestherequestedfilename'sextensionswiththefile'sbehaviorandcontent(mime-type,language,charactersetandencoding).Disablingthemappingoffile-extensionstoMIMEisnormallynotrecommended.

--disable-negotiation

Disablecontentnegotiationprovidedbymod_negotiation.

--disable-setenvif

Disablesupportforbasingenvironmentvariablesonheaders,whichisprovidedbymod_setenvif.

--disable-status

Disabletheprocess/threadmonitoring,whichisprovidedbymod_status.

--disable-userdir

Disablethemappingofrequeststouser-specificdirectories,whichisprovidedbymod_userdir.

Modules,disabledbydefaultSomemodulesarecompiledbydefaultandhavetobeenabledexplicitlyorbyusingthekeywordsmostorall(see--enable-mods-sharedbelowforfurtherexplanation)tobeavailable.Thereforeusetheoptionsbelow.

--enable-auth-anon

Enableanonymoususeraccessprovidedbymod_auth_anon.

--enable-auth-dbm

mod_auth_dbmprovidesforHTTPBasicAuthentication,wheretheusernamesandpasswordsarestoredinDBMtype

databasefiles.Usethisoptiontoenablethemodule.

--enable-auth-digest

EnableRFC2617Digestauthenticationprovidedbymod_auth_digest.Thismoduleusesplaintextfilestostorethecredentials.

--enable-auth-ldap

EnableLDAPbasedauthenticationprovidedbymod_auth_ldap.

--enable-cache

Enabledynamicfilecachingprovidedbymod_cache.Thisexperimentalmodulemaybeinterestingforserverswithhighloadorcachingproxyservers.Atleastonestoragemanagementmodule(e.g.mod_disk_cacheormod_mem_cache)isalsonecessary.

--enable-cern-meta

EnabletheCERN-typemetafilessupportprovidedbymod_cern_meta.

--enable-charset-lite

Enablecharactersettranslationprovidedbymod_charset_lite.ThismodulewillbeinstalledbydefaultonlyonEBCDICsystems.Onothersystems,youhavetoenableit.

--enable-dav

EnabletheWebDAVprotocolhandlingprovidedbymod_dav.Supportforfilesystemresourcesisprovidedbytheseperatemodulemod_dav_fs.Thismoduleisalsoautomaticallyenabledwith--enable-dav.Note:mod_davcanonlybeusedtogetherwiththehttpprotocolmodule.

--enable-dav-fs

EnableDAVsupportforfilesystemresources,whichis

providedbymod_dav_fs.Thismoduleisaproviderforthemod_davmodule,soyoushouldalsouse--enable-dav.

--enable-deflate

Enabledeflatetransferencodingprovidedbymod_deflate.

--enable-disk-cache

Enablediskcachingprovidedbymod_disk_cache.

--enable-expires

EnableExpiresheadercontrolprovidedbymod_expires.

--enable-ext-filter

Enabletheexternalfiltersupportprovidedbymod_ext_filter.

--enable-file-cache

Enablethefilecacheprovidedbymod_file_cache.

--enable-headers

EnablecontrolofHTTPheadersprovidedbymod_headers.

--enable-info

Enabletheserverinformationprovidedbymod_info.

--enable-ldap

EnableLDAPcachingandconnectionpoolingservicesprovidedbymod_ldap.

--enable-logio

Enableloggingofinputandoutputbytesincludingheadersprovidedbymod_logio.

--enable-mem-cache

Enablememorycachingprovidedbymod_mem_cache.

--enable-mime-magic

EnableautomaticaldeterminingofMIMEtypes,whichisprovidedbymod_mime_magic.

--enable-isapi

Enabletheisapiextensionsupportprovidedbymod_isapi.

--enable-proxy

Enabletheproxy/gatewayfunctionalityprovidedbymod_proxy.TheproxyingcapabilitiesforCONNECT,FTPandHTTPareprovidedbytheseperatemodulesmod_proxy_connect,mod_proxy_ftpandmod_proxy_http.Thesethreemodulesarealsoautomaticallyenabledwith--enable-proxy.

--enable-proxy-connect

EnableproxysupportforCONNECTrequesthandling,whichisprovidedbymod_proxy_connect.Thismoduleisanextensionforthemod_proxymodule,soyoushouldalsouse--enable-proxy.

--enable-proxy-ftp

EnableproxysupportforFTPrequests,whichisprovidedbymod_proxy_ftp..Thismoduleisanextensionforthemod_proxymodule,soyoushouldalsouse--enable-proxy.

--enable-proxy-http

EnableproxysupportforHTTPrequests,whichisprovidedbymod_proxy_http.Thismoduleisanextensionforthemod_proxymodule,soyoushouldalsouse--enable-proxy.

--enable-rewrite

EnablerulebasedURLmanipulationprovidedbymod_rewrite.

--enable-so

EnableDSOcapabilityprovidedbymod_so.Thismodulewillbeautomaticallyenabledifyouusethe--enable-mods-sharedoption.

--enable-speling

EnablethefunctionalitytocorrectcommonURLmisspellings,whichisprovidedbymod_speling.

--enable-ssl

EnablesupportforSSL/TLSprovidedbymod_ssl.

--enable-unique-id

Enablethegenerationofper-requestuniqueids,whichisprovidedbymod_unique_id.

--enable-usertrack

Enableuser-sessiontrackingprovidedbymod_usertrack.

--enable-vhost-alias

Enablemassvirtualhostingprovidedbymod_vhost_alias.

ModulesfordevelopersThefollowingmodulesareusefulonlyfordevelopersandtestingpurposesandaredisabledbydefault.Usethefollowingoptionstoenablethem.Ifyouarenotsurewhetheryouneedoneofthesemodules,omitthem.

--enable-bucketeer

Enablethemanipulationfilterforbuckets,whichisprovidedbymod_bucketeer.

--enable-case-filter

Enabletheexampleuppercaseconversionoutputfiltersupportofmod_case_filter.

--enable-case-filter-in

Enabletheexampleuppercaseconversioninputfiltersupportofmod_case_filter_in.

--enable-echo

EnabletheECHOserverprovidedbymod_echo.

--enable-example

Enabletheexampleanddemomodulemod_example.

--enable-optional-fn-export

Enabletheexampleforanoptionalfunctionexporter,whichisprovidedbymod_optional_fn_export.

--enable-optional-fn-import

Enabletheexampleforanoptionalfunctionimporter,whichisprovidedbymod_optional_fn_import.

--enable-optional-hook-export

Enabletheexampleforanoptionalhookexporter,whichisprovidedbymod_optional_hook_export.

--enable-optional-hook-import

Enabletheexampleoptionalhookimporter,whichisprovidedbymod_optional_hook_import.

MPMsandthird-partymodulesToaddthenecessaryMultiProcessingModuleandadditionalthird-partymodulesusethefollowingoptions:

--with-module=module-type:module-file[,module-

type:module-file]

Addoneormorethird-partymodulestothelistofstaticallylinkedmodules.Themodulesourcefilemodule-filewillbesearchedinthemodules/module-typesubdirectoryofyourApacheHTTPserversourcetree.Ifitisnotfoundthereconfigureisconsideringmodule-filetobeanabsolutefilepathandtriestocopythesourcefileintothemodule-typesubdirectory.Ifthesubdirectorydoesn'texistitwillbecreatedandpopulatedwithastandardMakefile.in.

Thisoptionisusefultoaddsmallexternalmodulesconsistingofonesourcefile.Formorecomplexmodulesyoushouldreadthevendor'sdocumentation.

Note

IfyouwanttobuildaDSOmoduleinsteadofastaticallylinkeduseapxs.

--with-mpm=MPM

Choosetheprocessmodelforyourserver.YouhavetoselectexactlyoneMulti-ProcessingModule.OtherwisethedefaultMPMforyouroperatingsystemwillbetaken.PossibleMPMsarebeos,leader,mpmt_os2,perchild,prefork,threadpoolandworker.

Cumulativeandotheroptions--enable-maintainer-mode

Turnondebuggingandcompiletimewarnings.

--enable-mods-shared=MODULE-LIST

Definesalistofmodulestobeenabledandbuildasdynamicsharedmodules.Thismean,thesemodulehavetobeloadeddynamicallybyusingtheLoadModuledirective.

MODULE-LISTisaspaceseparatedlistofmodulenamesenclosedbyquotationmarks.Themodulenamesaregivenwithouttheprecedingmod_.Forexample:

--enable-mods-shared='headersrewritedav'

Additionallyyoucanusethespecialkeywordsallandmost.Forexample,

--enable-mods-shared=most

willcompilemostmodulesandbuildthemasDSOmodules.

--enable-modules=MODULE-LIST

Thisoptionbehavessimilarto--enable-mods-shared,butwilllinkthegivenmodulesstatically.Thismean,thesemoduleswillalwaysbepresentwhilerunninghttpd.TheyneednotbeloadedwithLoadModule.

--enable-v4-mapped

AllowIPv6socketstohandleIPv4connections.

--with-port=PORT

Thisdefinestheportonwhichhttpdwilllisten.Thisportnumberisusedwhengeneratingtheconfigurationfilehttpd.conf.Thedefaultis80.

--with-program-name

Defineanalternativeexecutablename.Thedefaultishttpd.

OptionalpackagesTheseoptionsareusedtodefineoptionalpackages.

GeneralsyntaxGenerallyyoucanusethefollowingsyntaxtodefineanoptionalpackage:

--with-PACKAGE[=ARG]

UsethepackagePACKAGE.ThedefaultvalueforARGisyes.

--without-PACKAGE

DonotusethepackagePACKAGE.Thisisthesameas--with-PACKAGE=no.ThisoptionisprovidedbyautoconfbutnotveryusefulfortheApacheHTTPServer.

Specificpackages--with-apr=DIR|FILE

TheApachePortableRuntime(APR)ispartofthehttpd

sourcedistributionandwillautomaticallybebuildtogetherwiththeHTTPserver.IfyouwanttouseanalreadyinstalledAPRinsteadyouhavetotellconfigurethepathtotheapr-configscript.YoumaysettheabsolutepathandnameorthedirectorytotheinstalledAPR.apr-configmustexistwithinthisdirectoryorthesubdirectorybin.

--with-apr-util=DIR|FILE

TheApachePortableRuntimeUtilities(APU)arepartofthehttpdsourcedistributionandwillautomaticallybebuildtogetherwiththeHTTPserver.IfyouwanttouseanalreadyinstalledAPUinsteadyouhavetotellconfigurethepathtotheapu-configscript.YoumaysettheabsolutepathandnameorthedirectorytotheinstalledAPU.apu-configmustexistwithinthisdirectoryorthesubdirectorybin.

--with-ssl=DIR

Ifmod_sslhasbeenenabledconfiguresearchesforaninstalledOpenSSL.YoucansetthedirectorypathtotheSSL/TLStoolkitinstead.

--with-z=DIR

configuresearchesautomaticallyforaninstalledzliblibraryifyoursourceconfigurationrequiresone(e.g.,whenmod_deflateisenabled).Youcansetthedirectorypathtothecompressionlibraryinstead.

SeveralfeaturesoftheApacheHTTPServer,includingmod_authn_dbmandmod_rewrite'sDBMRewriteMapusesimplekey/valuedatabasesforquicklookupsofinformation.SDBMisincludedintheAPU,sothisdatabaseisalwaysavailable.Ifyouwouldliketouseotherdatabasetypes,usethefollowingoptionstoenablethem:

--with-gdbm[=path]

Ifnopathisspecified,configurewillsearchfortheincludefilesandlibrariesofaGNUDBMinstallationintheusualsearchpaths.Anexplicitpathwillcauseconfiguretolookinpath/libandpath/includefortherelevantfiles.Finally,thepathmayspecifyspecificincludeandlibrarypathsseparatedbyacolon.

--with-ndbm[=path]

Like--with-gdbm,bursearchesforaNewDBMinstallation.

--with-berkeley-db[=path]

Like--with-gdbm,butsearchesforaBerkeleyDBinstallation.

Note

TheDBMoptionsareprovidedbytheAPUandpassedthroughtoitsconfigurationscript.TheyareuselesswhenusinganalreadyinstalledAPUdefinedby--with-apr-util.

YoumayusemorethenoneDBMimplementationtogetherwithyourHTTPserver.TheappropriatedDBMtypewillbeconfiguredwithintheruntimeconfigurationateachtime.

Optionsforsupportprograms--enable-static-support

Buildastaticallylinkedversionofthesupportbinaries.Thismeans,astand-aloneexecutablewillbebuiltwithallthenecessarylibrariesintegrated.Otherwisethesupportbinariesarelinkeddynamicallybydefault.

--enable-suexec

Usethisoptiontoenablesuexec,whichallowsyoutosetuidandgidforspawnedprocesses.Donotusethisoptionunlessyouunderstandallthesecurityimplicationsofrunningasuidbinaryonyourserver.Furtheroptionsto

configuresuexecaredescribedbelow.

Itispossibletocreateastaticallylinkedbinaryofasinglesupportprogrambyusingthefollowingoptions:

--enable-static-ab

Buildastaticallylinkedversionofab.

--enable-static-checkgid

Buildastaticallylinkedversionofcheckgid.

--enable-static-htdbm

Buildastaticallylinkedversionofhtdbm.

--enable-static-htdigest

Buildastaticallylinkedversionofhtdigest.

--enable-static-htpasswd

Buildastaticallylinkedversionofhtpasswd.

--enable-static-logresolve

Buildastaticallylinkedversionoflogresolve.

--enable-static-rotatelogs

Buildastaticallylinkedversionofrotatelogs.

suexecconfigurationoptionsThefollowingoptionsareusedtofinetunethebehaviorofsuexec.SeeConfiguringandinstallingsuEXECorfurtherinformation.

--with-suexec-bin

Thisdefinesthepathtosuexecbinary.Defaultis--sbindir(seeFinetuningofinstallationdirectories).

--with-suexec-caller

Thisdefinestheuserallowedtocallsuexec.Itshouldbethesameastheuserunderwhichhttpdnormallyruns.

--with-suexec-docroot

Thisdefinesthedirectorytreeunderwhichsuexecaccessisallowedforexecutables.Defaultvalueis--datadir/htdocs.

--with-suexec-gidmin

DefinethisasthelowestGIDallowedtobeatargetuserforsuexec.Thedefaultvalueis100.

--with-suexec-logfile

Thisdefinesthefilenameofthesuexeclogfile.Bydefaultthelogfileisnamedsuexec_logandlocatedin--logfiledir.

--with-suexec-safepath

DefinethevalueoftheenvironmentvariablePATHtobesetforprocessesstartedbysuexec.Defaultvalueis/usr/local/bin:/usr/bin:/bin.

--with-suexec-userdir

Thisdefinesthesubdirectoryundertheuser'sdirectorythatcontainsallexecutablesforwhichsuexecaccessisallowed.Thissettingisnecessarywhenyouwanttousesuexectogetherwithuser-specificdirectories(asprovidedbymod_userdir).Thedefaultispublic_html.

--with-suexec-uidmin

DefinethisasthelowestUIDallowedtobeatargetuserforsuexec.Thedefaultvalueis100.

--with-suexec-umask

Setumaskforprocessesstartedbysuexec.Itdefaultstoyoursystemsettings.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Environmentvariables

Therearesomeusefulenvironmentvariablestooverridethechoicesmadebyconfigureortohelpittofindlibrariesandprogramswithnonstandardnamesorlocations.

CC

DefinetheCcompilercommandtobeusedforcompilation.

CFLAGS

SetCcompilerflagsyouwanttouseforcompilation.

CPP

DefinetheCpreprocessorcommandtobeused.

CPPFLAGS

SetC/C++preprocessorflags,e.g.-Iincludedirifyouhaveheadersinanonstandarddirectoryincludedir.

LDFLAGS

Setlinkerflags,e.g.-Llibdirifyouhavelibrariesinanonstandarddirectorylibdir.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

dbmmanage-ManageuserauthenticationfilesinDBMformat

dbmmanageisusedtocreateandupdatetheDBMformatfilesusedtostoreusernamesandpasswordforbasicauthenticationofHTTPusersviamod_auth_dbm.ResourcesavailablefromtheApacheHTTPservercanberestrictedtojusttheuserslistedinthefilescreatedbydbmmanage.ThisprogramcanonlybeusedwhentheusernamesarestoredinaDBMfile.Touseaflat-filedatabaseseehtpasswd.

Thismanualpageonlyliststhecommandlinearguments.Fordetailsofthedirectivesnecessarytoconfigureuserauthenticationinhttpdseethehttpdmanual,whichispartoftheApachedistributionorcanbefoundathttp://httpd.apache.org/.

Seealsohttpd

mod_auth_dbm

Synopsisdbmmanage[encoding]filename

add|adduser|check|delete|updateusername[

encpasswd[group[,group...][comment]]]

dbmmanagefilenameview[username]

dbmmanagefilenameimport

Options

filename

ThefilenameoftheDBMformatfile.Usuallywithouttheextension.db,.pag,or.dir.

username

Theuserforwhichtheoperationsareperformed.Theusernamemaynotcontainacolon(:).

encpasswd

Thisisthealreadyencryptedpasswordtousefortheupdateandaddcommands.Youmayuseahyphen(-)ifyouwanttogetpromptedforthepassword,butfillinthefieldsafterwards.Additionallywhenusingtheupdatecommand,aperiod(.)keepstheoriginalpassworduntouched.

group

Agroup,whichtheuserismemberof.Agroupnamemaynotcontainacolon(:).Youmayuseahyphen(-)ifyoudon'twanttoassigntheusertoagroup,butfillinthecommentfield.Additionallywhenusingtheupdatecommand,aperiod(.)keepstheoriginalgroupsuntouched.

comment

Thisistheplaceforyouropaquecommentsabouttheuser,likerealname,mailaddressorsuchthings.Theserverwillignorethisfield.

Encodings-d

cryptencryption(default,exceptonWin32,Netware)

-m

MD5encryption(defaultonWin32,Netware)

-s

SHA1encryption

-p

plaintext(notrecommended)

Commandsadd

Addsanentryforusernametofilenameusingtheencryptedpasswordencpasswd.

dbmmanagepasswords.dataddrbowenfoKntnEF3KSXA

adduser

Asksforapasswordandthenaddsanentryforusernametofilename.

dbmmanagepasswords.datadduserkrietz

check

Asksforapasswordandthenchecksifusernameisinfilenameandifit'spasswordmatchesthespecifiedone.

dbmmanagepasswords.datcheckrbowen

delete

Deletestheusernameentryfromfilename.

dbmmanagepasswords.datdeleterbowen

import

Readsusername:passwordentries(oneperline)fromSTDINandaddsthemtofilename.Thepasswordsalreadyhavetobecrypted.

update

Sameastheaddusercommand,exceptthatitmakessureusernamealreadyexistsinfilename.

dbmmanagepasswords.datupdaterbowen

view

JustdisplaysthecontentsoftheDBMfile.Ifyouspecifyausername,itdisplaystheparticularrecordonly.

dbmmanagepasswords.datview

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Bugs

OneshouldbeawarethatthereareanumberofdifferentDBMfileformatsinexistence,andwithalllikelihood,librariesformorethanoneformatmayexistonyoursystem.ThethreeprimaryexamplesareSDBM,NDBM,theGNUproject'sGDBM,andBerkeleyDB2.Unfortunately,alltheselibrariesusedifferentfileformats,andyoumustmakesurethatthefileformatusedbyfilenameisthesameformatthatdbmmanageexpectstosee.dbmmanagecurrentlyhasnowayofdeterminingwhattypeofDBMfileitislookingat.Ifusedagainstthewrongformat,willsimplyreturnnothing,ormaycreateadifferentDBMfilewithadifferentname,oratworst,itmaycorrupttheDBMfileifyouwereattemptingtowritetoit.

dbmmanagehasalistofDBMformatpreferences,definedbythe@AnyDBM::ISAarraynearthebeginningoftheprogram.SinceweprefertheBerkeleyDB2fileformat,theorderinwhichdbmmanagewilllookforsystemlibrariesisBerkeleyDB2,thenNDBM,thenGDBMandthenSDBM.ThefirstlibraryfoundwillbethelibrarydbmmanagewillattempttouseforallDBMfiletransactions.Thisorderingisslightlydifferentthanthestandard@AnyDBM::ISAorderinginPerl,aswellastheorderingusedbythesimpledbmopen()callinPerl,soifyouuseanyotherutilitiestomanageyourDBMfiles,theymustalsofollowthispreferenceordering.Similarcaremustbetakenifusingprogramsinotherlanguages,likeC,toaccessthesefiles.

OnecanusuallyusethefileprogramsuppliedwithmostUnixsystemstoseewhatformataDBMfileisin.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

htdigest-manageuserfilesfordigestauthentication

htdigestisusedtocreateandupdatetheflat-filesusedtostoreusernames,realmandpasswordfordigestauthenticationofHTTPusers.ResourcesavailablefromtheApacheHTTPservercanberestrictedtojusttheuserslistedinthefilescreatedbyhtdigest.

Thismanualpageonlyliststhecommandlinearguments.FordetailsofthedirectivesnecessarytoconfiguredigestauthenticationinhttpdseetheApachemanual,whichispartoftheApachedistributionorcanbefoundathttp://httpd.apache.org/.

Seealsohttpd

mod_auth_digest

Synopsishtdigest[-c]passwdfilerealmusername

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Options

-c

Createthepasswdfile.Ifpasswdfilealreadyexists,itisdeletedfirst.

passwdfile

Nameofthefiletocontaintheusername,realmandpassword.If-cisgiven,thisfileiscreatedifitdoesnotalreadyexist,ordeletedandrecreatedifitdoesexist.

realm

Therealmnametowhichtheusernamebelongs.

username

Theusernametocreateorupdateinpasswdfile.Ifusernamedoesnotexististhisfile,anentryisadded.Ifitdoesexist,thepasswordischanged.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

htpasswd-Manageuserfilesforbasicauthentication

htpasswdisusedtocreateandupdatetheflat-filesusedtostoreusernamesandpasswordforbasicauthenticationofHTTPusers.Ifhtpasswdcannotaccessafile,suchasnotbeingabletowritetotheoutputfileornotbeingabletoreadthefileinordertoupdateit,itreturnsanerrorstatusandmakesnochanges.

ResourcesavailablefromtheApacheHTTPservercanberestrictedtojusttheuserslistedinthefilescreatedbyhtpasswd.Thisprogramcanonlymanageusernamesandpasswordsstoredinaflat-file.Itcanencryptanddisplaypasswordinformationforuseinothertypesofdatastores,though.TouseaDBMdatabaseseedbmmanage.

htpasswdencryptspasswordsusingeitheraversionofMD5modifiedforApache,orthesystem'scrypt()routine.Filesmanagedbyhtpasswdmaycontainbothtypesofpasswords;someuserrecordsmayhaveMD5-encryptedpasswordswhileothersinthesamefilemayhavepasswordsencryptedwithcrypt().

Thismanualpageonlyliststhecommandlinearguments.FordetailsofthedirectivesnecessarytoconfigureuserauthenticationinhttpdseetheApachemanual,whichispartoftheApachedistributionorcanbefoundathttp://httpd.apache.org/.

Seealsohttpd

Thescriptsinsupport/SHA1whichcomewiththedistribution.

Synopsishtpasswd[-c][-m][-D]passwdfileusername

htpasswd-b[-c][-m|-d|-p|-s][-D]

passwdfileusernamepassword

htpasswd-n[-m|-d|-s|-p]username

htpasswd-nb[-m|-d|-s|-p]username

password

Options

-b

Usebatchmode;i.e.,getthepasswordfromthecommandlineratherthanpromptingforit.Thisoptionshouldbeusedwithextremecare,sincethepasswordisclearlyvisibleonthecommandline.

-c

Createthepasswdfile.Ifpasswdfilealreadyexists,itisrewrittenandtruncated.Thisoptioncannotbecombinedwiththe-noption.

-n

Displaytheresultsonstandardoutputratherthanupdatingafile.ThisisusefulforgeneratingpasswordrecordsacceptabletoApacheforinclusioninnon-textdatastores.Thisoptionchangesthesyntaxofthecommandline,sincethepasswdfileargument(usuallythefirstone)isomitted.Itcannotbecombinedwiththe-coption.

-m

UseMD5encryptionforpasswords.OnWindows,NetwareandTPF,thisisthedefault.

-d

Usecrypt()encryptionforpasswords.ThedefaultonallplatformsbutWindows,NetwareandTPF.Thoughpossiblysupportedbyhtpasswdonallplatforms,itisnotsupportedbythehttpdserveronWindows,NetwareandTPF.

-s

UseSHAencryptionforpasswords.Facilitatesmigrationfrom/toNetscapeserversusingtheLDAPDirectoryInterchangeFormat(ldif).

-p

Useplaintextpasswords.Thoughhtpasswdwillsupport

creationonallplatforms,thehttpddaemonwillonlyacceptplaintextpasswordsonWindows,NetwareandTPF.

-D

Deleteuser.Iftheusernameexistsinthespecifiedhtpasswdfile,itwillbedeleted.

passwdfile

Nameofthefiletocontaintheusernameandpassword.If-cisgiven,thisfileiscreatedifitdoesnotalreadyexist,orrewrittenandtruncatedifitdoesexist.

username

Theusernametocreateorupdateinpasswdfile.Ifusernamedoesnotexistinthisfile,anentryisadded.Ifitdoesexist,thepasswordischanged.

password

Theplaintextpasswordtobeencryptedandstoredinthefile.Onlyusedwiththe-bflag.

ExitStatus

htpasswdreturnsazerostatus("true")iftheusernameandpasswordhavebeensuccessfullyaddedorupdatedinthepasswdfile.htpasswdreturns1ifitencounterssomeproblemaccessingfiles,2iftherewasasyntaxproblemwiththecommandline,3ifthepasswordwasenteredinteractivelyandtheverificationentrydidn'tmatch,4ifitsoperationwasinterrupted,5ifavalueistoolong(username,filename,password,orfinalcomputedrecord),6iftheusernamecontainsillegalcharacters(seetheRestrictionssection),and7ifthefileisnotavalidpasswordfile.

Examples

htpasswd/usr/local/etc/apache/.htpasswd-usersjsmith

Addsormodifiesthepasswordforuserjsmith.Theuserispromptedforthepassword.IfexecutedonaWindowssystem,thepasswordwillbeencryptedusingthemodifiedApacheMD5algorithm;otherwise,thesystem'scrypt()routinewillbeused.Ifthefiledoesnotexist,htpasswdwilldonothingexceptreturnanerror.

htpasswd-c/home/doe/public_html/.htpasswdjane

Createsanewfileandstoresarecordinitforuserjane.Theuserispromptedforthepassword.Ifthefileexistsandcannotberead,orcannotbewritten,itisnotalteredandhtpasswdwilldisplayamessageandreturnanerrorstatus.

htpasswd-mb/usr/web/.htpasswd-alljonesPwd4Steve

Encryptsthepasswordfromthecommandline(Pwd4Steve)usingtheMD5algorithm,andstoresitinthespecifiedfile.

SecurityConsiderations

WebpasswordfilessuchasthosemanagedbyhtpasswdshouldnotbewithintheWebserver'sURIspace--thatis,theyshouldnotbefetchablewithabrowser.

Theuseofthe-boptionisdiscouraged,sincewhenitisusedtheunencryptedpasswordappearsonthecommandline.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Restrictions

OntheWindowsandMPEplatforms,passwordsencryptedwithhtpasswdarelimitedtonomorethan255charactersinlength.Longerpasswordswillbetruncatedto255characters.

TheMD5algorithmusedbyhtpasswdisspecifictotheApachesoftware;passwordsencryptedusingitwillnotbeusablewithotherWebservers.

Usernamesarelimitedto255bytesandmaynotincludethecharacter:.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

logresolve-ResolveIP-addressestohostnamesinApachelogfiles

logresolveisapost-processingprogramtoresolveIP-addressesinApache'saccesslogfiles.Tominimizeimpactonyournameserver,logresolvehasitsveryowninternalhash-tablecache.ThismeansthateachIPnumberwillonlybelookedupthefirsttimeitisfoundinthelogfile.

TakesanApachelogfileonstandardinput.TheIPaddressesmustbethefirstthingoneachlineandmustbeseperatedfromtheremainderofthelinebyaspace.

Synopsislogresolve[-sfilename][-c]<access_log>

access_log.new

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Options

-sfilename

Specifiesafilenametorecordstatistics.

-c

ThiscauseslogresolvetoapplysomeDNSchecks:afterfindingthehostnamefromtheIPaddress,itlooksuptheIPaddressesforthehostnameandchecksthatoneofthesematchestheoriginaladdress.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

rotatelogs-PipedloggingprogramtorotateApachelogs

rotatelogsisasimpleprogramforuseinconjunctionwithApache'spipedlogfilefeature.Forexample:

CustomLog"|bin/rotatelogs/var/logs/logfile86400"common

Thiscreatesthefiles/var/logs/logfile.nnnnwherennnnisthesystemtimeatwhichthelognominallystarts(thistimewillalwaysbeamultipleoftherotationtime,soyoucansynchronizecronscriptswithit).Attheendofeachrotationtime(hereafter24hours)anewlogisstarted.

CustomLog"|bin/rotatelogs/var/logs/logfile5M"common

Thisconfigurationwillrotatethelogfilewheneveritreachesasizeof5megabytes.

ErrorLog"|bin/rotatelogs/var/logs/errorlog.%Y-%m-%d-%H_%M_%S5M"

Thisconfigurationwillrotatetheerrorlogfilewheneveritreachesasizeof5megabytes,andthesuffixtothelogfilenamewillbecreatedoftheformerrorlog.YYYY-mm-dd-HH_MM_SS.

Synopsisrotatelogs[-l]logfile[rotationtime[offset

]]|[filesizeM]

Options

-l(2.0.51andlater)CausestheuseoflocaltimeratherthanGMTasthebasefortheinterval.Notethatusing-linanenvironmentwhichchangestheGMToffset(suchasforBSTorDST)canleadtounpredictableresults!

logfile

Thepathplusbasenameofthelogfile.Iflogfileincludesany'%'characters,itistreatedasaformatstringforstrftime(3).Otherwise,thesuffix.nnnnnnnnnnisautomaticallyaddedandisthetimeinseconds.Bothformatscomputethestarttimefromthebeginningofthecurrentperiod.

rotationtime

Thetimebetweenlogfilerotationsinseconds.

offset

ThenumberofminutesoffsetfromUTC.Ifomitted,zeroisassumedandUTCisused.Forexample,touselocaltimeinthezoneUTC-5hours,specifyavalueof-300forthisargument.

filesizeM

ThemaximumfilesizeinmegabytesfollowedbytheletterMtospecifysizeratherthantime.Usethisparameterinplaceofbothrotationtimeandoffset.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Portability

Thefollowinglogfileformatstringsubstitutionsshouldbesupportedbyallstrftime(3)implementations,seethestrftime(3)manpageforlibrary-specificextensions.

%A fullweekdayname(localized)%a 3-characterweekdayname(localized)%B fullmonthname(localized)%b 3-charactermonthname(localized)%c dateandtime(localized)%d 2-digitdayofmonth%H 2-digithour(24hourclock)%I 2-digithour(12hourclock)%j 3-digitdayofyear%M 2-digitminute%m 2-digitmonth%p am/pmof12hourclock(localized)%S 2-digitsecond%U 2-digitweekofyear(Sundayfirstdayofweek)%W 2-digitweekofyear(Mondayfirstdayofweek)%w 1-digitweekday(Sundayfirstdayofweek)%X time(localized)%x date(localized)%Y 4-digityear%y 2-digityear%Z timezonename%% literal`%'

Modules|Directives|FAQ|Glossary|Sitemap

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

OtherPrograms

ThefollowingprogramsaresimplesupportprogramsincludedwiththeApacheHTTPServerwhichdonothavetheirownmanualpages.Theyarenotinstalledautomatically.Youcanfindthemaftertheconfigurationprocessinthesupport/directory.

log_server_status

Thisperlscriptisdesignedtoberunatafrequentintervalbysomethinglikecron.Itconnectstotheserveranddownloadsthestatusinformation.Itreformatstheinformationtoasinglelineandlogsittoafile.Adjustthevariablesatthetopofthescripttospecifythelocationoftheresultinglogfile.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

split-logfile

ThisperlscriptwilltakeacombinedWebserveraccesslogfileandbreakitscontentsintoseparatefiles.Itassumesthatthefirstfieldofeachlineisthevirtualhostidentity(putthereby"%v"),andthatthelogfilesshouldbenamedthat+".log"inthecurrentdirectory.

Thecombinedlogfileisreadfromstdin.Recordsreadwillbeappendedtoanyexistinglogfiles.

split-logfile<access.log

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>MiscellaneousDocumentation

InternationalCustomizedServerErrorMessages

Warning:

Thisdocumenthasnotbeenfullyupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

ThisdocumentdescribesaneasywaytoprovideyourApacheHTTPServerwithasetofcustomizederrormessageswhichtakeadvantageofContentNegotiationandmod_includetoreturnerrormessagesgeneratedbytheserverintheclient'snativelanguage.

Introduction

ByusingSSI,allErrorDocumentmessagescanshareahomogenousandconsistentstyleandlayout,andmaintenancework(changingimages,changinglinks)iskepttoaminimumbecausealllayoutinformationcanbekeptinasinglefile.

Errordocumentscanbesharedacrossdifferentservers,orevenhosts,becauseallvaryinginformationisinsertedatthetimetheerrordocumentisreturnedonbehalfofafailedrequest.

ContentNegotiationthenselectstheappropriatelanguageversionofaparticularerrormessagetext,honoringthelanguagepreferencespassedintheclient'srequest.(Usersusuallyselecttheirfavoritelanguagesinthepreferencesoptionsmenuoftoday'sbrowsers).Whenanerrordocumentintheclient'sprimarylanguageversionisunavailable,thesecondarylanguagesaretriedoradefault(fallback)versionisused.

Youhavefullflexibilityindesigningyourerrordocumentstoyourpersonaltaste(oryourcompany'sconventions).Fordemonstrationpurposes,wepresentasimplegenericerrordocumentscheme.Forthishypotheticserver,weassumethatallerrormessages...

possiblyareservedbydifferentvirtualhosts(differenthostname,differentIPaddress,ordifferentport)ontheservermachine,showapredefinedcompanylogointherighttopofthemessage(selectablebyvirtualhost),printtheerrortitlefirst,followedbyanexplanatorytextand(dependingontheerrorcontext)helponhowtoresolvetheerror,havesomekindofstandardizedbackgroundimage,displayanapachelogoandafeedbackemailaddressatthebottomoftheerrormessage.

Anexampleofa"documentnotfound"messageforagermanclientmightlooklikethis:

Alllinksinthedocumentaswellaslinkstotheserver'sadministratormailaddress,andeventhenameandportoftheservingvirtualhostareinsertedintheerrordocumentat"run-time",i.e.,whentheerroractuallyoccurs.

CreatinganErrorDocumentdirectory

Forthisconcepttoworkaseasilyaspossible,wemusttakeadvantageofasmuchserversupportaswecanget:

1. BydefiningtheMultiViewsOptions,weenablethelanguageselectionofthemostappropriatelanguagealternative(contentnegotiation).

2. BysettingtheLanguagePrioritydirectivewedefineasetofdefaultfallbacklanguagesinthesituationwheretheclient'sbrowserdidnotexpressanypreferenceatall.

3. Byenablingmod_include(anddisallowingexecutionofcgiscriptsforsecurityreasons),weallowtheservertoincludebuildingblocksoftheerrormessage,andtosubstitutethevalueofcertainenvironmentvariablesintothegenerateddocument(dynamicHTML)oreventoconditionallyincludeoromitpartsofthetext.

4. TheAddHandlerandAddTypedirectivesareusefulforautomaticallySSI-expandingallfileswitha.shtmlsuffixtotext/html.

5. ByusingtheAliasdirective,wekeeptheerrordocumentdirectoryoutsideofthedocumenttreebecauseitcanberegardedmoreasaserverpartthanpartofthedocumenttree.

6. The<Directory>blockrestrictsthese"special"settingstotheerrordocumentdirectoryandavoidsanimpactonanyofthesettingsfortheregulardocumenttree.

7. Foreachoftheerrorcodestobehandled(seeRFC2068foranexactdescriptionofeacherrorcode,orlookatsrc/main/http_protocol.cifyouwishtoseeapache'sstandardmessages),anErrorDocumentinthealiased/errordocsdirectoryisdefined.Notethatweonlydefine

thebasenameofthedocumentherebecausetheMultiViewsoptionwillselectthebestcandidatebasedonthelanguagesuffixesandtheclient'spreferences.Anyerrorsituationwithanerrorcodenothandledbyacustomdocumentwillbedealtwithbytheserverinthestandardway(i.e.,aplainerrormessageinenglish).

8. Finally,theAllowOverridedirectivetellsapachethatitisnotnecessarytolookfora.htaccessfileinthe/errordocsdirectory:aminorspeedoptimization.

Theresultinghttpd.confconfigurationwouldthenlooksimilartothis:

NoteNotethatyoucandefineyourownerrormessagesusingthismethodforonlypartofthedocumenttree,e.g.,a/~user/subtree.Inthiscase,theconfigurationcouldaswellbeputintothe.htaccessfileattherootofthesubtree,andthe<Directory>and</Directory>directives-butnotthecontaineddirectives-mustbeomitted.

LanguagePriorityenfrde

Alias/errordocs/usr/local/apache/errordocs

<Directory/usr/local/apache/errordocs>

AllowOverridenone

OptionsMultiViewsIncludesNoExecFollowSymLinks

AddTypetext/html.shtml

<FilesMatch"\.shtml[.$]">

SetOutputFilterINCLUDES

</FilesMatch>

</Directory>

#"400BadRequest",

ErrorDocument400/errordocs/400

#"401AuthorizationRequired",

ErrorDocument401/errordocs/401

#"403Forbidden",

ErrorDocument403/errordocs/403

#"404NotFound",

ErrorDocument404/errordocs/404

#"500InternalServerError",

ErrorDocument500/errordocs/500

Thedirectoryfortheerrormessages(here:/usr/local/apache/errordocs/)mustthenbecreatedwiththeappropriatepermissions(readableandexecutablebytheserveruidorgid,onlywritablefortheadministrator).

NamingtheIndividualErrorDocumentfilesBydefiningtheMultiViewsoption,theserverwastoldtoautomaticallyscanthedirectoryformatchingvariants(lookingatlanguageandcontenttypesuffixes)whenarequesteddocumentwasnotfound.Intheconfiguration,wedefinedthenamesfortheerrordocumentstobejusttheirerrornumber(withoutanysuffix).

Thenamesoftheindividualerrordocumentsarenowdeterminedlikethis(I'musing403asanexample,thinkofitasaplaceholderforanyoftheconfigurederrordocuments):

Nofileerrordocs/403shouldexist.Otherwise,itwouldbefoundandserved(withtheDefaultType,usuallytext/plain),allnegotiationwouldbebypassed.Foreachlanguageforwhichwehaveaninternationalizedversion(notethatthisneednotbethesamesetoflanguagesforeacherrorcode-youcangetbywithasinglelanguageversionuntilyouactuallyhavetranslatedversions),adocumenterrordocs/403.shtml.langiscreatedandfilledwiththeerrortextinthatlanguage(seebelow).Onefallbackdocumentcallederrordocs/403.shtmliscreated,usuallybycreatingasymlinktothedefaultlanguagevariant(seebelow).

TheCommonHeaderandFooterFiles

Byputtingasmuchlayoutinformationintwospecial"includefiles",theerrordocumentscanbereducedtoabareminimum.

OneoftheselayoutfilesdefinestheHTMLdocumentheaderandaconfigurablelistofpathstotheiconstobeshownintheresultingerrordocument.ThesepathsareexportedasasetofSSIenvironmentvariablesandarelaterevaluatedbythe"footer"specialfile.Thetitleofthecurrenterror(whichisputintotheTITLEtagandanH1header)issimplypassedinfromthemainerrordocumentinavariablecalledtitle.

Bychangingthisfile,thelayoutofallgeneratederrormessagescanbechangedinasecond.(ByexploitingthefeaturesofSSI,youcaneasilydefinedifferentlayoutsbasedonthecurrentvirtualhost,orevenbasedontheclient'sdomainname).

Thesecondlayoutfiledescribesthefootertobedisplayedatthebottomofeveryerrormessage.Inthisexample,itshowsanapachelogo,thecurrentservertime,theserverversionstringandaddsamailreferencetothesite'swebmaster.

Forsimplicity,theheaderfileissimplycalledhead.shtmlbecauseitcontainsserver-parsedcontentbutnolanguagespecificinformation.Thefooterfileexistsonceforeachlanguagetranslation,plusasymlinkforthedefaultlanguage.

forEnglish,FrenchandGermanversions(defaultenglish)

foot.shtml.en,

foot.shtml.fr,

foot.shtml.de,

foot.shtmlsymlinkto

foot.shtml.en

Bothfilesareincludedintotheerrordocumentbyusingthedirectives<!--#includevirtual="head"-->and<!--

#includevirtual="foot"-->respectively:therestofthemagicoccursinmod_negotiationandinmod_include.

SeethelistingsbelowtoseeanactualHTMLimplementationofthediscussedexample.

CreatingErrorDocumentsinDifferentLanguagesAfterallthispreparationwork,littleremainstobesaidabouttheactualdocuments.Theyallshareasimplecommonstructure:

<!--#setvar="title"value="errordescriptiontitle"-->

<!--#includevirtual="head"-->

explanatoryerrortext

<!--#includevirtual="foot"-->

Inthelistingssection,youcanseeanexampleofa[400BadRequest]errordocument.Documentsassimpleasthatcertainlycausenoproblemstotranslateorexpand.

TheFallbackLanguageDoweneedaspecialhandlingforlanguagesotherthanthosewehavetranslationsfor?WedidsettheLanguagePriority,didn'twe?!

Well,theLanguagePrioritydirectiveisforthecasewheretheclientdoesnotexpressanylanguagepriorityatall.Butwhathappensinthesituationwheretheclientwantsoneofthelanguageswedonothave,andnoneofthosewedohave?

Withoutdoinganything,theApacheserverwillusuallyreturna[406noacceptablevariant]error,listingthechoicesfromwhichtheclientmayselect.Butwe'reinanerrormessagealready,andimportanterrorinformationmightgetlostwhentheclienthadtochoosealanguagerepresentationfirst.

So,inthissituationitappearstobeeasiertodefineafallback

language(bycopyingorlinking,e.g.,theenglishversiontoalanguage-lessversion).Becausethenegotiationalgorithmprefers"morespecialized"variantsover"moregeneric"variants,thesegenericalternativeswillonlybechosenwhenthenormalnegotiationdidnotsucceed.

Asimpleshellscripttodoit(executewithintheerrordocs/dir):

forfin*.shtml.en

do

ln-s$f`basename$f.en`

done

CustomizingProxyErrorMessages

AsofApache-1.3,itispossibletousetheErrorDocumentmechanismforproxyerrormessagesaswell(previousversionsalwaysreturnedfixedpredefinederrormessages).

Mostproxyerrorsreturnanerrorcodeof[500InternalServerError].Tofindoutwhetheraparticularerrordocumentwasinvokedonbehalfofaproxyerrororbecauseofsomeotherservererror,andwhatthereasonforthefailurewas,youcancheckthecontentsofthenewERROR_NOTESCGIenvironmentvariable:ifinvokedforaproxyerror,thisvariablewillcontaintheactualproxyerrormessagetextinHTMLform.

ThefollowingexcerptdemonstrateshowtoexploittheERROR_NOTESvariablewithinanerrordocument:

<!--#ifexpr="$REDIRECT_ERROR_NOTES=''"-->

<p>

Theserverencounteredanunexpectedcondition

whichpreventeditfromfulfillingtherequest.

</p>

<p>

<ahref="mailto:<!--#echovar="SERVER_ADMIN"-->"

SUBJECT="Errormessage[<!--#echovar="REDIRECT_STATUS"-->]

<!--#echovar="title"-->for<!--#echovar="REQUEST_URI"--

>">

Pleaseforwardthiserrorscreento<!--#echo

var="SERVER_NAME"-->'s

WebMaster</a>;itincludesusefuldebugginginformation

about

theRequestwhichcausedtheerror.

<pre><!--#printenv--></pre>

</p>

<!--#else-->

<!--#echovar="REDIRECT_ERROR_NOTES"-->

<!--#endif-->

HTMLListingoftheDiscussedExample

So,tosummarizeourexample,here'sthecompletelistingofthe400.shtml.endocument.Youwillnoticethatitcontainsalmostnothingbuttheerrortext(withconditionaladditions).Startingwiththisexample,youwillfinditeasytoaddmoreerrordocuments,ortotranslatetheerrordocumentstodifferentlanguages.

<!--#setvar="title"value="BadRequest"-->

<!--#includevirtual="head"-->

<p>

Yourbrowsersentarequestthatthisservercouldnot

understand:

<blockquote>

<strong><!--#echovar="REQUEST_URI"--></strong>

</blockquote>

Therequestcouldnotbeunderstoodbytheserverdueto

malformed

syntax.Theclientshouldnotrepeattherequestwithout

modifications.

</p>

<p>

<!--#ifexpr="$HTTP_REFERER!=''"-->

Pleaseinformtheownerof

<ahref="<!--#echovar="HTTP_REFERER"-->">thereferring

page</a>about

themalformedlink.

<!--#else-->

Pleasecheckyourrequestfortypingerrorsandretry.

<!--#endif-->

</p>

<!--#includevirtual="foot"-->

Hereisthecompletehead.shtml.enfile(thefunnylinebreaksavoidemptylinesinthedocumentafterSSIprocessing).Notetheconfigurationsectionattop.That'swhereyouconfiguretheimagesandlogosaswellastheapachedocumentationdirectory.Lookhowthisfiledisplaystwodifferentlogosdependingonthe

contentofthevirtualhostname($SERVER_NAME),andthatananimatedapachelogoisshownifthebrowserappearstosupportit(thelatterrequiresserverconfigurationlinesoftheform

BrowserMatch"^Mozilla/[2-4]"anigif

forbrowsertypeswhichsupportanimatedGIFs).

<!--#ifexpr="$SERVER_NAME=/.*\.mycompany\.com/"-->

<!--#setvar="IMG_CorpLogo"

value="http://$SERVER_NAME:$SERVER_PORT/errordocs/CorpLogo.gif"

-->

<!--#setvar="ALT_CorpLogo"value="PoweredbyLinux!"-->

<!--#else-->

<!--#setvar="IMG_CorpLogo"

value="http://$SERVER_NAME:$SERVER_PORT/errordocs/PrivLogo.gif"

-->

<!--#setvar="ALT_CorpLogo"value="PoweredbyLinux!"-->

<!--#endif-->

<!--#setvar="IMG_BgImage"

value="http://$SERVER_NAME:$SERVER_PORT/errordocs/BgImage.gif"

-->

<!--#setvar="DOC_Apache"

value="http://$SERVER_NAME:$SERVER_PORT/Apache/"-->

<!--#ifexpr="$anigif"-->

<!--#setvar="IMG_Apache"

value="http://$SERVER_NAME:$SERVER_PORT/icons/apache_anim.gif"

-->

<!--#else-->

<!--#setvar="IMG_Apache"

value="http://$SERVER_NAME:$SERVER_PORT/icons/apache_pb.gif"

-->

<!--#endif-->

<!DOCTYPEHTMLPUBLIC"-//IETF//DTDHTML//EN">

<html>

<head>

<title>

[<!--#echovar="REDIRECT_STATUS"-->]<!--#echovar="title"

-->

</title>

</head>

<bodybgcolor="white"background="<!--#echovar="IMG_BgImage"-

->">

<h1align="center">

[<!--#echovar="REDIRECT_STATUS"-->]<!--#echovar="title"

-->

<imgsrc="<!--#echovar="IMG_CorpLogo"-->"

alt="<!--#echovar="ALT_CorpLogo"-->"align="right">

</h1>

<hr/><!--

========================================================-->

<div>

andthisisthefoot.shtml.enfile:

</div>

<hr/>

<divalign="right">

<small>LocalServertime:<!--#echovar="DATE_LOCAL"-->

</small>

</div>

<divalign="center">

<ahref="<!--#echovar="DOC_Apache"-->">

<imgsrc="<!--#echovar="IMG_Apache"-->"border="0"

align="bottom"

alt="Poweredby<!--#echovar="SERVER_SOFTWARE"-->">

</a>

<br/>

<small><!--#setvar="var"value="Poweredby

$SERVER_SOFTWARE--

Filelastmodifiedon$LAST_MODIFIED"-->

<!--#echovar="var"--></small>

</div>

<p>Iftheindicatederrorlookslikeamisconfiguration,

pleaseinform

<ahref="mailto:<!--#echovar="SERVER_ADMIN"-->"

subject="FeedbackaboutErrormessage[<!--#echo

var="REDIRECT_STATUS"-->]

<!--#echovar="title"-->,req=<!--#echovar="REQUEST_URI"-

->">

<!--#echovar="SERVER_NAME"-->'sWebMaster</a>.

</p>

</body>

</html>

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Ifyouhavetipstocontribute,sendmailtomartin@apache.org

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>MiscellaneousDocumentation

ConnectionsintheFIN_WAIT_2stateandApache

Warning:

Thisdocumenthasnotbeenfullyupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

StartingwiththeApache1.2betas,peoplearereportingmanymoreconnectionsintheFIN_WAIT_2state(asreportedbynetstat)thantheysawusingolderversions.WhentheserverclosesaTCPconnection,itsendsapacketwiththeFINbitsettotheclient,whichthenrespondswithapacketwiththeACKbitset.TheclientthensendsapacketwiththeFINbitsettotheserver,whichrespondswithanACKandtheconnectionisclosed.ThestatethattheconnectionisinduringtheperiodbetweenwhentheservergetstheACKfromtheclientandtheservergetstheFINfromtheclientisknownasFIN_WAIT_2.SeetheTCPRFCforthetechnicaldetailsofthestatetransitions.

TheFIN_WAIT_2stateissomewhatunusualinthatthereisnotimeoutdefinedinthestandardforit.Thismeansthatonmanyoperatingsystems,aconnectionintheFIN_WAIT_2statewillstayarounduntilthesystemisrebooted.IfthesystemdoesnothaveatimeoutandtoomanyFIN_WAIT_2connectionsbuildup,itcanfillupthespaceallocatedforstoringinformationabouttheconnectionsandcrashthekernel.TheconnectionsinFIN_WAIT_2donottieupanhttpdprocess.

WhyDoesItHappen?

Therearenumerousreasonsforithappening,someofthemmaynotyetbefullyclear.Whatisknownfollows.

BuggyClientsandPersistentConnectionsSeveralclientshaveabugwhichpopsupwhendealingwithpersistentconnections(akakeepalives).Whentheconnectionisidleandtheserverclosestheconnection(basedontheKeepAliveTimeout),theclientisprogrammedsothattheclientdoesnotsendbackaFINandACKtotheserver.ThismeansthattheconnectionstaysintheFIN_WAIT_2stateuntiloneofthefollowinghappens:

Theclientopensanewconnectiontothesameoradifferentsite,whichcausesittofullyclosetheolderconnectiononthatsocket.Theuserexitstheclient,whichonsome(most?)clientscausestheOStofullyshutdowntheconnection.TheFIN_WAIT_2timesout,onserversthathaveatimeoutforthisstate.

Ifyouarelucky,thismeansthatthebuggyclientwillfullyclosetheconnectionandreleasetheresourcesonyourserver.However,therearesomecaseswherethesocketisneverfullyclosed,suchasadialupclientdisconnectingfromtheirproviderbeforeclosingtheclient.Inaddition,aclientmightsitidlefordayswithoutmakinganotherconnection,andthusmayholditsendofthesocketopenfordayseventhoughithasnofurtheruseforit.Thisisabuginthebrowserorinitsoperatingsystem'sTCPimplementation.

Theclientsonwhichthisproblemhasbeenverifiedtoexist:

Mozilla/3.01(X11;I;FreeBSD2.1.5-RELEASEi386)Mozilla/2.02(X11;I;FreeBSD2.1.5-RELEASEi386)Mozilla/3.01Gold(X11;I;SunOS5.5sun4m)

MSIE3.01ontheMacintoshMSIE3.01onWindows95

Thisdoesnotappeartobeaproblemon:

Mozilla/3.01(Win95;I)

Itisexpectedthatmanyotherclientshavethesameproblem.Whataclientshoulddoisperiodicallycheckitsopensocket(s)toseeiftheyhavebeenclosedbytheserver,andclosetheirsideoftheconnectioniftheserverhasclosed.Thischeckneedonlyoccuronceeveryfewseconds,andmayevenbedetectedbyaOSsignalonsomesystems(e.g.,Win95andNTclientshavethiscapability,buttheyseemtobeignoringit).

ApachecannotavoidtheseFIN_WAIT_2statesunlessitdisablespersistentconnectionsforthebuggyclients,justlikewerecommenddoingforNavigator2.xclientsduetootherbugs.However,non-persistentconnectionsincreasethetotalnumberofconnectionsneededperclientandslowretrievalofanimage-ladenwebpage.Sincenon-persistentconnectionshavetheirownresourceconsumptionsandashortwaitingperiodaftereachclosure,abusyservermayneedpersistenceinordertobestserveitsclients.

Asfarasweknow,theclient-causedFIN_WAIT_2problemispresentforallserversthatsupportpersistentconnections,includingApache1.1.xand1.2.

Anecessarybitofcodeintroducedin1.2Whiletheabovebugisaproblem,itisnotthewholeproblem.SomeusershaveobservednoFIN_WAIT_2problemswithApache1.1.x,butwith1.2benoughconnectionsbuildupintheFIN_WAIT_2statetocrashtheirserver.ThemostlikelysourceforadditionalFIN_WAIT_2statesisafunctioncalled

lingering_close()whichwasaddedbetween1.1and1.2.Thisfunctionisnecessaryfortheproperhandlingofpersistentconnectionsandanyrequestwhichincludescontentinthemessagebody(e.g.,PUTsandPOSTs).Whatitdoesisreadanydatasentbytheclientforacertaintimeaftertheserverclosestheconnection.Theexactreasonsfordoingthisaresomewhatcomplicated,butinvolvewhathappensiftheclientismakingarequestatthesametimetheserversendsaresponseandclosestheconnection.Withoutlingering,theclientmightbeforcedtoresetitsTCPinputbufferbeforeithasachancetoreadtheserver'sresponse,andthusunderstandwhytheconnectionhasclosed.Seetheappendixformoredetails.

Thecodeinlingering_close()appearstocauseproblemsforanumberoffactors,includingthechangeintrafficpatternsthatitcauses.Thecodehasbeenthoroughlyreviewedandwearenotawareofanybugsinit.ItispossiblethatthereissomeproblemintheBSDTCPstack,asidefromthelackofatimeoutfortheFIN_WAIT_2state,exposedbythelingering_closecodethatcausestheobservedproblems.

WhatCanIDoAboutit?

Thereareseveralpossibleworkaroundstotheproblem,someofwhichworkbetterthanothers.

AddatimeoutforFIN_WAIT_2TheobviousworkaroundistosimplyhaveatimeoutfortheFIN_WAIT_2state.ThisisnotspecifiedbytheRFC,andcouldbeclaimedtobeaviolationoftheRFC,butitiswidelyrecognizedasbeingnecessary.Thefollowingsystemsareknowntohaveatimeout:

FreeBSDversionsstartingat2.0orpossiblyearlier.NetBSDversion1.2(?)OpenBSDallversions(?)BSD/OS2.1,withtheK210-027patchinstalled.Solarisasofaroundversion2.2.Thetimeoutcanbetunedbyusingnddtomodifytcp_fin_wait_2_flush_interval,butthedefaultshouldbeappropriateformostserversandimpropertuningcanhavenegativeimpacts.Linux2.0.xandearlier(?)HP-UX10.xdefaultstoterminatingconnectionsintheFIN_WAIT_2stateafterthenormalkeepalivetimeouts.ThisdoesnotrefertothepersistentconnectionorHTTPkeepalivetimeouts,buttheSO_LINGERsocketoptionwhichisenabledbyApache.Thisparametercanbeadjustedbyusingnettunetomodifyparameterssuchastcp_keepstartandtcp_keepstop.Inlaterrevisions,thereisanexplicittimerforconnectionsinFIN_WAIT_2thatcanbemodified;contactHPsupportfordetails.SGIIRIXcanbepatchedtosupportatimeout.ForIRIX5.3,6.2,and6.3,usepatches1654,1703and1778respectively.Ifyouhavetroublelocatingthesepatches,pleasecontactyourSGIsupportchannelforhelp.NCR'sMPRASUnix2.xxand3.xxbothhaveFIN_WAIT_2

timeouts.In2.xxitisnon-tunableat600seconds,whilein3.xxitdefaultsto600secondsandiscalculatedbasedonthetunable"maxkeepaliveprobes"(defaultof8)multipliedbythe"keepaliveinterval"(default75seconds).Sequent'sptx/TCP/IPforDYNIX/ptxhashadaFIN_WAIT_2timeoutsincearoundrelease4.1inmid-1994.

Thefollowingsystemsareknowntonothaveatimeout:

SunOS4.xdoesnotandalmostcertainlyneverwillhaveonebecauseitasattheveryendofitsdevelopmentcycleforSun.Ifyouhavekernelsourceshouldbeeasytopatch.

ThereisapatchavailableforaddingatimeouttotheFIN_WAIT_2state;itwasoriginallyintendedforBSD/OS,butshouldbeadaptabletomostsystemsusingBSDnetworkingcode.Youneedkernelsourcecodetobeabletouseit.

Compilewithoutusinglingering_close()ItispossibletocompileApache1.2withoutusingthelingering_close()function.Thiswillresultinthatsectionofcodebeingsimilartothatwhichwasin1.1.Ifyoudothis,beawarethatitcancauseproblemswithPUTs,POSTsandpersistentconnections,especiallyiftheclientusespipelining.Thatsaid,itisnoworsethanon1.1,andweunderstandthatkeepingyourserverrunningisquiteimportant.

Tocompilewithoutthelingering_close()function,add-DNO_LINGCLOSEtotheendoftheEXTRA_CFLAGSlineinyourConfigurationfile,rerunConfigureandrebuildtheserver.

UseSO_LINGERasanalternativetolingering_close()

Onmostsystems,thereisanoptioncalledSO_LINGERthatcanbesetwithsetsockopt(2).Itdoessomethingverysimilartolingering_close(),exceptthatitisbrokenonmanysystemssothatitcausesfarmoreproblemsthanlingering_close.Onsomesystems,itcouldpossiblyworkbettersoitmaybeworthatryifyouhavenootheralternatives.

Totryit,add-DUSE_SO_LINGER-DNO_LINGCLOSEtotheendoftheEXTRA_CFLAGSlineinyourConfigurationfile,rerunConfigureandrebuildtheserver.

NOTEAttemptingtouseSO_LINGERandlingering_close()atthesametimeisverylikelytodoverybadthings,sodon't.

IncreasetheamountofmemoryusedforstoringconnectionstateBSDbasednetworkingcode:

BSDstoresnetworkdata,suchasconnectionstates,insomethingcalledanmbuf.Whenyougetsomanyconnectionsthatthekerneldoesnothaveenoughmbufstoputthemallin,yourkernelwilllikelycrash.Youcanreducetheeffectsoftheproblembyincreasingthenumberofmbufsthatareavailable;thiswillnotpreventtheproblem,itwilljustmaketheservergolongerbeforecrashing.TheexactwaytoincreasethemmaydependonyourOS;lookforsomereferencetothenumberof"mbufs"or"mbufclusters".Onmanysystems,thiscanbedonebyaddingthelineNMBCLUSTERS="n",wherenisthenumberofmbufclustersyouwanttoyourkernelconfigfileandrebuildingyourkernel.

DisableKeepAliveIfyouareunabletodoanyoftheabovethenyoushould,asalastresort,disableKeepAlive.Edityourhttpd.confandchange"KeepAliveOn"to"KeepAliveOff".

Appendix

BelowisamessagefromRoyFielding,oneoftheauthorsofHTTP/1.1.

WhythelingeringclosefunctionalityisnecessarywithHTTPTheneedforaservertolingeronasocketafteracloseisnotedacoupletimesintheHTTPspecs,butnotexplained.Thisexplanationisbasedondiscussionsbetweenmyself,HenrikFrystyk,RobertS.Thau,DaveRaggett,andJohnC.MalleryinthehallwaysofMITwhileIwasatW3C.

Ifaserverclosestheinputsideoftheconnectionwhiletheclientissendingdata(orisplanningtosenddata),thentheserver'sTCPstackwillsignalanRST(reset)backtotheclient.UponreceiptoftheRST,theclientwillflushitsownincomingTCPbufferbacktotheun-ACKedpacketindicatedbytheRSTpacketargument.Iftheserverhassentamessage,usuallyanerrorresponse,totheclientjustbeforetheclose,andtheclientreceivestheRSTpacketbeforeitsapplicationcodehasreadtheerrormessagefromitsincomingTCPbufferandbeforetheserverhasreceivedtheACKsentbytheclientuponreceiptofthatbuffer,thentheRSTwillflushtheerrormessagebeforetheclientapplicationhasachancetoseeit.Theresultisthattheclientisleftthinkingthattheconnectionfailedfornoapparentreason.

Therearetwoconditionsunderwhichthisislikelytooccur:

1. sendingPOSTorPUTdatawithoutproperauthorization

2. sendingmultiplerequestsbeforeeachresponse(pipelining)andoneofthemiddlerequestsresultinginanerrororotherbreak-the-connectionresult.

Thesolutioninallcasesistosendtheresponse,closeonlythe

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

writehalfoftheconnection(whatshutdownissupposedtodo),andcontinuereadingonthesocketuntilitiseitherclosedbytheclient(signifyingithasfinallyreadtheresponse)oratimeoutoccurs.ThatiswhatthekernelissupposedtodoifSO_LINGERisset.Unfortunately,SO_LINGERhasnoeffectonsomesystems;onsomeothersystems,itdoesnothaveitsowntimeoutandthustheTCPmemorysegmentsjustpile-upuntilthenextreboot(plannedornot).

Pleasenotethatsimplyremovingthelingercodewillnotsolvetheproblem--itonlymovesittoadifferentandmuchharderonetodetect.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>MiscellaneousDocumentation

KnownProblemsinClients

Warning:

Thisdocumenthasnotbeenfullyupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

OvertimetheApacheGrouphasdiscoveredorbeennotifiedofproblemswithvariousclientswhichwehavehadtoworkaround,orexplain.Thisdocumentdescribestheseproblemsandtheworkaroundsavailable.It'snotarrangedinanyparticularorder.Somefamiliaritywiththestandardsisassumed,butnotnecessary.

Forbrevity,NavigatorwillrefertoNetscape'sNavigatorproduct(whichinlaterversionswasrenamed"Communicator"andvariousothernames),andMSIEwillrefertoMicrosoft'sInternetExplorerproduct.Alltrademarksandcopyrightsbelongtotheirrespectivecompanies.Wewelcomeinputfromthevariousclientauthorstocorrectinconsistenciesinthispaper,ortoprovideuswithexactversionnumberswherethingsarebroken/fixed.

Forreference,RFC1945definesHTTP/1.0,andRFC2068definesHTTP/1.1.Apacheasofversion1.2isanHTTP/1.1server(withanoptionalHTTP/1.0proxy).

Variousoftheseworkaroundsaretriggeredbyenvironmentvariables.Theadmintypicallycontrolswhichareset,andforwhichclients,byusingmod_browser.Unlessotherwisenotedalloftheseworkaroundsexistinversions1.2andlater.

TrailingCRLFonPOSTs

Thisisalegacyissue.TheCERNwebserverrequiredPOSTdatatohaveanextraCRLFfollowingit.ThusmanyclientssendanextraCRLFthatisnotincludedintheContent-Lengthoftherequest.Apacheworksaroundthisproblembyeatinganyemptylineswhichappearbeforearequest.

BrokenKeepAlive

Variousclientshavehadbrokenimplementationsofkeepalive(persistentconnections).InparticulartheWindowsversionsofNavigator2.0getveryconfusedwhentheservertimesoutanidleconnection.Theworkaroundispresentinthedefaultconfigfiles:

BrowserMatchMozilla/2nokeepalive

NotethatthismatchessomeearlierversionsofMSIE,whichbeganthepracticeofcallingthemselvesMozillaintheiruser-agentstringsjustlikeNavigator.

MSIE4.0b2,whichclaimstosupportHTTP/1.1,doesnotproperlysupportkeepalivewhenitisusedon301or302(redirect)responses.UnfortunatelyApache'snokeepalivecodepriorto1.2.2wouldnotworkwithHTTP/1.1clients.Youmustapplythispatchtoversion1.2.1.Thenaddthistoyourconfig:

BrowserMatch"MSIE4\.0b2;"nokeepalive

IncorrectinterpretationofHTTP/1.1inresponse

Toquotefromsection3.1ofRFC1945:

HTTPusesa"<MAJOR>.<MINOR>"numberingschemetoindicateversionsoftheprotocol.TheprotocolversioningpolicyisintendedtoallowthesendertoindicatetheformatofamessageanditscapacityforunderstandingfurtherHTTPcommunication,ratherthanthefeaturesobtainedviathatcommunication.

SinceApacheisanHTTP/1.1server,itindicatessoaspartofitsresponse.Manyclientauthorsmistakenlytreatthispartoftheresponseasanindicationoftheprotocolthattheresponseisin,andthenrefusetoaccepttheresponse.

ThefirstmajorindicationofthisproblemwaswithAOL'sproxyservers.WhenApache1.2wentintobetaitwasthefirstwide-spreadHTTP/1.1server.Aftersomediscussion,AOLfixedtheirproxies.Inanticipationofsimilarproblems,theforce-response-1.0environmentvariablewasaddedtoApache.WhenpresentApachewillindicate"HTTP/1.0"inresponsetoanHTTP/1.0client,butwillnotinanyotherwaychangetheresponse.

Thepre-1.1JavaDevelopmentKit(JDK)thatisusedinmanyclients(includingNavigator3.xandMSIE3.x)exhibitsthisproblem.Asdosomeoftheearlypre-releasesofthe1.1JDK.Wethinkitisfixedinthe1.1JDKrelease.Inanyeventtheworkaround:

BrowserMatchJava/1.0force-response-1.0

BrowserMatchJDK/1.0force-response-1.0

RealPlayer4.0fromProgressiveNetworksalsoexhibitsthisproblem.Howevertheyhavefixeditinversion4.01oftheplayer,

butversion4.01usesthesameUser-Agentasversion4.0.Theworkaroundisstill:

BrowserMatch"RealPlayer4.0"force-response-1.0

RequestsuseHTTP/1.1butresponsesmustbeinHTTP/1.0

MSIE4.0b2hasthisproblem.ItsJavaVMmakesrequestsinHTTP/1.1formatbuttheresponsesmustbeinHTTP/1.0format(inparticular,itdoesnotunderstandchunkedresponses).TheworkaroundistofoolApacheintobelievingtherequestcameinHTTP/1.0format.

BrowserMatch"MSIE4\.0b2;"downgrade-1.0force-response-1.0

Thisworkaroundisavailablein1.2.2,andinapatchagainst1.2.1.

Boundaryproblemswithheaderparsing

AllversionsofNavigatorfrom2.0through4.0b2(andpossiblylater)haveaproblemifthetrailingCRLFoftheresponseheaderstartsatoffset256,257or258oftheresponse.ABrowserMatchforthiswouldmatchonnearlyeveryhit,sotheworkaroundisenabledautomaticallyonallresponses.TheworkaroundimplementeddetectswhenthisconditionwouldoccurinaresponseandaddsextrapaddingtotheheadertopushthetrailingCRLFpastoffset258oftheresponse.

MultipartresponsesandQuotedBoundaryStrings

Onmultipartresponsessomeclientswillnotacceptquotes(")aroundtheboundarystring.TheMIMEstandardrecommendsthatsuchquotesbeused.ButtheclientswereprobablywrittenbasedononeoftheexamplesinRFC2068,whichdoesnotincludequotes.Apachedoesnotincludequotesonitsboundarystringstoworkaroundthisproblem.

ByterangeRequests

Abyterangerequestisusedwhentheclientwishestoretrieveaportionofanobject,notnecessarilytheentireobject.TherewasaveryolddraftwhichincludedthesebyterangesintheURL.OldclientssuchasNavigator2.0b1andMSIE3.0fortheMACexhibitthisbehaviour,anditwillappearintheservers'accesslogsas(failed)attemptstoretrieveaURLwithatrailing";xxx-yyy".Apachedoesnotattempttoimplementthisatall.

AsubsequentdraftofthisstandarddefinesaheaderRequest-Range,andaresponsetypemultipart/x-byteranges.TheHTTP/1.1standardincludesthisdraftwithafewfixes,anditdefinestheheaderRangeandtypemultipart/byteranges.

Navigator(versions2and3)sendsbothRangeandRequest-Rangeheaders(withthesamevalue),butdoesnotacceptamultipart/byterangesresponse.Theresponsemustbemultipart/x-byteranges.Asaworkaround,ifApachereceivesaRequest-Rangeheaderitconsidersit"higherpriority"thanaRangeheaderandinresponseusesmultipart/x-byteranges.

TheAdobeAcrobatReaderpluginmakesextensiveuseofbyterangesandpriortoversion3.01supportsonlythemultipart/x-byterangeresponse.Unfortunatelythereisnocluethatitisthepluginmakingtherequest.IfthepluginisusedwithNavigator,theaboveworkaroundworksfine.ButifthepluginisusedwithMSIE3(onWindows)theworkaroundwon'tworkbecauseMSIE3doesn'tgivetheRange-RequestcluethatNavigatordoes.Toworkaroundthis,Apachespecialcases"MSIE3"intheUser-Agentandservesmultipart/x-byteranges.NotethatthenecessityforthiswithMSIE3isactuallyduetotheAcrobatplugin,notduetothebrowser.

NetscapeCommunicatorappearstonotissuethenon-standardRequest-Rangeheader.WhenanAcrobatpluginpriortoversion3.01isusedwithit,itwillnotproperlyunderstandbyteranges.TheusermustupgradetheirAcrobatreaderto3.01.

Set-Cookieheaderisunmergeable

TheHTTPspecificationssaythatitislegaltomergeheaderswithduplicatenamesintoone(separatedbycommas).SomebrowsersthatsupportCookiesdon'tlikemergedheadersandpreferthateachSet-Cookieheaderissentseparately.WhenparsingtheheadersreturnedbyaCGI,ApachewillexplicitlyavoidmerginganySet-Cookieheaders.

ExpiresheadersandGIF89Aanimations

Navigatorversions2through4willerroneouslyre-requestGIF89AanimationsoneachloopoftheanimationifthefirstresponseincludedanExpiresheader.Thishappensregardlessofhowfarinthefuturetheexpirytimeisset.ThereisnoworkaroundsuppliedwithApache,howevertherearehacksfor1.2andfor1.3.

POSTwithoutContent-Length

IncertainsituationsNavigator3.01through3.03appeartoincorrectlyissueaPOSTwithouttherequestbody.Thereisnoknownworkaround.IthasbeenfixedinNavigator3.04,Netscapesprovidessomeinformation.There'salsosomeinformationabouttheactualproblem.

JDK1.2betaslosepartsofresponses.

ThehttpclientintheJDK1.2beta2andbeta3willthrowawaythefirstpartoftheresponsebodywhenboththeheadersandthefirstpartofthebodyaresentinthesamenetworkpacketANDkeep-alive'sarebeingused.Ifeitherconditionisnotmetthenitworksfine.

SeealsoBug-ID's4124329and4125538atthejavadeveloperconnection.

Ifyouareseeingthisbugyourself,youcanaddthefollowingBrowserMatchdirectivetoworkaroundit:

BrowserMatch"Java1\.2beta[23]"nokeepalive

Wedon'tadvocatethisthoughsincebendingoverbackwardsforbetasoftwareisusuallynotagoodidea;ideallyitgetsfixed,newbetasorafinalreleasecomesout,andnooneusesthebrokenoldsoftwareanymore.Intheory.

Content-Typechangeisnotnoticedafterreload

Navigator(allversions?)willcachethecontent-typeforanobject"forever".Usingreloadorshift-reloadwillnotcauseNavigatortonoticeacontent-typechange.Theonlywork-aroundisfortheusertoflushtheircaches(memoryanddisk).Bywayofanexample,somefolksmaybeusinganoldmime.typesfilewhichdoesnotmap.htmtotext/html,inthiscaseApachewilldefaulttosendingtext/plain.Iftheuserrequeststhepageanditisservedastext/plain.Aftertheadminfixestheserver,theuserwillhavetoflushtheircachesbeforetheobjectwillbeshownwiththecorrecttext/htmltype.

MSIECookieproblemwithexpirydateintheyear2000

MSIEversions3.00and3.02(withouttheY2Kpatch)donothandlecookieexpirydatesintheyear2000properly.Yearsafter2000andbefore2000workfine.ThisisfixedinIE4.01servicepack1,andintheY2KpatchforIE3.02.Usersshouldavoidusingexpirydatesintheyear2000.

Lynxincorrectlyaskingfortransparentcontentnegotiation

TheLynxbrowserversions2.7and2.8senda"negotiate:trans"headerintheirrequests,whichisanindicationthebrowsersupportstransparentcontentnegotiation(TCN).HoweverthebrowserdoesnotsupportTCN.Asofversion1.3.4,ApachesupportsTCN,andthiscausesproblemswiththeseversionsofLynx.AsaworkaroundfutureversionsofApachewillignorethisheaderwhensentbytheLynxclient.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

MSIE4.0mishandlesVaryresponseheader

MSIE4.0doesnothandleaVaryheaderproperly.TheVaryheaderisgeneratedbymod_rewriteinapache1.3.TheresultisanerrorfromMSIEsayingitcannotdownloadtherequestedfile.TherearemoredetailsinPR#4118.

Aworkaroundistoaddthefollowingtoyourserver'sconfigurationfiles:

BrowserMatch"MSIE4\.0"force-no-vary

(Thisworkaroundisonlyavailablewithreleasesafter1.3.6oftheApacheWebserver.)

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>MiscellaneousDocumentation

DescriptorsandApache

Warning:

Thisdocumenthasnotbeenfullyupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

Adescriptor,alsocommonlycalledafilehandleisanobjectthataprogramusestoreadorwriteanopenfile,oropennetworksocket,oravarietyofotherdevices.Itisrepresentedbyaninteger,andyoumaybefamiliarwithstdin,stdout,andstderrwhicharedescriptors0,1,and2respectively.Apacheneedsadescriptorforeachlogfile,plusoneforeachnetworksocketthatitlistenson,plusahandfulofothers.LibrariesthatApacheusesmayalsorequiredescriptors.Normalprogramsdon'topenupmanydescriptorsatall,andsotherearesomelatentproblemsthatyoumayexperienceshouldyoustartrunningApachewithmanydescriptors(i.e.,withmanyvirtualhosts).

Theoperatingsystemenforcesalimitonthenumberofdescriptorsthataprogramcanhaveopenatatime.Therearetypicallythreelimitsinvolvedhere.Oneisakernellimitation,dependingonyouroperatingsystemyouwilleitherbeabletotunethenumberofdescriptorsavailabletohighernumbers(thisisfrequentlycalledFD_SETSIZE).Oryoumaybestuckwitha(relatively)lowamount.Thesecondlimitiscalledthehardresourcelimit,anditissometimessetbyrootinanobscureoperatingsystemfile,butfrequentlyisthesameasthekernellimit.Thethirdlimitiscalledthesoftresourcelimit.Thesoftlimitisalwayslessthanorequaltothehardlimit.Forexample,thehardlimitmaybe1024,butthesoftlimitonly64.Anyusercanraisetheirsoftlimituptothehardlimit.Rootcanraisethehardlimituptothesystemmaximumlimit.Thesoftlimitistheactual

limitthatisusedwhenenforcingthemaximumnumberoffilesaprocesscanhaveopen.

Tosummarize:

#openfiles<=softlimit<=hardlimit<=kernellimit

Youcontrolthehardandsoftlimitsusingthelimit(csh)orulimit(sh)directives.Seetherespectivemanpagesformoreinformation.Forexampleyoucanprobablyuseulimit-nunlimitedtoraiseyoursoftlimituptothehardlimit.Youshouldincludethiscommandinashellscriptwhichstartsyourwebserver.

Unfortunately,it'snotalwaysthissimple.Asmentionedabove,youwillprobablyrunintosomesystemlimitationsthatwillneedtobeworkedaroundsomehow.Workwasdoneinversion1.2.1toimprovethesituationsomewhat.Hereisapartiallistofsystemsandworkarounds(assumingyouareusing1.2.1orlater).

BSDI2.0

UnderBSDI2.0youcanbuildApachetosupportmoredescriptorsbyadding-DFD_SETSIZE=nnntoEXTRA_CFLAGS(wherennnisthenumberofdescriptorsyouwishtosupport,keepitlessthanthehardlimit).Butitwillrunintotroubleifmorethanapproximately240Listendirectivesareused.ThismaybecuredbyrebuildingyourkernelwithahigherFD_SETSIZE.

FreeBSD2.2,BSDI2.1+

SimilartotheBSDI2.0case,youshoulddefineFD_SETSIZEandrebuild.ButtheextraListenlimitationdoesn'texist.

Linux

BydefaultLinuxhasakernelmaximumof256opendescriptorsperprocess.Thereareseveralpatchesavailableforthe2.0.xserieswhichraisethisto1024andbeyond,andyoucanfindtheminthe"unofficialpatches"sectionoftheLinuxInformationHQ.Noneofthesepatchesareperfect,andanentirelydifferentapproachislikelytobetakenduringthe2.1.xdevelopment.ApplyingthesepatcheswillraisetheFD_SETSIZEusedtocompileallprograms,andunlessyourebuildallyourlibrariesyoushouldavoidrunninganyotherprogramwithasoftdescriptorlimitabove256.Asofthiswritingthepatchesavailableforincreasingthenumberofdescriptorsdonottakethisintoaccount.Onadedicatedwebserveryouprobablywon'trunintotrouble.

Solaristhrough2.5.1

Solarishasakernelhardlimitof1024(maybelowerinearlierversions).Butithasalimitationthatfilesusingthestdiolibrarycannothaveadescriptorabove255.ApacheusesthestdiolibraryfortheErrorLogdirective.Whenyouhavemorethanapproximately110virtualhosts(withanerrorlogandanaccesslogeach)youwillneedtobuildApachewith-DHIGH_SLACK_LINE=256addedtoEXTRA_CFLAGS.Youwillbelimitedtoapproximately240errorlogsifyoudothis.

AIX

AIXversion3.2??appearstohaveahardlimitof128descriptors.Endofstory.Version4.1.5hasahardlimitof2000.

SCOOpenServer

Editthe/etc/conf/cf.d/stunefileoruse/etc/conf/cf.d/configurechoice7(UserandGroupconfiguration)andmodifytheNOFILESkernelparametertoasuitablyhighervalue.SCOrecommendsanumberbetween60and11000,thedefaultis110.Relinkandreboot,andthenewnumberofdescriptorswillbeavailable.

CompaqTru64UNIX/DigitalUNIX/OSF

1. Raiseopen_max_softandopen_max_hardto4096intheprocsubsystem.Doamanonsysconfig,sysconfigdb,andsysconfigtab.

2. Raisemax-vnodestoalargenumberwhichisgreaterthanthenumberofapacheprocesses*4096(Settingitto250,000shouldbegoodformostpeople).Doamanonsysconfig,sysconfigdb,andsysconfigtab.

3. IfyouareusingTru645.0,5.0A,or5.1,defineNO_SLACKtoworkaroundabugintheOS.CFLAGS="-DNO_SLACK"./configure

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Others

Ifyouhavedetailsonanotheroperatingsystem,pleasesubmititthroughourBugReportPage.

InadditiontotheproblemsdescribedabovethereareproblemswithmanylibrariesthatApacheuses.ThemostcommonexampleisthebindDNSresolverlibrarythatisusedbyprettymucheveryunix,whichfailsifitendsupwithadescriptorabove256.Wesuspectthereareotherlibrariesthatsimilarlimitations.Sothecodeasof1.2.1takesadefensivestanceandtriestosavedescriptorslessthan16forusewhileprocessingeachrequest.Thisiscalledthelowslackline.

Notethatthisshouldn'twastedescriptors.IfyoureallyarepushingthelimitsandApachecan'tgetadescriptorabove16whenitwantsit,itwillsettleforonebelow16.

Inextremesituationsyoumaywanttolowerthelowslackline,butyoushouldn'teverneedto.Forexample,loweringitcanincreasethelimits240describedaboveunderSolarisandBSDI2.0.Butyou'llplayadelicatebalancinggamewiththedescriptorsneededtoservearequest.Shouldyouwanttoplaythisgame,thecompiletimeparameterisLOW_SLACK_LINEandthere'satinybitofdocumentationintheheaderfilehttpd.h.

Finally,ifyoususpectthatallthisslackstuffiscausingyouproblems,youcandisableit.Add-DNO_SLACKtoEXTRA_CFLAGSandrebuild.ButpleasereportittoourBugReportPagesothatwecaninvestigate.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>MiscellaneousDocumentation

RelevantStandards

ThispagedocumentsalltherelevantstandardsthattheApacheHTTPServerfollows,alongwithbriefdescriptions.

Inadditiontotheinformationlistedbelow,thefollowingresourcesshouldbeconsulted:

http://purl.org/NET/http-errata-HTTP/1.1SpecificationErratahttp://www.rfc-editor.org/errata.html-RFCErratahttp://ftp.ics.uci.edu/pub/ietf/http/#RFC-Apre-compiledlistofHTTPrelatedRFCs

Notice

Thisdocumentisnotyetcomplete.

HTTPRecommendations

Regardlessofwhatmodulesarecompiledandused,ApacheasabasicwebservercomplieswiththefollowingIETFrecommendations:

RFC1945(Informational)TheHypertextTransferProtocol(HTTP)isanapplication-levelprotocolwiththelightnessandspeednecessaryfordistributed,collaborative,hypermediainformationsystems.ThisdocumentsHTTP/1.0.

RFC2616(StandardsTrack)TheHypertextTransferProtocol(HTTP)isanapplication-levelprotocolfordistributed,collaborative,hypermediainformationsystems.ThisdocumentsHTTP/1.1.

RFC2396(StandardsTrack)AUniformResourceIdentifier(URI)isacompactstringofcharactersforidentifyinganabstractorphysicalresource.

HTMLRecommendations

RegardingtheHypertextMarkupLanguage,ApachecomplieswiththefollowingIETFandW3Crecommendations:

RFC2854(Informational)ThisdocumentsummarizesthehistoryofHTMLdevelopment,anddefinesthe"text/html"MIMEtypebypointingtotherelevantW3Crecommendations.

HTML4.01Specification(Errata)ThisspecificationdefinestheHyperTextMarkupLanguage(HTML),thepublishinglanguageoftheWorldWideWeb.ThisspecificationdefinesHTML4.01,whichisasubversionofHTML4.

HTML3.2ReferenceSpecificationTheHyperTextMarkupLanguage(HTML)isasimplemarkuplanguageusedtocreatehypertextdocumentsthatareportablefromoneplatformtoanother.HTMLdocumentsareSGMLdocuments.

XHTML1.1-Module-basedXHTML(Errata)ThisRecommendationdefinesanewXHTMLdocumenttypethatisbaseduponthemoduleframeworkandmodulesdefinedinModularizationofXHTML.

XHTML1.0TheExtensibleHyperTextMarkupLanguage(SecondEdition)(Errata)

ThisspecificationdefinestheSecondEditionofXHTML1.0,areformulationofHTML4asanXML1.0application,andthreeDTDscorrespondingtotheonesdefinedbyHTML4.

Authentication

Concerningthedifferentmethodsofauthentication,ApachefollowsthefollowingIETFrecommendations:

RFC2617(Draftstandard)"HTTP/1.0",includesthespecificationforaBasicAccessAuthenticationscheme.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Language/CountryCodes

ThefollowinglinksdocumentISOandotherlanguageandcountrycodeinformation:

ISO639-2ISO639providestwosetsoflanguagecodes,oneasatwo-lettercodeset(639-1)andanotherasathree-lettercodeset(thispartofISO639)fortherepresentationofnamesoflanguages.

ISO3166-1Thesepagesdocumentthecountrynames(officialshortnamesinEnglish)inalphabeticalorderasgiveninISO3166-1andthecorrespondingISO3166-1-alpha-2codeelements.

BCP47(BestCurrentPractice),RFC3066Thisdocumentdescribesalanguagetagforuseincaseswhereitisdesiredtoindicatethelanguageusedinaninformationobject,howtoregistervaluesforuseinthislanguagetag,andaconstructformatchingsuchlanguagetags.

RFC3282(StandardsTrack)Thisdocumentdefinesa"Content-language:"header,foruseincaseswhereonedesirestoindicatethelanguageofsomethingthathasRFC822-likeheaders,likeMIMEbodypartsorWebdocuments,andan"Accept-Language:"headerforuseincaseswhereonewishestoindicateone'spreferenceswithregardtolanguage.

Apache

Apache

Apache

MPM"MPM" ApacheMPM

Base"Base"

Extension"Extension"

Experimental"Experimental" Apache

External"External"Apache ("")

LoadModule module

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

Apache2

Apache

"..."

URLhttp://www.example.com/path/to/file.html() UniformResourceLocator

URL-path/path/to/file.html url

file-path/usr/local/apache/htdocs/path/to/file.html file-path ServerRoot

directory-path/usr/local/apache/htdocs/path/to/

filenamefile.html

regexPerl regex

extension filenameApache:) filenamefile.html.enApache extension

MIME-typetext/html

env-variableApache

( Apache

(httpd.conf,srm.conf,access.conf<VirtualHost> <Directory> .htaccess

<VirtualHost>

<Directory>,<Location>,<Files>Location,Files

.htaccess.htaccess

(:BoolenOR)httpd.conf .htaccess <Directory>

<VirtualHost>

.htaccess

AllowOverride ()

Apache

Core"Core"Apache

MPM"MPM"

Base"Base"

Extension"Extension"Apache

Experimental"Experimental"Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

Apache2

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apache

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: ApacheHTTP

: Core

AcceptPathInfo

:: AcceptPathInfoOn|Off|Default

: AcceptPathInfoDefault

: ,,,.htaccess: FileInfo: Core: core: Apache2.0.30

( )

/test/ here.html /test/nothere.html/more /more PATH_INFO

AcceptPathInfo :

Off

On

Default

PATH_INFO

AcceptPathInfo PATH_INFO PATH_INFO

<Files"mypaths.shtml">

Options+Includes

SetOutputFilterINCLUDES

AcceptPathInfoOn

</Files>

AccessFileName

:: AccessFileNamefilename[filename]...

: AccessFileName.htaccess

: ,: Core: core

AccessFileName.acl

/usr/local/web/index.html

/usr/.acl,/usr/local/.acl,/usr/local/web/.acl

<Directory/>

AllowOverrideNone

</Directory>

AllowOverride

.htaccess

AddDefaultCharset

: : AddDefaultCharsetOn|Off|charset

: AddDefaultCharsetOff

: ,,,.htaccess: FileInfo: Core: core

HTTP AddDefaultCharsetOn1 charset:

AddDefaultCharsetutf-8

AddOutputFilterByType

: MIME-type: AddOutputFilterByTypefilter[;filter...]

MIME-type[MIME-type]...

: ,,,.htaccess: FileInfo: Core: core: Apache2.0.33

MIME-type

mod_deflate DEFLATE text/html text/plain

()

AddOutputFilterByTypeDEFLATEtext/htmltext/plain

text/html INCLUDES DEFLATE

<Location/cgi-bin/>

OptionsIncludes

AddOutputFilterByTypeINCLUDES;DEFLATEtext/html

</Location>

:

AddOutputFilterByType DefaultType DefaultType

AddOutputFilter

SetOutputFilter

AllowEncodedSlashes

: URL: AllowEncodedSlashesOn|Off

: AllowEncodedSlashesOff

: ,: Core: core: Apache2.0.46

AllowEncodedSlashes ( / %2F

URL404(Notfound)

AllowEncodedSlashesOn PATH_INFO

TurningAllowEncodedSlashesOnismostlyusefulwhenusedinconjunctionwithPATH_INFO.

%2F() %5CURL

AcceptPathInfo

AllowOverride

: .htaccess: AllowOverrideAll|None|directive-type

[directive-type]...

: AllowOverrideAll

:: Core: core

( AccessFileName) .htaccess

<Directory>AllowOverride<Directory> <Location>

<DirectoryMatch> <Files>

None .htaccess

All .htaccess

directive-type

AuthConfig( AuthDBMGroupFile,AuthDBMUserFileAuthGroupFile,AuthName,AuthType,AuthUserFile,Require )

FileInfo( DefaultType

LanguagePriority,SetHandler,SetInputFilter,SetOutputFilter,mod_mimeAdd*Remove*

Indexes (AddDescriptionAddIconByType,DefaultIcon,DirectoryIndex,

FancyIndexing,HeaderName,IndexIgnore,IndexOptions,ReadmeName )

Limit( Allow

Options

:

AllowOverrideAuthConfigIndexes

AuthConfig Indexes

AccessFileName

.htaccess

AuthName

: HTTP(:realm): AuthNameauth-domain

: ,.htaccess: AuthConfig: Core: core

(:realm) Require AuthUserFile AuthGroupFile

:

AuthName"TopSecret"

AuthName

AuthType

:: AuthTypeBasic|Digest

: ,.htaccess: AuthConfig: Core: core

AuthUserFile AuthGroupFile

CGIMapExtension

: CGI: CGIMapExtensioncgi-path.extension

: None

: ,.htaccess: FileInfo: Core: core: NetWare

ApacheCGI .foo .fooCGIFOO

ContentDigest

: Content-MD5HTTP: ContentDigestOn|Off

: ContentDigestOff

: ,,,.htaccess: Options: Core: core

RFC1864RFC2068 Content-MD5

MD5( )

Content-MD5 :

Content-MD5:AuLb7Dp1rqtRtxz2m9kRpA==

()

Content-MD5 core

DefaultType

: MIME: DefaultTypeMIME-type

: DefaultTypetext/plain

: ,,,.htaccess: FileInfo: Core: core

MIME

DefaultTypeimage/gif

.gif GIF

ForceType MIME

<Directory>

: : <Directorydirectory-path>...</Directory>

: ,: Core: core

pathUnix ?1 /home/user/public_html <Directory

/*/public_html> <Directory

/home/*/public_html> :

<Directory/usr/local/httpd/htdocs>

OptionsIndexesFollowSymLinks

</Directory>

directory-path:Apache <Directory>

~ :

<Directory~"^/www/.*/[0-9]{3}">

/www/ 3

() <Directory> ()

<Directory/>

AllowOverrideNone

</Directory>

<Directory/home/>

AllowOverrideFileInfo

</Directory>

/home/web/dir/doc.html :

AllowOverrideNone (.htaccess)AllowOverrideFileInfo (/home)/home/.htaccess,/home/web/.htaccess,/home/web/.htaccess FileInfo

<Directory~abc$>

#...directiveshere...

</Directory>

<Directory> .htaccess/home/abc/public_html/abc <Directory>

Apache <Directory/> AllowfromAllURLApache

<Directory/>

OrderDeny,Allow

DenyfromAll

</Directory>

httpd.conf <Directory><LimitExcept>

<DirectoryMatch>

: : <DirectoryMatchregex>...</DirectoryMatch>

: ,: Core: core

<Directory> <DirectoryMatch> </DirectoryMatch>

<DirectoryMatch"^/www/.*/[0-9]{3}">

/www/3

<Directory> <Directory>

DocumentRoot

: : DocumentRootdirectory-path

: DocumentRoot/usr/local/apache/htdocs

: ,: Core: core

httpd Alias

DocumentRoot/usr/web

http://www.my.host.com/index.html/usr/web/index.html

DocumentRoot

URL

EnableMMAP

: : EnableMMAPOn|Off

: EnableMMAPOn

: ,,,.htaccess: FileInfo: Core: core

httpd

httpdNFS DocumentRoot httpd

:

EnableMMAPOff

NFS :

<Directory"/path-to-nfs-files">

EnableMMAPOff

</Directory>

EnableSendfile

: sendfile: EnableSendfileOn|Off

: EnableSendfileOn

: ,,,.htaccess: FileInfo: Core: core: 2.0.44

httpd sendfile

sendfilereadsend

sendfileLinuxsendfile IPv6TCP-checksum DocumentRoot(NFSSMB)

:

EnableSendfileOff

NFSSMB :

<Directory"/path-to-nfs-files">

EnableSendfileOff

</Directory>

ErrorDocument

:: ErrorDocumenterror-codedocument

: ,,,.htaccess: FileInfo: Core: core: Apache2.0

Apache

1. Apache

2.

3. URL-path

4. URL

24 ErrorDocumentApache

URLURL(/) URL :

ErrorDocument500http://foo.example.com/cgi-bin/tester

ErrorDocument404/cgi-bin/bad_urls.pl

ErrorDocument401/subscription_info.html

ErrorDocument403"Sorrycan'tallowyouaccesstoday"

defaultApache ErrorDocument Apache

ErrorDocument404/cgi-bin/bad_urls.pl

<Directory/web/docs>

ErrorDocument404default

</Directory>

URL( http) ErrorDocumentApache

ErrorDocument401URL 401ErrorDocument401

MicrosoftInternetExplorer(MSIE)MSIE Microsoft

2.0

ErrorLog

:: ErrorLogfile-path|syslog[:facility]

: ErrorLoglogs/error_log(Unix)ErrorLog

logs/error.log(WindowsandOS/2)

: ,: Core: core

ErrorLog

ErrorLog/var/log/httpd/error_log

file-path(|)

ErrorLog"|/usr/local/bin/httpd_errors"

syslog syslogd(8)syslog:facility syslog(1)

ErrorLogsyslog:user

:

Unix

LogLevel

Apache

FileETag

: ETagHTTP: FileETagcomponent...

: FileETagINodeMTimeSize

: ,,,.htaccess: FileInfo: Core: core

FileETag ETag

ETag inode,(mtime)

INodeinode

MTime

Size

All

FileETagINodeMTimeSize

NoneETag

INode,MTime,Size + -

FileETagINodeMTimeSize ( )

<Files>

:: <Filesfilename>...</Files>

: ,,,.htaccess: All: Core: core

<Files> </Files> ()

.htaccess <Location> <Directory>

filename ? *

<Files~"\.(gif|jpe?g|png)$">

<Directory> <Location> <Files> .htaccess

<FilesMatch>

: : <FilesMatchregex>...</FilesMatch>

: ,,,.htaccess: All: Core: core

<FilesMatch> <Files>

<FilesMatch"\.(gif|jpe?g|png)$">

ForceType

: MIME: ForceTypeMIME-type|None

: ,.htaccess: FileInfo: Core: core: Apache2.0core

.htaccess <Directory> <Location> <Files>

MIME-type

ForceTypeimage/gif

DefaultType

None ForceType :

#forceallfilestobeimage/gif:

<Location/images>

ForceTypeimage/gif

</Location>

#butnormalmime-typeassociationshere:

<Location/images/mixed>

ForceTypeNone

</Location>

HostnameLookups

: IPDNS: HostnameLookupsOn|Off|Double

: HostnameLookupsOff

: ,,: Core: core

DNS IP

mod_access 2Double 2 REMOTE_HOST

bin

IdentityCheck

: RFC1413: IdentityCheckOn|Off

: IdentityCheckOff

: ,,: Core: core

identd

<IfDefine>

: : <IfDefine[!]parameter-name>...</IfDefine>

: ,,,.htaccess: All: Core: core

<IfDefinetest>...</IfDefine> test test

<IfDefine> test :

parameter-name!parameter-name

parameter-name

parameter-name httpd -Dparameter-

<IfDefine>

httpd-DReverseProxy...

#httpd.conf

<IfDefineReverseProxy>

LoadModulerewrite_modulemodules/mod_rewrite.so

LoadModuleproxy_modulemodules/libproxy.so

</IfDefine>

<IfModule>

: : <IfModule[!]module-name>...</IfModule>

: ,,,.htaccess: All: Core: core

<IfModuletest>...</IfModule>test test

<IfModule> test

modulename!modulename

modulename Apache (modulename

modulename mod_rewrite.c

STANDARD20_MODULE_STUFF

<IfModule>

Include

:: Includefile-path|directory-path

: ,,: Core: core: 2.0.41

( fnmatch)httpd

ServerRoot

:

Include/usr/local/apache2/conf/ssl.conf

Include/usr/local/apache2/conf/vhosts/*.conf

ServerRoot:

Includeconf/ssl.conf

Includeconf/vhosts/*.conf

apachectlconfigtest :

root@host#apachectlconfigtest

Processingconfigfile:/usr/local/apache2/conf/ssl.conf

Processingconfigfile:

/usr/local/apache2/conf/vhosts/vhost1.conf

Processingconfigfile:

/usr/local/apache2/conf/vhosts/vhost2.conf

SyntaxOK

apachectl

KeepAlive

: HTTP: KeepAliveOn|Off

: KeepAliveOn

: ,: Core: core

HTTP/1.0Keep-AliveHTTP/1.1 TCP HTML50%

HTTP/1.0 Keep-AliveKeep-Alive CGISSI HTTP/1.1

MaxKeepAliveRequests

KeepAliveTimeout

:: KeepAliveTimeoutseconds

: KeepAliveTimeout15

: ,: Core: core

Apache

KeepAliveTimeout

<Limit>

: HTTP: <Limitmethod[method]...>...</Limit>

: ,,,.htaccess: All: Core: core

<Limit> HTTPDELETE :

<LimitPOSTPUTDELETE>

Requirevalid-user

</Limit>

: GET,POST,PUT,PROPFIND,PROPPATCH,MKCOL,COPY,MOVE,LOCK,UNLOCK.

GET HEAD TRACE

<Limit> <LimitExcept>

<LimitExcept>

: HTTP: <LimitExceptmethod[method]...>...

</LimitExcept>

: ,,,.htaccess: All: Core: core

<LimitExcept> </LimitExcept> HTTP<Limit>

:

<LimitExceptPOSTGET>

Requirevalid-user

</LimitExcept>

LimitInternalRecursion

:: LimitInternalRecursionnumber[number]

: LimitInternalRecursion10

: ,: Core: core: Apache2.0.47

Action Actionmod_dir DirectoryIndex

LimitInternalRecursion

LimitInternalRecursion5

LimitRequestBody

: HTTP: LimitRequestBodybytes

: LimitRequestBody0

: ,,,.htaccess: All: Core: core

bytes0()2147483647(2GB)

LimitRequestBody ()

100K

LimitRequestBody102400

LimitRequestFields

: HTTP: LimitRequestFieldsnumber

: LimitRequestFields100

:: Core: core

number0()32767 DEFAULT_LIMIT_REQUEST_FIELDS(100)

LimitRequestBody HTTPHTTP

:

LimitRequestFields50

LimitRequestFieldSize

: HTTP: LimitRequestFieldsizebytes

: LimitRequestFieldsize8190

:: Core: core

HTTP bytesDEFAULT_LIMIT_REQUEST_FIELDSIZE(8192)

LimitRequestFieldSize

:

LimitRequestFieldSize4094

LimitRequestLine

: HTTP: LimitRequestLinebytes

: LimitRequestLine8190

:: Core: core

HTTP bytes08190)

LimitRequestLine LimitRequestLine URI

:

LimitRequestLine4094

LimitXMLRequestBody

: XML: LimitXMLRequestBodybytes

: LimitXMLRequestBody1000000

: ,,,.htaccess: All: Core: core

XML() 0

:

LimitXMLRequestBody0

<Location>

: URL: <LocationURL-path|URL>...</Location>

: ,: Core: core

<Location> URL <Location><Files>

<Location>

<Location>

<Location> <Location/>

() URL /path/ http://servername

scheme://servername/path

URL ? *

~ :

<Location~"/(extra|special)/data">

URL /extra/data /special/data<LocationMatch> <Location>

<Location> SetHandler

<Location/status>

SetHandlerserver-status

OrderDeny,Allow

Denyfromall

Allowfrom.foo.com

</Location>

/()

URL <LocationMatch> <Location>

<LocationMatch^/abc> /abcURLURL () <Location><Location>proxy /abc//def

<LocationMatch>

: URL: <LocationMatchregex>...</LocationMatch>

: ,: Core: core

<LocationMatch> <Location> URL

<LocationMatch"/(extra|special)/data">

URL /extra/data /special/data

LogLevel

: ErrorLog: LogLevellevel

: LogLevelwarn

: ,: Core: core

LogLevel( ErrorLog )

emerg - Childcannotopenlockfile.Exiting()

alert getpwuid:couldn'tdetermineusernamefromuid(getpwuid:UID)

crit socket:Failedtogetasocket,exitingchild(socket:)

error Prematureendofscriptheaders()warn childprocess1234didnotexit,sendinganother

SIGHUP(1234SIGHUP)notice httpd:caughtSIGBUS,attemptingtodumpcorein

...(httpd:SIGBUS...)info "Serverseemsbusy,(youmayneedtoincrease

StartServers,orMin/MaxSpareServers)..."((StartServersMin/MaxSpareServers))

debug "Openingconfigfile..."(...)

crit

:

LogLevelnotice

notice

MaxKeepAliveRequests

:: MaxKeepAliveRequestsnumber

: MaxKeepAliveRequests100

: ,: Core: core

MaxKeepAliveRequests KeepAlive

:

MaxKeepAliveRequests500

MaxRanges

: Numberofrangesallowedbeforereturningthecompleteresource

: MaxRangesdefault|unlimited|none|

number-of-ranges

: MaxRanges200

: ,,: Core: core: AvailableinApacheHTTPServer2.0.65andlater

Thedocumentationforthisdirectivehasnotbeentranslatedyet.PleasehavealookattheEnglishversion.

NameVirtualHost

: IP: NameVirtualHostaddr[:port]

:: Core: core

NameVirtualHost

addr IP

NameVirtualHost111.22.33.44

NameVirtualHost IP

_default_ NameVirtualHostIPNameVirtualHost VirtualHost)

NameVirtualHost111.22.33.44:8080

IPV6:

NameVirtualHost[2001:db8::a00:20ff:fea7:ccea]:8080

*

NameVirtualHost*

<VirtualHost>

<VirtualHost> NameVirtualHost

NameVirtualHost1.2.3.4

<VirtualHost1.2.3.4>

#...

</VirtualHost>

Options

:: Options[+|-]option[[+|-]option]...

: OptionsAll

: ,,,.htaccess: Options: Core: core

Options

option None 1

All

MultiViews

ExecCGI

mod_cgiCGI

FollowSymLinks

<Directory>

<Location>

Includes

mod_includeSSI

IncludesNOEXEC

SSI #exec #execCGIvirtual ScriptAlias CGI

Indexes

URL DirectoryIndex

mod_autoindex

MultiViews

mod_negotiation "MultiViews"

SymLinksIfOwnerMatch

ID

<Location>

Options +

+ -:

<Directory/web/docs>

OptionsIndexesFollowSymLinks

</Directory>

<Directory/web/docs/spec>

OptionsIncludes

</Directory>

/web/docs/spec Includes 2 -:

<Directory/web/docs>

OptionsIndexesFollowSymLinks

</Directory>

<Directory/web/docs/spec>

Options+Includes-Indexes

</Directory>

/web/docs/spec FollowSymLinks Includes

-IncludesNOEXEC -Includes SSI

All

Require

:: Requireentity-name[entity-name]...

: ,.htaccess: AuthConfig: Core: core

Requireuseruserid[userid]...

Requiregroupgroup-name[group-name]...

Requirevalid-user

Require AuthName AuthType ()AuthUserFile AuthGroupFile

AuthTypeBasic

AuthName"RestrictedDirectory"

AuthUserFile/web/users

AuthGroupFile/web/groups

Requiregroupadmin

Satisfy

mod_access

RLimitCPU

: ApacheCPU: RLimitCPUseconds|max[seconds|max]

:: ,,,.htaccess: All: Core: core

Apache ApacheforkApache fork

CPU

RLimitMEM

RLimitNPROC

RLimitMEM

: Apache: RLimitMEMbytes|max[bytes|max]

:: ,,,.htaccess: All: Core: core

Apache ApacheforkApache fork

RLimitCPU

RLimitNPROC

RLimitNPROC

: Apache: RLimitNPROCnumber|max[number|max]

:: ,,,.htaccess: All: Core: core

Apache ApacheforkApache fork

CGIID

RLimitMEM

RLimitCPU

Satisfy

:: SatisfyAny|All

: SatisfyAll

: ,.htaccess: AuthConfig: Core: core: 2.0.51 <Limit>

<LimitExcept>

Allow Require Any

Requirevalid-user

Allowfrom192.168.1

SatisfyAny

2.0.51 <Limit> <LimitExcept>

Allow

Require

ScriptInterpreterSource

: CGI: ScriptInterpreterSourceRegistry|Registry-

Strict|Script

: ScriptInterpreterSourceScript

: ,,,.htaccess: FileInfo: Core: core: Win32 Registry-StrictApache2.0

ApacheCGI ) Win32

#!C:/Perl/bin/perl.exe

perl PATH:

#!perl

ScriptInterpreterSourceRegistry (Windows HKEY_CLASSES_ROOTShell\ExecCGI\Command Shell\Open\Command

Apache Script

ScriptInterpreterSourceRegistry ScriptAliasApache MicrosoftInternetExplorer

Apache2.0 Registry-Strict RegistryShell\ExecCGI\Command ExecCGIWindows

ServerAdmin

: : ServerAdminemail-address

: ,: Core: core

ServerAdmin

ServerAdminwww-admin@foo.example.com

ServerAlias

: : ServerAliashostname[hostname]...

:: Core: core

ServerAlias

<VirtualHost*>

ServerNameserver.domain.com

ServerAliasserverserver2.domain.comserver2

#...

</VirtualHost>

Apache

ServerName

:: ServerNamefully-qualified-domain-name[:port]

: ,: Core: core: 2.01.3 Port

ServerName simple.example.comDNS www.example.com

ServerNamewww.example.com:80

ServerName IPServerName

<VirtualHost> ServerName

URL( mod_dir)

DNSApacheApacheUseCanonicalName

NameVirtualHost

ServerAlias

ServerPath

: URL: ServerPathURL-path

:: Core: core

ServerPath URL

Apache

ServerRoot

:: ServerRootdirectory-path

: ServerRoot/usr/local/apache

:: Core: core

ServerRoot

ServerRoot/home/httpd

httpd -dServerRoot

ServerSignature

:: ServerSignatureOn|Off|EMail

: ServerSignatureOff

: ,,,.htaccess: All: Core: core

ServerSignature (mod_info)

Off (Apache-1.2)ServerName EMail ServerAdmin"mailto:"

2.0.44 ServerSignature

ServerTokens

ServerTokens

: ServerHTTP: ServerTokens

Major|Minor|Min[imal]|Prod[uctOnly]|OS|Full

: ServerTokensFull

:: Core: core

ServerOS

ServerTokensProd[uctOnly]

(): Server:Apache

ServerTokensMajor

Serversends(e.g.):Server:Apache/2

ServerTokensMinor

Serversends(e.g.):Server:Apache/2.0

ServerTokensMin[imal]

(): Server:Apache/2.0.41

ServerTokensOS

(): Server:Apache/2.0.41(Unix)

ServerTokensFull()(): Server:Apache/2.0.41(Unix)PHP/4.2.2

MyMod/1.2

2.0.44 ServerSignature

ServerSignature

SetHandler

:: SetHandlerhandler-name|None

: ,,,.htaccess: FileInfo: Core: core: Apache2.0core

.htaccess <Directory> <Location>name

SetHandlerimap-file

:URL http://servername/status

<Location/status>

SetHandlerserver-status

</Location>

None SetHandler

AddHandler

SetInputFilter

: POST: SetInputFilterfilter[;filter...]

: ,,,.htaccess: FileInfo: Core: core

SetInputFilter POST

SetOutputFilter

:: SetOutputFilterfilter[;filter...]

: ,,,.htaccess: FileInfo: Core: core

SetOutputFilter

/www/data/ SSI

<Directory/www/data/>

SetOutputFilterINCLUDES

</Directory>

TimeOut

: : TimeOutseconds

: TimeOut300

:: Core: core

TimeOut :

1. GET

2. POSTPUTTCP

3. TCPACK

Apache1.21200

TraceEnable

: DeterminesthebehaviouronTRACErequests: TraceEnable[on|off|extended]

: TraceEnableon

:: Core: core: AvailableinApache1.3.34,2.0.55andlater

Thedocumentationforthisdirectivehasnotbeentranslatedyet.PleasehavealookattheEnglishversion.

UseCanonicalName

:: UseCanonicalNameOn|Off|Dns

: UseCanonicalNameOn

: ,,: Core: core

Apache URL URL UseCanonicalNameOn

)Apache ServerName PortSERVER_NAME SERVER_PORT

UseCanonicalNameOffApache URLCGI SERVER_NAME SERVER_PORT

www URLhttp://www.domain.com/splat/ 1 www.domain.com-- FAQ

UseCanonicalName Off Apachehtttp://www/splat/

UseCanonicalNameDNS Host: IPDNSURL

CGI SERVER_NAME URL

ServerName

Listen

<VirtualHost>

: IP: <VirtualHostaddr[:port][addr[:port]]...>

...</VirtualHost>

:: Core: core

<VirtualHost> </VirtualHost> <VirtualHost> Addr:

IPIPNameVirtualHost* IPIPIP

<VirtualHost10.1.2.3>

ServerAdminwebmaster@host.foo.com

DocumentRoot/www/docs/host.foo.com

ServerNamehost.foo.com

ErrorLoglogs/host.foo.com-error_log

TransferLoglogs/host.foo.com-access_log

</VirtualHost>

IPv6 IPv6:

<VirtualHost[2001:db8::a00:20ff:fea7:ccea]>

ServerAdminwebmaster@host.example.com

DocumentRoot/www/docs/host.example.com

ServerNamehost.example.com

ErrorLoglogs/host.example.com-error_log

TransferLoglogs/host.example.com-access_log

</VirtualHost>

IP alias )

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

:port )

:

<VirtualHost>ApacheListen IP ListenApachelisten

IP _default_VirtualHost (_default_ )

:port )

:port )

ApacheDNSApacheApache

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

ApacheMPM

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: (MPM)

: MPM

AcceptMutex

: acceptApache: AcceptMutexdefault|method

: AcceptMutexdefault

:: MPM: leader,perchild,prefork,threadpool,worker

AcceptMutex accept

Default

flock

LockFile flock(2)

fcntl

LockFile fcntl(2)

posixsem

POSIX

pthread

POSIXThreads(PThreads) POSIX

sysvsem

SySV

LogLevel

BS2000Account

: BS2000: BS2000Accountaccount

:: MPM: perchild,prefork: BS2000

BS2000Account BS2000 Apache(BS2000POSIX(sub-LOGON BS2000) SYSROOT

Note

BS2000Account

ApacheEBCDICport

CoreDumpDirectory

: Apache: CoreDumpDirectorydirectory

::: MPM: beos,leader,mpm_winnt,perchild,prefork,

threadpool,worker

Apache

Linux

Apacheroot Linux2.4 CoreDumpDirectory

EnableExceptionHook

:: EnableExceptionHookOn|Off

: EnableExceptionHookOff

:: MPM: leader,perchild,prefork,threadpool,worker: 2.0.49

--enable-exception-hookconfigure

mod_whatkilledus mod_backtrace

Trawick EnableExceptionHooksite

Group

:: Groupunix-group

: Group#-1

:: MPM: beos,leader,mpmt_os2,perchild,prefork,

threadpool,worker: Apache2.0

Group :

#

Groupwww-group

nobody

Group( User)

: <VirtualHost>Apache2.0SuexecUserGroup

Group beos mpmt_os2MPM

Listen

: listenIP: Listen[IP-address:]portnumber

:: MPM: beos,leader,mpm_netware,mpm_winnt,mpmt_os2,

perchild,prefork,threadpool,worker: Apache2.0

ListenApache IPlisten Apache

Listen

listen Listen

808000

Listen80

Listen8000

Listen192.170.2.1:80

Listen192.170.2.5:8000

IPv6

Listen[2001:db8::a00:20ff:fea7:ccea]:80

IP Listen'Addressalreadyinuse'

DNSApache

ListenBackLog

:: ListenBacklogbacklog

: ListenBacklog511

:: MPM: beos,leader,mpm_netware,mpm_winnt,mpmt_os2,

perchild,prefork,threadpool,worker

OS OSOS

LockFile

:: LockFilefilename

: LockFilelogs/accept.lock

:: MPM: leader,perchild,prefork,threadpool,worker

AcceptMutex fcntl flocklogsNFS

/var/tmp

AcceptMutex

MaxClients

: : MaxClientsnumber

::: MPM: beos,leader,prefork,threadpool,worker

MaxClients

( prefork) MaxClientsServerLimit

( beosworker) MaxClientsMPM16 ServerLimit 25( ThreadsPerChild

MaxClients16 ServerLimit

MaxMemFree

: free(): MaxMemFreeKBytes

: MaxMemFree0

:: MPM: beos,leader,mpm_netware,prefork,threadpool,

worker,mpm_winnt

MaxMemFree free()

MaxRequestsPerChild

:: MaxRequestsPerChildnumber

: MaxRequestsPerChild10000

:: MPM: leader,mpm_netware,mpm_winnt,mpmt_os2,

perchild,prefork,threadpool,worker

MaxRequestsPerChild MaxRequestsPerChild 0

mpm_netware mpm_winnt 0

MaxRequestsPerChild:

()

KeepAlive

MaxSpareThreads

:: MaxSpareThreadsnumber

::: MPM: beos,leader,mpm_netware,mpmt_os2,perchild,

threadpool,worker

MPM

perchild MaxSpareThreads10 MPM

worker,leader,threadpool MaxSpareThreads

250 MPM

mpm_netware MaxSpareThreads100 MPM

beos mpmt_os2 mpm_netware beosMaxSpareThreads50 mpmt_os2 10

MaxSpareThreads Apache

perchild MaxSpareThreads ThreadLimitmpm_netware MinSpareThreadsleader,threadpool,worker MinSpareThreads

ThreadsPerChild

MinSpareThreads

StartServers

MinSpareThreads

: : MinSpareThreadsnumber

::: MPM: beos,leader,mpm_netware,mpmt_os2,perchild,

threadpool,worker

MPM

perchild MinSpareThreads5 NumServers10 MinSpareThreads 550

worker,leader,threadpool MinSpareThreads75

mpm_netware MinSpareThreads10 MPM

beos mpmt_os2 mpm_netware beosMinSpareThreads1 mpmt_os2 5

MaxSpareThreads

StartServers

PidFile

: ID: PidFilefilename

: PidFilelogs/httpd.pid

:: MPM: beos,leader,mpm_winnt,mpmt_os2,perchild,

prefork,threadpool,worker

PidFile ID

PidFile/var/run/apache.pid

ErrorLog TransferLog PidFileID

PidFile

Apache2 apachectl()

ReceiveBufferSize

: TCPreceivebuffersize: ReceiveBufferSizebytes

: ReceiveBufferSize0

:: MPM: beos,leader,mpm_netware,mpm_winnt,mpmt_os2,

perchild,prefork,threadpool,worker

Thedocumentationforthisdirectivehasnotbeentranslatedyet.PleasehavealookattheEnglishversion.

ScoreBoardFile

: : ScoreBoardFilefile-path

: ScoreBoardFilelogs/apache_status

:: MPM: beos,leader,mpm_winnt,perchild,prefork,

threadpool,worker

Apache Apache

ScoreBoardFile/var/run/apache_status

ScoreBoardFile RAM

Apache

SendBufferSize

: TCP: SendBufferSizebytes

: SendBufferSize0

:: MPM: beos,leader,mpm_netware,mpm_winnt,mpmt_os2,

perchild,prefork,threadpool,worker

TCP

0OS

ServerLimit

:: ServerLimitnumber

::: MPM: leader,perchild,prefork,threadpool,worker

preforkMPM Apache MaxClients

) workerMPM ThreadLimit

MaxClients

ServerLimitApache

preforkMPM MaxClients256()MaxClients

worker,leader,threadpoolMPM MaxClientsThreadsPerChild16() ThreadsPerChild

perchildMPM NumServers8()

ServerLimit20000

Apache

StartServers

:: StartServersnumber

::: MPM: leader,mpmt_os2,prefork,threadpool,worker

StartServers

MPM leader,threadpool,worker3 prefork 5 mpmt_os2 2

StartThreads

:: StartThreadsnumber

::: MPM: beos,mpm_netware,perchild

perchild StartThreads5

mpm_netware StartThreads50

beos StartThreads10

ThreadLimit

: : ThreadLimitnumber

::: MPM: leader,mpm_winnt,perchild,threadpool,worker: Apache2.0.41 mpm_winnt

Apache ThreadsPerChild

ThreadLimit ThreadsPerChild

ThreadsPerChild ApacheThreadsPerChild

ThreadLimit mpm_winnt1920 64

ThreadLimit20000(mpm_winnt ThreadLimit15000

ThreadsPerChild

:: ThreadsPerChildnumber

::: MPM: leader,mpm_winnt,threadpool,worker

MPM

mpm_winnt ThreadsPerChild 64 25

Copyright2013TheApacheSoftwareFoundation. ||FAQ||

User

: ID: Userunix-userid

: User#-1

:: MPM: leader,perchild,prefork,threadpool,worker: Apache2.0

User IDroot Unix-userid

#

User( Group)

perchildMPMID <VirtualHost>

: <VirtualHost>

User beos mpmt_os2MPM

LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheMPMbeos

Description: ThisMulti-ProcessingModuleisoptimizedforBeOS.

Status: MPMModuleIdentifier: mpm_beos_moduleSourceFile: beos.c

SummaryThisMulti-ProcessingModule(MPM)isthedefaultforBeOS.Itusesasinglecontrolprocesswhichcreatesthreadstohandlerequests.

SeealsoSettingwhichaddressesandportsApacheuses

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

MaxRequestsPerThreadDirective

Description: Limitonthenumberofrequeststhatanindividualthreadwillhandleduringitslife

Syntax: MaxRequestsPerThreadnumber

Default: MaxRequestsPerThread0

Context: serverconfigStatus: MPMModule: beos

TheMaxRequestsPerThreaddirectivesetsthelimitonthenumberofrequeststhatanindividualserverthreadwillhandle.AfterMaxRequestsPerThreadrequests,thethreadwilldie.IfMaxRequestsPerThreadis0,thenthethreadwillneverexpire.

SettingMaxRequestsPerThreadtoanon-zerolimithastwobeneficialeffects:

itlimitstheamountofmemorythatathreadcanconsumeby(accidental)memoryleakage;bygivingthreadsafinitelifetime,ithelpsreducethenumberofthreadswhentheserverloadreduces.

Note:

ForKeepAliverequests,onlythefirstrequestiscountedtowardsthislimit.Ineffect,itchangesthebehaviortolimitthenumberofconnectionsperthread.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheMPMleader

Description: AnexperimentalvariantofthestandardworkerMPM

Status: MPMModuleIdentifier: mpm_leader_moduleSourceFile: leader.c

Summary

Warning

ThisMPMisexperimental,soitmayormaynotworkasexpected.

ThisisanexperimentalvariantofthestandardworkerMPM.ItusesaLeader/Followersdesignpatterntocoordinateworkamongthreads.Formoreinfo,seehttp://deuce.doc.wustl.edu/doc/pspdfs/lf.pdf.

TousetheleaderMPM,add--with-mpm=leadertotheconfigurescript'sargumentswhenbuildingthehttpd.

ThisMPMdependsonAPR'satomiccompare-and-swapoperationsforthreadsynchronization.Ifyouarecompilingforanx86targetandyoudon'tneedtosupport386s,oryouarecompilingforaSPARCandyoudon'tneedtorunonpre-UltraSPARCchips,add--enable-nonportable-atomics=yestotheconfigurescript'sarguments.ThiswillcauseAPRtoimplementatomicoperationsusingefficientopcodesnotavailableinolderCPUs.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheMPMnetware

Description: Multi-ProcessingModuleimplementinganexclusivelythreadedwebserveroptimizedforNovellNetWare

Status: MPMModuleIdentifier: mpm_netware_moduleSourceFile: mpm_netware.c

SummaryThisMulti-ProcessingModule(MPM)implementsanexclusivelythreadedwebserverthathasbeenoptimizedforNovellNetWare.

Themainthreadisresponsibleforlaunchingchildworkerthreadswhichlistenforconnectionsandservethemwhentheyarrive.Apachealwaystriestomaintainseveralspareoridleworkerthreads,whichstandreadytoserveincomingrequests.Inthisway,clientsdonotneedtowaitforanewchildthreadstobespawnedbeforetheirrequestscanbeserved.

TheStartThreads,MinSpareThreads,MaxSpareThreads,andMaxThreadsregulatehowthemainthreadcreatesworkerthreadstoserverequests.Ingeneral,Apacheisveryself-regulating,somostsitesdonotneedtoadjustthesedirectivesfromtheirdefaultvalues.SiteswithlimitedmemorymayneedtodecreaseMaxThreadstokeeptheserverfromthrashing(spawningandterminatingidlethreads).Moreinformationabouttuningprocesscreationisprovidedintheperformancehintsdocumentation.

MaxRequestsPerChildcontrolshowfrequentlytheserverrecyclesprocessesbykillingoldonesandlaunchingnewones.OntheNetWareOSitishighlyrecommendedthatthisdirectiveremainsetto0.Thisallowsworkerthreadstocontinueservicingrequests

indefinitely.

SeealsoSettingwhichaddressesandportsApacheuses

MaxThreadsDirective

Description: SetthemaximumnumberofworkerthreadsSyntax: MaxThreadsnumber

Default: MaxThreads2048

Context: serverconfigStatus: MPMModule: mpm_netware

TheMaxThreadsdirectivesetsthedesiredmaximumnumberworkerthreadsallowable.Thedefaultvalueisalsothecompiledinhardlimit.Thereforeitcanonlybelowered,forexample:

MaxThreads512

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ThreadStackSizeDirective

Description: DeterminethestacksizeforeachthreadSyntax: ThreadStackSizenumber

Default: ThreadStackSize65536

Context: serverconfigStatus: MPMModule: mpm_netware

Thisdirectivetellstheserverwhatstacksizetouseforeachoftherunningthreads.Ifyouevergetastackoverflowyouwillneedtobumpthisnumbertoahighersetting.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheMPMos2

Description: Hybridmulti-process,multi-threadedMPMforOS/2

Status: MPMModuleIdentifier: mpm_mpmt_os2_moduleSourceFile: mpmt_os2.c

SummaryTheServerconsistsofamain,parentprocessandasmall,staticnumberofchildprocesses.

Theparentprocess'sjobistomanagethechildprocesses.ThisinvolvesspawningchildrenasrequiredtoensuretherearealwaysStartServersprocessesacceptingconnections.

Eachchildprocessconsistsofaapoolofworkerthreadsandamainthreadthatacceptsconnectionsandpassesthemtotheworkersviaaworkqueue.Theworkerthreadpoolisdynamic,managedbyamaintenancethreadsothatthenumberofidlethreadsiskeptbetweenMinSpareThreadsandMaxSpareThreads.

SeealsoSettingwhichaddressesandportsApacheuses

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheMPMperchild

Description: Multi-ProcessingModuleallowingfordaemonprocessesservingrequeststobeassignedavarietyofdifferentuserids

Status: MPMModuleIdentifier: mpm_perchild_moduleSourceFile: perchild.c

Summary

Thismoduleisnotfunctional.Developmentofthismoduleisnotcompleteandisnotcurrentlyactive.Donotuseperchildunlessyouareaprogrammerwillingtohelpfixit.

ThisMulti-ProcessingModule(MPM)implementsahybridmulti-process,multi-threadedwebserver.Afixednumberofprocessescreatethreadstohandlerequests.Fluctuationsinloadarehandledbyincreasingordecreasingthenumberofthreadsineachprocess.

SeealsoSettingwhichaddressesandportsApacheuses

Howitworks

AsinglecontrolprocesslaunchesthenumberofchildprocessesindicatedbytheNumServersdirectiveatserverstartup.EachchildprocesscreatesthreadsasspecifiedintheStartThreadsdirective.Theindividualthreadsthenlistenforconnectionsandservethemwhentheyarrive.

Apachealwaystriestomaintainapoolofspareoridleserverthreads,whichstandreadytoserveincomingrequests.Inthisway,clientsdonotneedtowaitfornewthreadstobecreated.Foreachchildprocess,ApacheassessesthenumberofidlethreadsandcreatesordestroysthreadstokeepthisnumberwithintheboundariesspecifiedbyMinSpareThreadsandMaxSpareThreads.Sincethisprocessisveryself-regulating,itisrarelynecessarytomodifythesedirectivesfromtheirdefaultvalues.Themaximumnumberofclientsthatmaybeservedsimultaneouslyisdeterminedbymultiplyingthenumberofserverprocessesthatwillbecreated(NumServers)bythemaximumnumberofthreadscreatedineachprocess(MaxThreadsPerChild).

WhiletheparentprocessisusuallystartedasrootunderUnixinordertobindtoport80,thechildprocessesandthreadsarelaunchedbyApacheasaless-privilegeduser.TheUserandGroupdirectivesareusedtosettheprivilegesoftheApachechildprocesses.Thechildprocessesmustbeabletoreadallthecontentthatwillbeserved,butshouldhaveasfewprivilegesbeyondthataspossible.Inaddition,unlesssuexecisused,thesedirectivesalsosettheprivilegeswhichwillbeinheritedbyCGIscripts.

MaxRequestsPerChildcontrolshowfrequentlytheserverrecyclesprocessesbykillingoldonesandlaunchingnewones.

Workingwithdifferentuser-IDsTheperchildMPMaddstheextraabilitytospecifythatparticularprocessesshouldserverequestsunderdifferentuser-IDs.Theseuser-IDscanthenbeassociatedwithspecificvirtualhosts.YouhavetouseoneChildPerUserIDdirectiveforeveryuser/groupcombinationyouwanttoberun.ThenyoucantieparticularvirtualhoststothatuserandgroupIDs.

Thefollowingexampleruns7childprocesses.Twoofthemarerununderuser1/group1.Thenextfourarerununderuser2/group2andtheremainingprocessusestheUserandGroupofthemainserver:

GlobalconfigNumServers7

ChildPerUserIDuser1group12

ChildPerUserIDuser2group24

Usingunbalancednumbersofprocessesasaboveisuseful,iftheparticularvirtualhostsproducedifferentload.Theassignmenttothevirtualhostsiseasilydoneasintheexamplebelow.Inconclusionwiththeexampleabovethefollowingassumes,thatserver2hastoserveabouttwiceofthehitsofserver1.

ExampleNameVirtualHost*

<VirtualHost*>

ServerNamefallbackhost

#noassignment;usefallback

</VirtualHost>

<VirtualHost*>

ServerNameserver1

AssignUserIDuser1group1

</VirtualHost>

<VirtualHost*>

ServerNameserver2

AssignUserIDuser2group2

</VirtualHost>

AssignUserIDDirective

Description: TieavirtualhosttoauserandgroupIDSyntax: AssignUserIDuser-idgroup-id

Context: virtualhostStatus: MPMModule: perchild

Tieavirtualhosttoaspecificuser/groupcombination.RequestsaddressedtothevirtualhostwherethisdirectiveappearswillbeservedbyaprocessrunningwiththespecifieduserandgroupID.

TheuserandgroupIDhastobeassignedtoanumberofchildrenintheglobalserverconfigusingtheChildPerUserIDdirective.Seethesectionaboveforaconfigurationexample.

ChildPerUserIDDirective

Description: SpecifyuserIDandgroupIDforanumberofchildprocesses

Syntax: ChildPerUserIDuser-idgroup-idnum-

children

Context: serverconfigStatus: MPMModule: perchild

SpecifyauserIDandgroupIDforanumberofchildprocesses.Thethirdargument,num-children,isthenumberofchildprocessestostartwiththespecifieduserandgroup.Itdoesnotrepresentaspecificchildnumber.Inordertousethisdirective,theservermustberuninitiallyasroot.Ifyoustarttheserverasanon-rootuser,itwillfailtochangetothelesserprivilegeduser.

Ifthetotalnumberofchildprocesses,foundbytotalingallofthethirdargumentstoallChildPerUserIDdirectivesintheconfigfile,islessthanNumServers,thenallremainingchildrenwillinherittheUserandGroupsettingsfromthemainserver.Seethesectionaboveforaconfigurationexample.

Security

Don'tsetuser-id(orgroup-id)torootunlessyouknowexactlywhatyouaredoing,andwhatthedangersare.

MaxThreadsPerChildDirective

Description: MaximumnumberofthreadsperchildprocessSyntax: MaxThreadsPerChildnumber

Default: MaxThreadsPerChild64

Context: serverconfigStatus: MPMModule: perchild

Thisdirectivesetsthemaximumnumberofthreadsthatwillbecreatedineachchildprocess.Toincreasethisvaluebeyonditsdefault,itisnecessarytochangethevalueoftheThreadLimitdirectiveandstopandre-starttheserver.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

NumServersDirective

Description: TotalnumberofchildrenaliveatthesametimeSyntax: NumServersnumber

Default: NumServers2

Context: serverconfigStatus: MPMModule: perchild

TheNumServersdirectivedeterminesthenumberofchildrenaliveatthesametime.Thisnumbershouldbelargeenoughtohandletherequestsfortheentiresite.Toincreasethisvaluebeyondthevalueof8,itisnecessarytochangethevalueoftheServerLimitdirectiveandstopandre-starttheserver.Seethesectionaboveforaconfigurationexample.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

ApacheMPMprefork

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: fork: MPM: mpm_prefork_module: prefork.c

(MPM) UnixApache1.3 MPM

MPMMPM

Apache

listen

StartServers

MaxClientsApache ()

Unix80 rootApache

MaxRequestsPerChild

MaxSpareServers

:: MaxSpareServersnumber

: MaxSpareServers10

:: MPM: prefork

MaxSpareServers kill

MinSpareServers

StartServers

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

MinSpareServers

:: MinSpareServersnumber

: MinSpareServers5

:: MPM: prefork

MaxSpareServers 11

MaxSpareServers

StartServers

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheMPMthreadpool

Description: YetanotherexperimentalvariantofthestandardworkerMPM

Status: MPMModuleIdentifier: mpm_threadpool_moduleSourceFile: threadpool.c

Summary

Warning

ThisMPMisadeveloperplaygroundandhighlyexperimental,soitmayormaynotworkasexpected.

ThisisanexperimentalvariantofthestandardworkerMPM.RatherthanqueuingconnectionsliketheworkerMPM,thethreadpoolMPMqueuesidleworkerthreadsandhandseachacceptedconnectiontothenextavailableworker.

ThethreadpoolMPMcan'tmatchtheperformanceoftheworkerMPMinbenchmarktesting.Asof2.0.39,someofthekeyload-throttingconceptsfromthethreadpoolMPMhavebeenincorporatedintotheworkerMPM.Thethreadpoolcodeisusefulprimarilyasaresearchplatform.Forgeneral-purposeuseandforanyproductionenvironments,useworkerinstead.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

ApacheMPMwinnt

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: WindowsNT: MPM: mpm_winnt_module: mpm_winnt.c

(MPM) WindowsNT

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

Win32DisableAcceptEx

: accept()AcceptEx: Win32DisableAcceptEx

: AcceptEx()AcceptEx()

:: MPM: mpm_winnt: 2.0.49

AcceptEx()MicrosoftWinSockv2API BSD accept()

API WindowsVPNAcceptEx()

[error](730038)Anoperationwasattemptedonsomethingthatis

notasocket.:winnt_accept:AcceptExfailed.Attemptingto

recover.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

ApacheMPMworker

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: : MPM: mpm_worker_module: worker.c

(MPM)

MPM ThreadsPerChild

ThreadsPerChild MaxClients

Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

() ThreadsPerChild

Apache MinSpareThreads MaxSpareThreadsfork ThreadsPerChild

ThreadsPerChild ThreadLimit

ThreadsPerChild

MaxRequestsPerChild0MaxSpareThreads MaxClients

workerMPM

ServerLimit16

StartServers2

MaxClients150

MinSpareThreads25

MaxSpareThreads75

ThreadsPerChild25

Unix80 rootApache

MaxRequestsPerChild

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_access

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: IP: Base: access_module: mod_access.c: 2.1

mod_access .htaccessIP Order Allow Deny

(GET,PUT,POST)

Satisfy

Require

Allow

:: Allowfromall|host|env=env-variable

[host|env=env-variable]...

: ,.htaccess: Limit: Base: mod_access

Allow

from Allowfromall

()

:Allowfromapache.org

Apache HostnameLookupsIPIPDNS

IP

:Allowfrom10.1.2.3

IP

IP

:

Allowfrom10.1

IP

/

:Allowfrom10.1.0.0/255.255.0.0

a.b.c.dw.x.y.z

/nnnCIDR

:Allowfrom10.1.0.0/16

nnn1

:

IPv6IPv6:

Allowfrom2001:db8::a00:20ff:fea7:ccea

Allowfrom2001:db8::a00:20ff:fea7:ccea/10

Allow variable mod_setenvif

) RefererHTTP

:SetEnvIfUser-Agent^KnockKnock/2\.0let_me_in

<Directory/docroot>

OrderDeny,Allow

Denyfromall

Allowfromenv=let_me_in

</Directory>

user-agent KnockKnock/2.0

Deny

:: Denyfromall|host|env=env-variable

[host|env=env-variable]...

: ,.htaccess: Limit: Base: mod_access

IP

Order

: Allow Deny: Orderordering

: OrderDeny,Allow

: ,.htaccess: Limit: Base: mod_access

Order Allow Deny

Deny,Allow

Deny Allow

Allow,Deny

Allow Deny

Mutual-failure

Allow Deny

Allow Deny

apache.org

OrderDeny,Allow

Denyfromall

Allowfromapache.org

foo.apache.org apache.org

OrderAllow,Deny

Allowfromapache.org

Denyfromfoo.apache.org

Order Deny,Allowapache.org Denyfromfoo.apache.org

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

apache.org allow

Order Allow

<Directory/www>

OrderAllow,Deny

</Directory>

deny /www

Order Directory .htaccess Allow Deny

Directory,Location,Files

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_actions

: CGI: Base: actions_module: mod_actions.c

Action CGI

mod_cgi

CGIApache

Action

: CGI: Actionaction-typecgi-script

: ,,,.htaccess: FileInfo: Base: mod_actions

action-type cgi-scriptAddHandler CGIURL-pathMIMEURL CGIPATH_INFOPATH_TRANSLATED

#Requestsforfilesofaparticulartype:

Actionimage/gif/cgi-bin/images.cgi

#Filesofaparticularfileextension

AddHandlermy-file-type.xyz

Actionmy-file-type/cgi-bin/program.cgi

MIME image/gif

2 .xyz

AddHandler

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

Script

: CGI: Scriptmethodcgi-script

: ,,: Base: mod_actions

method cgi-scriptAddHandler CGIURL-pathPATH_INFOPATH_TRANSLATED

ScriptPUT Scriptput

Script CGI

#For<ISINDEX>-stylesearching

ScriptGET/cgi-bin/search

#ACGIPUThandler

ScriptPUT/~bob/put.cgi

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_alias

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: : Base: alias_module: mod_alias.c

URLScriptAliasCGI

Redirect URL

mod_aliasURL

mod_rewrite

URL

AliasRedirect ( <VirtualHost>)AliasRedirect

AliasRedirect Redirect RedirectMatchAliasAliasRedirect

:

Alias/foo/bar/baz

Alias/foo/gaq

/fooAlias /foo/barAlias

Alias

: URL: AliasURL-pathfile-path|directory-path

: ,: Base: mod_alias

Alias DocumentRoot

directory-filename

Alias/image/ftp/pub/image

http://myserver/image/foo.gif /ftp/pub/image/foo.gif

url-path/ //usr/local/apache/icons/ /icons

<Directory> ( <Location>

Alias DocumentRoot

Alias/image/ftp/pub/image

<Directory/ftp/pub/image>

Orderallow,deny

Allowfromall

</Directory>

AliasMatch

: URL: AliasMatchregexfile-path|directory-path

: ,: Base: mod_alias

Alias URL

AliasMatch^/icons(.*)/usr/local/apache/icons$1

Redirect

: URL: Redirect[status]URL-pathURL

: ,,,.htaccess: FileInfo: Base: mod_alias

RedirectURL URL URL (%)URL

Redirect/servicehttp://foo2.bar.com/service

http://myserver/service/foo.txthttp://foo2.bar.com/service/foo.txt

RedirectAliasScriptAlias.htaccess<Directory> URL-pathURL

status "temporary"(HTTP302)HTTP:

permanent(301)

temp(302)

seeother"SeeOther"(303)

gone"Gone"(410)

Status 300399(http_protocol.c send_error_response)

:

Redirectpermanent/onehttp://example.com/two

Redirect303/threehttp://example.com/other

RedirectMatch

: URL: RedirectMatch[status]regexURL

: ,,,.htaccess: FileInfo: Base: mod_alias

RedirectJPEG:

RedirectMatch(.*)\.gif$http://www.anotherserver.com$1.jpg

RedirectPermanent

: URL: RedirectPermanentURL-pathURL

: ,,,.htaccess: FileInfo: Base: mod_alias

Redirect (301)

RedirectTemp

: URL: RedirectTempURL-pathURL

: ,,,.htaccess: FileInfo: Base: mod_alias

Redirect (302)

ScriptAlias

: URLCGI: ScriptAliasURL-pathfile-path|directory-path

: ,: Base: mod_alias

ScriptAlias mod_cgicgi-scriptURL(%) URL-path

ScriptAlias/cgi-bin//web/cgi-bin/

http://myserver/cgi-bin/foo

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

ScriptAliasMatch

: URLCGI: ScriptAliasMatchregexfile-path|directory-

path

: ,: Base: mod_alias

ScriptAliasbin:

ScriptAliasMatch^/cgi-bin(.*)/usr/local/apache/cgi-bin$1

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_asis

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: HTTP: Base: asis_module: mod_asis.c

send-as-isHTTP

Cginph

mime httpd/send-as-is

mod_headers

mod_cern_meta

Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

send-as-is

AddHandlersend-as-isasis

.asisApache HTTP

asis()

Status:301NowwheredidIleavethatURL

Location:http://xyz.abc.com/foo/bar.html

Content-type:text/html

<html>

<head>

<title>Lameexcuses'R'us</title>

</head>

<body>

<h1>Fred'sexceptionallywonderfulpagehasmovedto

<ahref="http://xyz.abc.com/foo/bar.html">Joe's</a>site.

</h1>

</body>

</html>

: Date: Server:

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_auth

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

:: Base: auth_module: mod_auth.c: 2.1

HTTPmod_auth_digest

Require

Satisfy

AuthName

AuthType

AuthAuthoritative

: : AuthAuthoritativeOn|Off

: AuthAuthoritativeOn

: ,.htaccess: AuthConfig: Base: mod_auth

AuthAuthoritative Off ID(Configuration modules.c)"AuthenticationRequired"

ID

mod_auth_dbm,mod_auth_msql,mod_auth_anon() AuthUserFile

ID "AuthenticationRequired"NCSA

.htaccessAuthUserFile AuthGroupFile AuthUserFile AuthGroupFile

AuthGroupFile

: : AuthGroupFilefile-path

: ,.htaccess: AuthConfig: Base: mod_auth

AuthGroupFile

:mygroup:bobjoeanne

AuthDBMGroupFile

AuthGroupFile

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

AuthUserFile

: : AuthUserFilefile-path

: ,.htaccess: AuthConfig: Base: mod_auth

AuthUserFile

ID

src/support htpasswd

ID username Filename :

htpasswd-cFilenameusername

Filename username2:

htpasswdFilenameusername2

(:)

AuthUserFile

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_auth_anon

Description: Allows"anonymous"useraccesstoauthenticatedareas

Status: ExtensionModuleIdentifier: auth_anon_moduleSourceFile: mod_auth_anon.cCompatibility: Availableonlyinversionspriorto2.1

SummaryThismoduledoesaccesscontrolinamannersimilartoanonymous-ftpsites;i.e.havea'magic'userid'anonymous'andtheemailaddressasapassword.Theseemailaddressescanbelogged.

Combinedwithother(database)accesscontrolmethods,thisallowsforeffectiveusertrackingandcustomizationaccordingtoauserprofilewhilestillkeepingthesiteopenfor'unregistered'users.OneadvantageofusingAuth-basedusertrackingisthat,unlikemagic-cookiesandfunnyURLpre/postfixes,itiscompletelybrowserindependentanditallowsuserstoshareURLs.

Example

Theexamplebelow(whencombinedwiththeAuthdirectivesofahtpasswd-filebased(orGDM,mSQLetc.)baseaccesscontrolsystemallowsusersinas'guests'withthefollowingproperties:

ItinsiststhattheuserentersauserID.(Anonymous_NoUserID)Itinsiststhattheuserentersapassword.(Anonymous_MustGiveEmail)Thepasswordenteredmustbeavalidemailaddress,ie.containatleastone'@'anda'.'.(Anonymous_VerifyEmail)TheuserIDmustbeoneofanonymousguestwwwtestwelcomeandcomparisonisnotcasesensitive.(Anonymous)AndtheEmailaddressesenteredinthepasswdfieldareloggedtotheerrorlogfile.(Anonymous_LogEmail)

Excerptofhttpd.conf:Anonymous_NoUserIDoff

Anonymous_MustGiveEmailon

Anonymous_VerifyEmailon

Anonymous_LogEmailon

Anonymousanonymousguestwwwtestwelcome

AuthName"Use'anonymous'&Emailaddressforguestentry"

AuthTypebasic

#AnAuthUserFile/AuthDBUserFile/AuthDBMUserFile

#directivemustbespecified,oruse

#Anonymous_Authoritativeforpublicaccess.

#Inthe.htaccessforthepublicdirectory,add:

<Files*>

OrderDeny,Allow

Allowfromall

Requirevalid-user

</Files>

AnonymousDirective

Description: SpecifiesuserIDsthatareallowedaccesswithoutpasswordverification

Syntax: Anonymoususer[user]...

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_anon

Alistofoneormore'magic'userIDswhichareallowedaccesswithoutpasswordverification.TheuserIDsarespaceseparated.Itispossibletousethe'and"quotestoallowaspaceinauserIDaswellasthe\escapecharacter.

Pleasenotethatthecomparisoniscase-IN-sensitive.Istronglysuggestthatthemagicusername'anonymous'isalwaysoneofthealloweduserIDs.

Example:Anonymousanonymous"NotRegistered""Idon'tknow"

ThiswouldallowtheusertoenterwithoutpasswordverificationbyusingtheuserIDs"anonymous","AnonyMous","NotRegistered"and"IDon'tKnow".

Anonymous_AuthoritativeDirective

Description: Configuresifauthorizationwillfall-throughtoothermethods

Syntax: Anonymous_AuthoritativeOn|Off

Default: Anonymous_AuthoritativeOff

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_anon

WhensetOn,thereisnofall-throughtootherauthenticationmethods.SoifauserIDdoesnotmatchthevaluesspecifiedintheAnonymousdirective,accessisdenied.

Besureyouknowwhatyouaredoingwhenyoudecidetoswitchiton.AndrememberthattheorderinwhichtheAuthenticationmodulesarequeriedisdefinedinthemodules.cfilesatcompiletime.

Anonymous_LogEmailDirective

Description: Setswhetherthepasswordenteredwillbeloggedintheerrorlog

Syntax: Anonymous_LogEmailOn|Off

Default: Anonymous_LogEmailOn

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_anon

WhensetOn,thedefault,the'password'entered(whichhopefullycontainsasensibleemailaddress)isloggedintheerrorlog.

Anonymous_MustGiveEmailDirective

Description: SpecifieswhetherblankpasswordsareallowedSyntax: Anonymous_MustGiveEmailOn|Off

Default: Anonymous_MustGiveEmailOn

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_anon

Specifieswhethertheusermustspecifyanemailaddressasthepassword.Thisprohibitsblankpasswords.

Anonymous_NoUserIDDirective

Description: SetswhethertheuserIDfieldmaybeemptySyntax: Anonymous_NoUserIDOn|Off

Default: Anonymous_NoUserIDOff

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_anon

WhensetOn,userscanleavetheuserID(andperhapsthepasswordfield)empty.ThiscanbeveryconvenientforMS-ExploreruserswhocanjusthitreturnorclickdirectlyontheOKbutton;whichseemsanaturalreaction.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Anonymous_VerifyEmailDirective

Description: Setswhethertocheckthepasswordfieldforacorrectlyformattedemailaddress

Syntax: Anonymous_VerifyEmailOn|Off

Default: Anonymous_VerifyEmailOff

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_anon

WhensetOnthe'password'enteredischeckedforatleastone'@'anda'.'toencourageuserstoentervalidemailaddresses(seetheaboveAnonymous_LogEmail).

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_auth_dbm

Description: ProvidesforuserauthenticationusingDBMfilesStatus: ExtensionModuleIdentifier: auth_dbm_moduleSourceFile: mod_auth_dbm.cCompatibility: Availableonlyinversionspriorto2.1

SummaryThismoduleprovidesforHTTPBasicAuthentication,wheretheusernamesandpasswordsarestoredinDBMtypedatabasefiles.Itisanalternativetotheplaintextpasswordfilesprovidedbymod_auth.

SeealsoAuthName

AuthType

Require

Satisfy

AuthDBMAuthoritativeDirective

Description: Setswhetherauthenticationandauthorizationwillbepassedontolowerlevelmodules

Syntax: AuthDBMAuthoritativeOn|Off

Default: AuthDBMAuthoritativeOn

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_dbm

SettingtheAuthDBMAuthoritativedirectiveexplicitlytoOffallowsforbothauthenticationandauthorizationtobepassedontolowerlevelmodules(asdefinedinthemodules.cfiles)ifthereisnouserIDorrulematchingthesupplieduserID.IfthereisauserIDand/orrulespecified;theusualpasswordandaccesscheckswillbeappliedandafailurewillgivean"AuthenticationRequired"reply.

SoifauserIDappearsinthedatabaseofmorethanonemodule;orifavalidRequiredirectiveappliestomorethanonemodule;thenthefirstmodulewillverifythecredentials;andnoaccessispassedon;regardlessoftheAuthDBMAuthoritativesetting.

Acommonuseforthisisinconjunctionwithoneofthebasicauthmodules;suchasmod_auth.WhereasthisDBMmodulesuppliesthebulkoftheusercredentialchecking;afew(administrator)relatedaccessesfallthroughtoalowerlevelwithawellprotected.htpasswdfile.

Bydefault,controlisnotpassedonandanunknownuserIDorrulewillresultinan"AuthenticationRequired"reply.NotsettingitthuskeepsthesystemsecureandforcesanNCSAcompliantbehaviour.

Security:

Doconsidertheimplicationsofallowingausertoallowfall-throughinhis.htaccessfile;andverifythatthisisreallywhatyouwant;Generallyitiseasiertojustsecureasingle.htpasswdfile,thanitistosecureadatabasewhichmighthavemoreaccessinterfaces.

AuthDBMGroupFileDirective

Description: Setsthenameofthedatabasefilecontainingthelistofusergroupsforauthentication

Syntax: AuthDBMGroupFilefile-path

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_dbm

TheAuthDBMGroupFiledirectivesetsthenameofaDBMfilecontainingthelistofusergroupsforuserauthentication.File-pathistheabsolutepathtothegroupfile.

Thegroupfileiskeyedontheusername.Thevalueforauserisacomma-separatedlistofthegroupstowhichtheusersbelongs.Theremustbenowhitespacewithinthevalue,anditmustnevercontainanycolons.

Security:makesurethattheAuthDBMGroupFileisstoredoutsidethedocumenttreeoftheweb-server;donotputitinthedirectorythatitprotects.Otherwise,clientswillbeabletodownloadtheAuthDBMGroupFileunlessotherwiseprotected.

CombiningGroupandPasswordDBMfiles:Insomecasesitiseasiertomanageasingledatabasewhichcontainsboththepasswordandgroupdetailsforeachuser.Thissimplifiesanysupportprogramsthatneedtobewritten:theynowonlyhavetodealwithwritingtoandlockingasingleDBMfile.ThiscanbeaccomplishedbyfirstsettingthegroupandpasswordfilestopointtothesameDBM:

AuthDBMGroupFile/www/userbase

AuthDBMUserFile/www/userbase

ThekeyforthesingleDBMistheusername.Thevalueconsistsof

UnixCrypt-edPassword:ListofGroups[:(ignored)]

Thepasswordsectioncontainstheencryptedpasswordasbefore.Thisisfollowedbyacolonandthecommaseparatedlistofgroups.OtherdatamayoptionallybeleftintheDBMfileafteranothercolon;itisignoredbytheauthenticationmodule.Thisiswhatwww.telescope.orgusesforitscombinedpasswordandgroupdatabase.

AuthDBMTypeDirective

Description: Setsthetypeofdatabasefilethatisusedtostorepasswords

Syntax: AuthDBMType

default|SDBM|GDBM|NDBM|DB

Default: AuthDBMTypedefault

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_dbmCompatibility: Availableinversion2.0.30andlater.

Setsthetypeofdatabasefilethatisusedtostorethepasswords.Thedefaultdatabasetypeisdeterminedatcompiletime.Theavailabilityofothertypesofdatabasefilesalsodependsoncompile-timesettings.

Itiscrucialthatwhateverprogramyouusetocreateyourpasswordfilesisconfiguredtousethesametypeofdatabase.

AuthDBMUserFileDirective

Description: Setsthenameofadatabasefilecontainingthelistofusersandpasswordsforauthentication

Syntax: AuthDBMUserFilefile-path

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_auth_dbm

TheAuthDBMUserFiledirectivesetsthenameofaDBMfilecontainingthelistofusersandpasswordsforuserauthentication.File-pathistheabsolutepathtotheuserfile.

Theuserfileiskeyedontheusername.Thevalueforauseristheencryptedpassword,optionallyfollowedbyacolonandarbitrarydata.Thecolonandthedatafollowingitwillbeignoredbytheserver.

Security:

MakesurethattheAuthDBMUserFileisstoredoutsidethedocumenttreeoftheweb-server;donotputitinthedirectorythatitprotects.Otherwise,clientswillbeabletodownloadtheAuthDBMUserFile.

Importantcompatibilitynote:Theimplementationof"dbmopen"intheapachemodulesreadsthestringlengthofthehashedvaluesfromtheDBMdatastructures,ratherthanrelyinguponthestringbeingNULL-appended.Someapplications,suchastheNetscapewebserver,relyuponthestringbeingNULL-appended,soifyouarehavingtroubleusingDBMfilesinterchangeablybetweenapplicationsthismaybeapartoftheproblem.

AperlscriptcalleddbmmanageisincludedwithApache.This

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

programcanbeusedtocreateandupdateDBMformatpasswordfilesforusewiththismodule.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_auth_digest

Description: UserauthenticationusingMD5DigestAuthentication.

Status: ExperimentalModuleIdentifier: auth_digest_moduleSourceFile: mod_auth_digest.c

SummaryThismoduleimplementsHTTPDigestAuthentication.However,ithasnotbeenextensivelytestedandisthereforemarkedexperimental.

SeealsoAuthName

AuthType

Require

Satisfy

UsingDigestAuthentication

UsingMD5Digestauthenticationisverysimple.Simplysetupauthenticationnormally,usingAuthTypeDigestandAuthDigestFileinsteadofthenormalAuthTypeBasicandAuthUserFile;also,replaceanyAuthGroupFilewithAuthDigestGroupFile.ThenaddaAuthDigestDomaindirectivecontainingatleasttherootURI(s)forthisprotectionspace.

Appropriateuser(text)filescanbecreatedusingthehtdigesttool.

Example:<Location/private/>

AuthTypeDigest

AuthName"privatearea"

AuthDigestDomain/private/http://mirror.my.dom/private2/

AuthDigestFile/web/auth/.digest_pw

Requirevalid-user

</Location>

Note

DigestauthenticationprovidesamoresecurepasswordsystemthanBasicauthentication,butonlyworkswithsupportingbrowsers.AsofNovember2002,themajorbrowsersthatsupportdigestauthenticationareOpera,MSInternetExplorer(failswhenusedwithaquerystring-see"WorkingwithMSInternetExplorer"belowforaworkaround),Amaya,MozillaandNetscapesinceversion7.Sincedigestauthenticationisnotaswidelyimplementedasbasicauthentication,youshoulduseitonlyincontrolledenvironments.

WorkingwithMSInternetExplorer

TheDigestauthenticationimplementationinpreviousInternetExplorerforWindowsversions(5and6)hadissues,namelythatGETrequestswithaquerystringwerenotRFCcompliant.Thereareafewwaystoworkaroundthisissue.

ThefirstwayistousePOSTrequestsinsteadofGETrequeststopassdatatoyourprogram.Thismethodisthesimplestapproachifyourapplicationcanworkwiththislimitation.

Sinceversion2.0.51ApachealsoprovidesaworkaroundintheAuthDigestEnableQueryStringHackenvironmentvariable.IfAuthDigestEnableQueryStringHackissetfortherequest,ApachewilltakestepstoworkaroundtheMSIEbugandremovethequerystringfromthedigestcomparison.Usingthismethodwouldlooksimilartothefollowing.

UsingDigestAuthenticationwithMSIE:BrowserMatch"MSIE"AuthDigestEnableQueryStringHack=On

ThisworkaroundisnotnecessaryforMSIE7,thoughenablingitdoesnotcauseanycompatibilityissuesorsignificantoverhead.

SeetheBrowserMatchdirectiveformoredetailsonconditionallysettingenvironmentvariables

AuthDigestAlgorithmDirective

Description: Selectsthealgorithmusedtocalculatethechallengeandresponsehasesindigestauthentication

Syntax: AuthDigestAlgorithmMD5|MD5-sess

Default: AuthDigestAlgorithmMD5

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_digest

TheAuthDigestAlgorithmdirectiveselectsthealgorithmusedtocalculatethechallengeandresponsehashes.

MD5-sessisnotcorrectlyimplementedyet.

AuthDigestDomainDirective

Description: URIsthatareinthesameprotectionspacefordigestauthentication

Syntax: AuthDigestDomainURI[URI]...

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_digest

TheAuthDigestDomaindirectiveallowsyoutospecifyoneormoreURIswhichareinthesameprotectionspace(i.e.usethesamerealmandusername/passwordinfo).ThespecifiedURIsareprefixes,i.e.theclientwillassumethatallURIs"below"thesearealsoprotectedbythesameusername/password.TheURIsmaybeeitherabsoluteURIs(i.e.includingascheme,host,port,etc)orrelativeURIs.

Thisdirectiveshouldalwaysbespecifiedandcontainatleastthe(setof)rootURI(s)forthisspace.OmittingtodosowillcausetheclienttosendtheAuthorizationheaderforeveryrequestsenttothisserver.Apartfromincreasingthesizeoftherequest,itmayalsohaveadetrimentaleffectonperformanceifAuthDigestNcCheckison.

TheURIsspecifiedcanalsopointtodifferentservers,inwhichcaseclients(whichunderstandthis)willthenshareusername/passwordinfoacrossmultipleserverswithoutpromptingtheusereachtime.

AuthDigestFileDirective

Description: Locationofthetextfilecontainingthelistofusersandencodedpasswordsfordigestauthentication

Syntax: AuthDigestFilefile-path

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_digest

TheAuthDigestFiledirectivesetsthenameofatextualfilecontainingthelistofusersandencodedpasswordsfordigestauthentication.File-pathistheabsolutepathtotheuserfile.

Thedigestfileusesaspecialformat.Filesinthisformatcanbecreatedusingthehtdigestutilityfoundinthesupport/subdirectoryoftheApachedistribution.

AuthDigestGroupFileDirective

Description: Nameofthetextfilecontainingthelistofgroupsfordigestauthentication

Syntax: AuthDigestGroupFilefile-path

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_digest

TheAuthDigestGroupFiledirectivesetsthenameofatextualfilecontainingthelistofgroupsandtheirmembers(usernames).File-pathistheabsolutepathtothegroupfile.

Eachlineofthegroupfilecontainsagroupnamefollowedbyacolon,followedbythememberusernamesseparatedbyspaces.Example:

mygroup:bobjoeanne

Notethatsearchinglargetextfilesisveryinefficient.

Security:

MakesurethattheAuthGroupFileisstoredoutsidethedocumenttreeoftheweb-server;donotputitinthedirectorythatitprotects.Otherwise,clientsmaybeabletodownloadtheAuthGroupFile.

AuthDigestNcCheckDirective

Description: Enablesordisablescheckingofthenonce-countsentbytheserver

Syntax: AuthDigestNcCheckOn|Off

Default: AuthDigestNcCheckOff

Context: serverconfigStatus: ExperimentalModule: mod_auth_digest

Notimplementedyet.

AuthDigestNonceFormatDirective

Description: DetermineshowthenonceisgeneratedSyntax: AuthDigestNonceFormatformat

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_digest

Notimplementedyet.

AuthDigestNonceLifetimeDirective

Description: HowlongtheservernonceisvalidSyntax: AuthDigestNonceLifetimeseconds

Default: AuthDigestNonceLifetime300

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_digest

TheAuthDigestNonceLifetimedirectivecontrolshowlongtheservernonceisvalid.Whentheclientcontactstheserverusinganexpirednoncetheserverwillsendbacka401withstale=true.Ifsecondsisgreaterthan0thenitspecifiestheamountoftimeforwhichthenonceisvalid;thisshouldprobablyneverbesettolessthan10seconds.Ifsecondsislessthan0thenthenonceneverexpires.

AuthDigestQopDirective

Description: Determinesthequality-of-protectiontouseindigestauthentication

Syntax: AuthDigestQopnone|auth|auth-int

[auth|auth-int]

Default: AuthDigestQopauth

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_digest

TheAuthDigestQopdirectivedeterminesthequality-of-protectiontouse.authwillonlydoauthentication(username/password);auth-intisauthenticationplusintegritychecking(anMD5hashoftheentityisalsocomputedandchecked);nonewillcausethemoduletousetheoldRFC-2069digestalgorithm(whichdoesnotincludeintegritychecking).Bothauthandauth-intmaybespecified,inwhichthecasethebrowserwillchoosewhichofthesetouse.noneshouldonlybeusedifthebrowserforsomereasondoesnotlikethechallengeitreceivesotherwise.

auth-intisnotimplementedyet.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

AuthDigestShmemSizeDirective

Description: Theamountofsharedmemorytoallocateforkeepingtrackofclients

Syntax: AuthDigestShmemSizesize

Default: AuthDigestShmemSize1000

Context: serverconfigStatus: ExperimentalModule: mod_auth_digest

TheAuthDigestShmemSizedirectivedefinestheamountofsharedmemory,thatwillbeallocatedattheserverstartupforkeepingtrackofclients.Notethatthesharedmemorysegmentcannotbesetlessthanthespacethatisneccessaryfortrackingatleastoneclient.Thisvalueisdependantonyoursystem.Ifyouwanttofindouttheexactvalue,youmaysimplysetAuthDigestShmemSizetothevalueof0andreadtheerrormessageaftertryingtostarttheserver.

ThesizeisnormallyexpressedinBytes,butyoumayletthenumberfollowaKoranMtoexpressyourvalueasKBytesorMBytes.Forexample,thefollowingdirectivesareallequivalent:

AuthDigestShmemSize1048576

AuthDigestShmemSize1024K

AuthDigestShmemSize1M

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_auth_ldap

Description: AllowsanLDAPdirectorytobeusedtostorethedatabaseforHTTPBasicauthentication.

Status: ExperimentalModuleIdentifier: auth_ldap_moduleSourceFile: mod_auth_ldap.cCompatibility: Availableinversion2.0.41andlater

Summarymod_auth_ldapsupportsthefollowingfeatures:

KnowntosupporttheOpenLDAPSDK(both1.xand2.x),NovellLDAPSDKandtheiPlanet(Netscape)SDK.ComplexauthorizationpoliciescanbeimplementedbyrepresentingthepolicywithLDAPfilters.SupportforMicrosoftFrontPageallowsFrontPageuserstocontrolaccesstotheirwebs,whileretainingLDAPforuserauthentication.UsesextensivecachingofLDAPoperationsviamod_ldap.SupportforLDAPoverSSL(requirestheNetscapeSDK)orTLS(requirestheOpenLDAP2.xSDKorNovellLDAPSDK).

Seealsomod_ldap

Contents

OperationTheAuthenticationPhaseTheAuthorizationPhase

TheRequireDirectivesRequirevalid-userRequireuserRequiregroupRequirednRequireldap-attribute

ExamplesUsingTLSUsingSSLUsingMicrosoftFrontPagewithmod_auth_ldap

HowItWorksCaveats

Operation

Therearetwophasesingrantingaccesstoauser.Thefirstphaseisauthentication,inwhichmod_auth_ldapverifiesthattheuser'scredentialsarevalid.Thisalsocalledthesearch/bindphase.Thesecondphaseisauthorization,inwhichmod_auth_ldapdeterminesiftheauthenticateduserisallowedaccesstotheresourceinquestion.Thisisalsoknownasthecomparephase.

TheAuthenticationPhaseDuringtheauthenticationphase,mod_auth_ldapsearchesforanentryinthedirectorythatmatchestheusernamethattheHTTPclientpasses.Ifasingleuniquematchisfound,thenmod_auth_ldapattemptstobindtothedirectoryserverusingtheDNoftheentryplusthepasswordprovidedbytheHTTPclient.Becauseitdoesasearch,thenabind,itisoftenreferredtoasthesearch/bindphase.Herearethestepstakenduringthesearch/bindphase.

1. GenerateasearchfilterbycombiningtheattributeandfilterprovidedintheAuthLDAPURLdirectivewiththeusernamepassedbytheHTTPclient.

2. Searchthedirectoryusingthegeneratedfilter.Ifthesearchdoesnotreturnexactlyoneentry,denyordeclineaccess.

3. FetchthedistinguishednameoftheentryretrievedfromthesearchandattempttobindtotheLDAPserverusingtheDNandthepasswordpassedbytheHTTPclient.Ifthebindisunsuccessful,denyordeclineaccess.

Thefollowingdirectivesareusedduringthesearch/bindphase

AuthLDAPURL SpecifiestheLDAPserver,thebaseDN,theattributetouseinthesearch,aswellastheextrasearchfilterto

use.AuthLDAPBindDN AnoptionalDNtobindwithduring

thesearchphase.AuthLDAPBindPassword Anoptionalpasswordtobindwith

duringthesearchphase.

TheAuthorizationPhaseDuringtheauthorizationphase,mod_auth_ldapattemptstodetermineiftheuserisauthorizedtoaccesstheresource.Manyofthesechecksrequiremod_auth_ldaptodoacompareoperationontheLDAPserver.Thisiswhythisphaseisoftenreferredtoasthecomparephase.mod_auth_ldapacceptsthefollowingRequiredirectivestodetermineifthecredentialsareacceptable:

GrantaccessifthereisaRequirevalid-userdirective.GrantaccessifthereisaRequireuserdirective,andtheusernameinthedirectivematchestheusernamepassedbytheclient.GrantaccessifthereisaRequiredndirective,andtheDNinthedirectivematchestheDNfetchedfromtheLDAPdirectory.GrantaccessifthereisaRequiregroupdirective,andtheDNfetchedfromtheLDAPdirectory(ortheusernamepassedbytheclient)occursintheLDAPgroup.GrantaccessifthereisaRequireldap-attributedirective,andtheattributefetchedfromtheLDAPdirectorymatchesthegivenvalue.otherwise,denyordeclineaccess

mod_auth_ldapusesthefollowingdirectivesduringthecomparephase:

AuthLDAPURL Theattributespecifiedinthe

URLisusedincompareoperationsfortheRequireuseroperation.

AuthLDAPCompareDNOnServer DeterminesthebehavioroftheRequiredndirective.

AuthLDAPGroupAttribute DeterminestheattributetouseforcomparisonsintheRequiregroupdirective.

AuthLDAPGroupAttributeIsDN SpecifieswhethertousetheuserDNortheusernamewhendoingcomparisonsfortheRequiregroupdirective.

TheRequireDirectives

Apache'sRequiredirectivesareusedduringtheauthorizationphasetoensurethatauserisallowedtoaccessaresource.

Requirevalid-userIfthisdirectiveexists,mod_auth_ldapgrantsaccesstoanyuserthathassuccessfullyauthenticatedduringthesearch/bindphase.

RequireuserTheRequireuserdirectivespecifieswhatusernamescanaccesstheresource.Oncemod_auth_ldaphasretrievedauniqueDNfromthedirectory,itdoesanLDAPcompareoperationusingtheusernamespecifiedintheRequireusertoseeifthatusernameispartofthejust-fetchedLDAPentry.Multipleuserscanbegrantedaccessbyputtingmultipleusernamesontheline,separatedwithspaces.Ifausernamehasaspaceinit,thenitmustbesurroundedwithdoublequotes.MultipleuserscanalsobegrantedaccessbyusingmultipleRequireuserdirectives,withoneuserperline.Forexample,withaAuthLDAPURLofldap://ldap/o=Airius?cn(i.e.,cnisusedforsearches),thefollowingRequiredirectivescouldbeusedtorestrictaccess:

Requireuser"BarbaraJenson"

Requireuser"FredUser"

Requireuser"JoeManager"

Becauseofthewaythatmod_auth_ldaphandlesthisdirective,BarbaraJensoncouldsignonasBarbaraJenson,BabsJensonoranyothercnthatshehasinherLDAPentry.OnlythesingleRequireuserlineisneededtosupportallvaluesoftheattributeintheuser'sentry.

IftheuidattributewasusedinsteadofthecnattributeintheURL

above,theabovethreelinescouldbecondensedto

Requireuserbjensonfuserjmanager

RequiregroupThisdirectivespecifiesanLDAPgroupwhosemembersareallowedaccess.IttakesthedistinguishednameoftheLDAPgroup.Note:Donotsurroundthegroupnamewithquotes.Forexample,assumethatthefollowingentryexistedintheLDAPdirectory:

dn:cn=Administrators,o=Airius

objectClass:groupOfUniqueNames

uniqueMember:cn=BarbaraJenson,o=Airius

uniqueMember:cn=FredUser,o=Airius

ThefollowingdirectivewouldgrantaccesstobothFredandBarbara:

Requiregroupcn=Administrators,o=Airius

BehaviorofthisdirectiveismodifiedbytheAuthLDAPGroupAttributeandAuthLDAPGroupAttributeIsDNdirectives.

RequirednTheRequiredndirectiveallowstheadministratortograntaccessbasedondistinguishednames.ItspecifiesaDNthatmustmatchforaccesstobegranted.IfthedistinguishednamethatwasretrievedfromthedirectoryservermatchesthedistinguishednameintheRequiredn,thenauthorizationisgranted.Note:donotsurroundthedistinguishednamewithquotes.

ThefollowingdirectivewouldgrantaccesstoaspecificDN:

Requiredncn=BarbaraJenson,o=Airius

BehaviorofthisdirectiveismodifiedbytheAuthLDAPCompareDNOnServerdirective.

Requireldap-attributeTheRequireldap-attributedirectiveallowstheadministratortograntaccessbasedonattributesoftheauthenticateduserintheLDAPdirectory.Iftheattributeinthedirectorymatchesthevaluegivenintheconfiguration,accessisgranted.

ThefollowingdirectivewouldgrantaccesstoanyonewiththeattributeemployeeType=active

Requireldap-attributeemployeeType=active

Multipleattribute/valuepairscanbespecifiedonthesamelineseparatedbyspacesortheycanbespecifiedinmultipleRequireldap-attributedirectives.Theeffectoflistingmultipleattribute/valuespairsisanORoperation.Accesswillbegrantedifanyofthelistedattributevaluesmatchthevalueofacorrespondingattributeintheuserobject.Ifthevalueoftheattributecontainsaspace,onlythevaluemustbewithindoublequotes.

Thefollowingdirectivewouldgrantaccesstoanyonewiththecityattributeequalto"SanJose"orstatusequalto"Active"

Requireldap-attributecity="SanJose"status=active

Examples

GrantaccesstoanyonewhoexistsintheLDAPdirectory,usingtheirUIDforsearches.

AuthLDAPURL"ldap://ldap1.airius.com:389/ou=People,

o=Airius?uid?sub?(objectClass=*)"

Requirevalid-user

Thenextexampleisthesameasabove;butwiththefieldsthathaveusefuldefaultsomitted.Also,notetheuseofaredundantLDAPserver.

AuthLDAPURL"ldap://ldap1.airius.com

ldap2.airius.com/ou=People,o=Airius"

Requirevalid-user

Thenextexampleissimilartothepreviousone,butisusesthecommonnameinsteadoftheUID.Notethatthiscouldbeproblematicalifmultiplepeopleinthedirectorysharethesamecn,becauseasearchoncnmustreturnexactlyoneentry.That'swhythisapproachisnotrecommended:it'sabetterideatochooseanattributethatisguaranteeduniqueinyourdirectory,suchasuid.

AuthLDAPURL"ldap://ldap.airius.com/ou=People,o=Airius?

cn"

Requirevalid-user

GrantaccesstoanybodyintheAdministratorsgroup.TheusersmustauthenticateusingtheirUID.

AuthLDAPURLldap://ldap.airius.com/o=Airius?uid

Requiregroupcn=Administrators,o=Airius

ThenextexampleassumesthateveryoneatAiriuswhocarriesanalphanumericpagerwillhaveanLDAPattributeof

qpagePagerID.Theexamplewillgrantaccessonlytopeople(authenticatedviatheirUID)whohavealphanumericpagers:

AuthLDAPURLldap://ldap.airius.com/o=Airius?uid??

(qpagePagerID=*)

Requirevalid-user

Thenextexampledemonstratesthepowerofusingfilterstoaccomplishcomplicatedadministrativerequirements.Withoutfilters,itwouldhavebeennecessarytocreateanewLDAPgroupandensurethatthegroup'smembersremainsynchronizedwiththepagerusers.Thisbecomestrivialwithfilters.Thegoalistograntaccesstoanyonewhohasafilter,plusgrantaccesstoJoeManager,whodoesn'thaveapager,butdoesneedtoaccessthesameresource:

AuthLDAPURLldap://ldap.airius.com/o=Airius?uid??(|

(qpagePagerID=*)(uid=jmanager))

Requirevalid-user

Thislastmaylookconfusingatfirst,soithelpstoevaluatewhatthesearchfilterwilllooklikebasedonwhoconnects,asshownbelow.ThetextinblueisthepartthatisfilledinusingtheattributespecifiedintheURL.ThetextinredisthepartthatisfilledinusingthefilterspecifiedintheURL.ThetextingreenisfilledinusingtheinformationthatisretrievedfromtheHTTPclient.IfFredUserconnectsasfuser,thefilterwouldlooklike

(&(|(qpagePagerID=*)(uid=jmanager))(uid=fuser))

Theabovesearchwillonlysucceediffuserhasapager.WhenJoeManagerconnectsasjmanager,thefilterlookslike

(&(|(qpagePagerID=*)(uid=jmanager))(uid=jmanager))

Theabovesearchwillsucceedwhetherjmanagerhasapagerornot.

UsingTLS

TouseTLS,seethemod_ldapdirectivesLDAPTrustedCAandLDAPTrustedCAType.

UsingSSL

TouseSSL,seethemod_ldapdirectivesLDAPTrustedCAandLDAPTrustedCAType.

TospecifyasecureLDAPserver,useldaps://intheAuthLDAPURLdirective,insteadofldap://.

UsingMicrosoftFrontPagewithmod_auth_ldap

Normally,FrontPageusesFrontPage-web-specificuser/groupfiles(i.e.,themod_authmodule)tohandleallauthentication.Unfortunately,itisnotpossibletojustchangetoLDAPauthenticationbyaddingtheproperdirectives,becauseitwillbreakthePermissionsformsintheFrontPageclient,whichattempttomodifythestandardtext-basedauthorizationfiles.

OnceaFrontPagewebhasbeencreated,addingLDAPauthenticationtoitisamatterofaddingthefollowingdirectivestoevery.htaccessfilethatgetscreatedintheweb

AuthLDAPURL"theurl"

AuthLDAPAuthoritativeoff

AuthLDAPFrontPageHackon

AuthLDAPAuthoritativemustbeofftoallowmod_auth_ldaptodeclinegroupauthenticationsothatApachewillfallbacktofileauthenticationforcheckinggroupmembership.ThisallowstheFrontPage-managedgroupfiletobeused.

HowItWorksFrontPagerestrictsaccesstoawebbyaddingtheRequirevalid-userdirectivetothe.htaccessfiles.IfAuthLDAPFrontPageHackisnoton,theRequirevalid-userdirectivewillsucceedforanyuserwhoisvalidasfarasLDAPisconcerned.ThismeansthatanybodywhohasanentryintheLDAPdirectoryisconsideredavaliduser,whereasFrontPageconsidersonlythosepeopleinthelocaluserfiletobevalid.ThepurposeofthehackistoforceApachetoconsultthelocaluserfile(whichismanagedbyFrontPage)-insteadofLDAP-whenhandlingtheRequirevalid-userdirective.

Oncedirectiveshavebeenaddedasspecifiedabove,FrontPage

userswillbeabletoperformallmanagementoperationsfromtheFrontPageclient.

CaveatsWhenchoosingtheLDAPURL,theattributetouseforauthenticationshouldbesomethingthatwillalsobevalidforputtingintoamod_authuserfile.TheuserIDisidealforthis.WhenaddingusersviaFrontPage,FrontPageadministratorsshouldchooseusernamesthatalreadyexistintheLDAPdirectory(forobviousreasons).Also,thepasswordthattheadministratorentersintotheformisignored,sinceApachewillactuallybeauthenticatingagainstthepasswordintheLDAPdatabase,andnotagainstthepasswordinthelocaluserfile.Thiscouldcauseconfusionforwebadministrators.Apachemustbecompiledwithmod_authinordertouseFrontPagesupport.ThisisbecauseApachewillstillusethemod_authgroupfilefordeterminetheextentofauser'saccesstotheFrontPageweb.Thedirectivesmustbeputinthe.htaccessfiles.Attemptingtoputtheminside<Location>or<Directory>directiveswon'twork.Thisisbecausemod_auth_ldaphastobeabletograbtheAuthUserFiledirectivethatisfoundinFrontPage.htaccessfilessothatitknowswheretolookforthevaliduserlist.Ifthemod_auth_ldapdirectivesaren'tinthesame.htaccessfileastheFrontPagedirectives,thenthehackwon'twork,becausemod_auth_ldapwillnevergetachancetoprocessthe.htaccessfile,andwon'tbeabletofindtheFrontPage-manageduserfile.

AuthLDAPAuthoritativeDirective

Description: Preventotherauthenticationmodulesfromauthenticatingtheuserifthisonefails

Syntax: AuthLDAPAuthoritativeon|off

Default: AuthLDAPAuthoritativeon

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

Settooffifthismoduleshouldletotherauthenticationmodulesattempttoauthenticatetheuser,shouldauthenticationwiththismodulefail.ControlisonlypassedontolowermodulesifthereisnoDNorrulethatmatchesthesuppliedusername(aspassedbytheclient).

AuthLDAPBindDNDirective

Description: OptionalDNtouseinbindingtotheLDAPserverSyntax: AuthLDAPBindDNdistinguished-name

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

AnoptionalDNusedtobindtotheserverwhensearchingforentries.Ifnotprovided,mod_auth_ldapwilluseananonymousbind.

AuthLDAPBindPasswordDirective

Description: PasswordusedinconjuctionwiththebindDNSyntax: AuthLDAPBindPasswordpassword

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

AbindpasswordtouseinconjunctionwiththebindDN.Notethatthebindpasswordisprobablysensitivedata,andshouldbeproperlyprotected.YoushouldonlyusetheAuthLDAPBindDNandAuthLDAPBindPasswordifyouabsolutelyneedthemtosearchthedirectory.

AuthLDAPCharsetConfigDirective

Description: LanguagetocharsetconversionconfigurationfileSyntax: AuthLDAPCharsetConfigfile-path

Context: serverconfigStatus: ExperimentalModule: mod_auth_ldap

TheAuthLDAPCharsetConfigdirectivesetsthelocationofthelanguagetocharsetconversionconfigurationfile.File-pathisrelativetotheServerRoot.Thisfilespecifiesthelistoflanguageextensionstocharactersets.Mostadministratorsusetheprovidedcharset.convfile,whichassociatescommonlanguageextensionstocharactersets.

Thefilecontainslinesinthefollowingformat:

Language-Extensioncharset[Language-String]...

Thecaseoftheextensiondoesnotmatter.Blanklines,andlinesbeginningwithahashcharacter(#)areignored.

AuthLDAPCompareDNOnServerDirective

Description: UsetheLDAPservertocomparetheDNsSyntax: AuthLDAPCompareDNOnServeron|off

Default: AuthLDAPCompareDNOnServeron

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

Whenset,mod_auth_ldapwillusetheLDAPservertocomparetheDNs.ThisistheonlyfoolproofwaytocompareDNs.mod_auth_ldapwillsearchthedirectoryfortheDNspecifiedwiththeRequiredndirective,then,retrievetheDNandcompareitwiththeDNretrievedfromtheuserentry.Ifthisdirectiveisnotset,mod_auth_ldapsimplydoesastringcomparison.Itispossibletogetfalsenegativeswiththisapproach,butitismuchfaster.Notethemod_ldapcachecanspeedupDNcomparisoninmostsituations.

AuthLDAPDereferenceAliasesDirective

Description: Whenwillthemodulede-referencealiasesSyntax: AuthLDAPDereferenceAliases

never|searching|finding|always

Default: AuthLDAPDereferenceAliasesAlways

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

Thisdirectivespecifieswhenmod_auth_ldapwillde-referencealiasesduringLDAPoperations.Thedefaultisalways.

AuthLDAPEnabledDirective

Description: TurnonoroffLDAPauthenticationSyntax: AuthLDAPEnabledon|off

Default: AuthLDAPEnabledon

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

Settoofftodisablemod_auth_ldapincertaindirectories.Thisisusefulifyouhavemod_auth_ldapenabledatornearthetopofyourtree,butwanttodisableitcompletelyincertainlocations.

AuthLDAPFrontPageHackDirective

Description: AllowLDAPauthenticationtoworkwithMSFrontPage

Syntax: AuthLDAPFrontPageHackon|off

Default: AuthLDAPFrontPageHackoff

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

SeethesectiononusingMicrosoftFrontPagewithmod_auth_ldap.

AuthLDAPGroupAttributeDirective

Description: LDAPattributesusedtocheckforgroupmembership

Syntax: AuthLDAPGroupAttributeattribute

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

ThisdirectivespecifieswhichLDAPattributesareusedtocheckforgroupmembership.Multipleattributescanbeusedbyspecifyingthisdirectivemultipletimes.Ifnotspecified,thenmod_auth_ldapusesthememberanduniquememberattributes.

AuthLDAPGroupAttributeIsDNDirective

Description: UsetheDNoftheclientusernamewhencheckingforgroupmembership

Syntax: AuthLDAPGroupAttributeIsDNon|off

Default: AuthLDAPGroupAttributeIsDNon

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

Whenseton,thisdirectivesaystousethedistinguishednameoftheclientusernamewhencheckingforgroupmembership.Otherwise,theusernamewillbeused.Forexample,assumethattheclientsenttheusernamebjenson,whichcorrespondstotheLDAPDNcn=BabsJenson,o=Airius.Ifthisdirectiveisset,mod_auth_ldapwillcheckifthegrouphascn=BabsJenson,o=Airiusasamember.Ifthisdirectiveisnotset,thenmod_auth_ldapwillcheckifthegrouphasbjensonasamember.

AuthLDAPRemoteUserIsDNDirective

Description: UsetheDNoftheclientusernametosettheREMOTE_USERenvironmentvariable

Syntax: AuthLDAPRemoteUserIsDNon|off

Default: AuthLDAPRemoteUserIsDNoff

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

Ifthisdirectiveissettoon,thevalueoftheREMOTE_USERenvironmentvariablewillbesettothefulldistinguishednameoftheauthenticateduser,ratherthanjusttheusernamethatwaspassedbytheclient.Itisturnedoffbydefault.

AuthLDAPUrlDirective

Description: URLspecifyingtheLDAPsearchparametersSyntax: AuthLDAPUrlurl

Context: directory,.htaccessOverride: AuthConfigStatus: ExperimentalModule: mod_auth_ldap

AnRFC2255URLwhichspecifiestheLDAPsearchparameterstouse.ThesyntaxoftheURLis

ldap://host:port/basedn?attribute?scope?filter

ldapForregularldap,usethestringldap.ForsecureLDAP,useldapsinstead.SecureLDAPisonlyavailableifApachewaslinkedtoanLDAPlibrarywithSSLsupport.

host:portThename/portoftheldapserver(defaultstolocalhost:389forldap,andlocalhost:636forldaps).Tospecifymultiple,redundantLDAPservers,justlistallservers,separatedbyspaces.mod_auth_ldapwilltryconnectingtoeachserverinturn,untilitmakesasuccessfulconnection.

Onceaconnectionhasbeenmadetoaserver,thatconnectionremainsactiveforthelifeofthehttpdprocess,oruntiltheLDAPservergoesdown.

IftheLDAPservergoesdownandbreaksanexistingconnection,mod_auth_ldapwillattempttore-connect,startingwiththeprimaryserver,andtryingeachredundantserverinturn.Notethatthisisdifferentthanatrueround-

robinsearch.

basednTheDNofthebranchofthedirectorywhereallsearchesshouldstartfrom.Attheveryleast,thismustbethetopofyourdirectorytree,butcouldalsospecifyasubtreeinthedirectory.

attributeTheattributetosearchfor.AlthoughRFC2255allowsacomma-separatedlistofattributes,onlythefirstattributewillbeused,nomatterhowmanyareprovided.Ifnoattributesareprovided,thedefaultistouseuid.It'sagoodideatochooseanattributethatwillbeuniqueacrossallentriesinthesubtreeyouwillbeusing.

scopeThescopeofthesearch.Canbeeitheroneorsub.NotethatascopeofbaseisalsosupportedbyRFC2255,butisnotsupportedbythismodule.Ifthescopeisnotprovided,orifbasescopeisspecified,thedefaultistouseascopeofsub.

filterAvalidLDAPsearchfilter.Ifnotprovided,defaultsto(objectClass=*),whichwillsearchforallobjectsinthetree.Filtersarelimitedtoapproximately8000characters(thedefinitionofMAX_STRING_LENintheApachesourcecode).Thisshouldbethansufficientforanyapplication.

Whendoingsearches,theattribute,filterandusernamepassedbytheHTTPclientarecombinedtocreateasearchfilterthatlookslike(&(filter)(attribute=username)).

Forexample,consideranURLofldap://ldap.airius.com/o=Airius?cn?sub?

(posixid=*).Whenaclientattemptstoconnectusinga

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

usernameofBabsJenson,theresultingsearchfilterwillbe(&(posixid=*)(cn=BabsJenson)).

SeeaboveforexamplesofAuthLDAPURLURLs.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_autoindex

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: Unix ls Win32dir

: Base: autoindex_module: mod_autoindex.c

:

index.html DirectoryIndex

AddIconByType

()

Options+Indexes Options

FancyIndexing IndexOptionsIndexOptions SuppressColumnSorting

"Size" -

Autoindex

Apache2.0.23

C=NC=MC=SC=D

O=AO=D

F=0 (FancyIndex)F=1FancyIndexF=2HTML FancyIndexV=0V=1

P=pattern pattern

"P(P)" IndexIgnoremod_autoindex()

HEADER.html

<formaction=""method="get">

Showmea<selectname="F">

<optionvalue="0">Plainlist</option>

<optionvalue="1"selected="selected">Fancylist</option>

<optionvalue="2">Tablelist</option>

</select>

Sortedby<selectname="C">

<optionvalue="N"selected="selected">Name</option>

<optionvalue="M">DateModified</option>

<optionvalue="S">Size</option>

<optionvalue="D">Description</option>

</select>

<selectname="O">

<optionvalue="A"selected="selected">Ascending</option>

<optionvalue="D">Descending</option>

</select>

<selectname="V">

<optionvalue="0"selected="selected">inNormal

order</option>

<optionvalue="1">inVersionorder</option>

</select>

Matching<inputtype="text"name="P"value="*"/>

<inputtype="submit"name="X"value="Go"/>

</form>

AddAlt

: : AddAltstringfile[file]...

: ,,,.htaccess: Indexes: Base: mod_autoindex

AddAlt FancyIndexing (" ')

AddAlt"PDFfile"*.pdf

AddAltCompressed*.gz*.zip*.Z

AddAltByEncoding

: MIME: AddAltByEncodingstringMIME-encoding[MIME-

encoding]...

: ,,,.htaccess: Indexes: Base: mod_autoindex

AddAltByEncoding FancyIndexingencoding x-compress string( " ')

AddAltByEncodinggzipx-gzip

AddAltByType

: MIME: AddAltByTypestringMIME-type[MIME-type]...

: ,,,.htaccess: Indexes: Base: mod_autoindex

AddAltByType FancyIndexingtext/html string( " ')

AddAltByType'plaintext'text/plain

AddDescription

:: AddDescriptionstringfile[file]...

: ,,,.htaccess: Indexes: Base: mod_autoindex

FancyIndexing file

AddDescription"TheplanetMars"/web/pics/mars.gif

23 IndexOptionsSuppressIcon

IndexOptionsSuppressSize7 IndexOptions

SuppressLastModified19

AddDescription HTML

AddIcon

:: AddIconiconname[name]...

: ,,,.htaccess: Indexes: Base: mod_autoindex

FancyIndexing name(alttext,url) alttext

name ^^DIRECTORY^^ ^^BLANKICON^^()

AddIcon(IMG,/icons/image.xbm).gif.jpg.xbm

AddIcon/icons/dir.xbm^^DIRECTORY^^

AddIcon/icons/backup.xbm*~

AddIcon AddIconByType

AddIconByEncoding

: MIME: AddIconByEncodingiconMIME-encoding[MIME-

encoding]...

: ,,,.htaccess: Indexes: Base: mod_autoindex

FancyIndexing icon(alttext,url) alttext

MIME-encoding

AddIconByEncoding/icons/compress.xbmx-compress

AddIconByType

: MIME: AddIconByTypeiconMIME-type[MIME-type]...

: ,,,.htaccess: Indexes: Base: mod_autoindex

FancyIndexing icon(alttext,url) alttext

MIME-type

AddIconByType(IMG,/icons/image.xbm)image/*

DefaultIcon

: : DefaultIconurl-path

: ,,,.htaccess: Indexes: Base: mod_autoindex

FancyIndexing

DefaultIcon/icon/unknown.xbm

HeaderName

:: HeaderNamefilename

: ,,,.htaccess: Indexes: Base: mod_autoindex

HeaderName

HeaderNameHEADER.html

HeaderName ReadmeName filenameURIfilename DocumentRoot

HeaderName/include/HEADER.html

filename " text/*"(text/html,text/plain CGI

AddTypetext/html.cgi

OptionsMultiViews filenametext/html optionsIncludes IncludesNOEXEC

(mod_include)

HeaderName HTML(<html>,<head>,IndexOptions+SuppressHTMLPreamble

IndexIgnore

: : IndexIgnorefile[file]...

: ,,,.htaccess: Indexes: Base: mod_autoindex

IndexIgnore ()

IndexIgnoreREADME.htaccess*.bak*~

IndexOptions

:: IndexOptions[+|-]option[[+|-]option]...

: ,,,.htaccess: Indexes: Base: mod_autoindex

IndexOptions option:

DescriptionWidth=[n|*](2.0.23)DescriptionWidth-DescriptionWidth() mod_autoindexDescriptionWidth=n nDescriptionWidth=* AddDescription

FancyIndexing

FoldersFirst(2.0.23) Zed Beta Gamma

HTMLTable( Apache2.0.23)FancyIndexing

IconsAreLinksFancyIndexing

IconHeight[=pixels]IconWidth Apache

IconWidth[=pixels]IconHeight

Apache

IgnoreCasegamma)

IgnoreClient mod_autoindex SuppressColumnSorting)

NameWidth=[n|*]NameWidth-NameWidth() mod_autoindexNameWidth=n nNameWidth=*

ScanHTMLTitlesFancyIndexing HTMLhttpd title CPUdisk

SuppressColumnSortingApache FancyIndexing2.0.23 IgnoreClient

SuppressDescriptionFancyIndexing AddDescription DescriptionWidth

SuppressHTMLPreamble HeaderName HTML SuppressHTMLPreamble

SuppressIcon(Apache2.0.23 )FancyIndexing SuppressIcon

HTML3.2 HTML3.2(FancyIndexing)

SuppressLastModifiedFancyIndexing

SuppressRules(Apache2.0.23)( hr) SuppressIcon SuppressRulesHTML3.2 HTML3.2(FancyIndexing)

SuppressSizeFancyIndexing

TrackModified(Apache2.0.23)HTTP ETagOS2JFSWin32NTFS OS2Win32FAT HEAD

VersionSort(Apache2.0a3)VersionSort

:foo-1.7

foo-1.7.2

foo-1.7.12

foo-1.8.2

foo-1.8.2a

foo-1.12

0

foo-1.001

foo-1.002

foo-1.030

foo-1.04

XHTML(Apache2.0.49)XHTML mod_autoindexHTML3.2XHTML1.0

IndexOptions

Apache1.3.3 IndexOptions

IndexOptions

<Directory/foo>

IndexOptionsHTMLTable

IndexOptionsSuppressColumnsorting

</Directory>

IndexOptionsHTMLTableSuppressColumnsorting

('+''-' )

'+''-' IndexOptions

IndexOptions+ScanHTMLTitles-IconsAreLinksFancyIndexing

IndexOptions+SuppressSize

IndexOptionsFancyIndexing+SuppressSize

FancyIndexing

IndexOptions

IndexOrderDefault

:: IndexOrderDefaultAscending|Descending

Name|Date|Size|Description

: IndexOrderDefaultAscendingName

: ,,,.htaccess: Indexes: Base: mod_autoindex

IndexOrderDefault FancyIndexing IndexOrderDefault

IndexOrderDefaultName,Date,Size Description

SuppressColumnSorting

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

ReadmeName

:: ReadmeNamefilename

: ,,,.htaccess: Indexes: Base: mod_autoindex

ReadmeName DocumentRoot

ReadmeNameFOOTER.html

2ReadmeName/include/FOOTER.html

HeaderName

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_cache

Description: ContentcachekeyedtoURIs.Status: ExperimentalModuleIdentifier: cache_moduleSourceFile: mod_cache.c

Summary

Thismoduleisexperimental.Documentationisstillunderdevelopment...

mod_cacheimplementsanRFC2616compliantHTTPcontentcachethatcanbeusedtocacheeitherlocalorproxiedcontent.mod_cacherequirestheservicesofoneormorestoragemanagementmodules.TwostoragemanagementmodulesareincludedinthebaseApachedistribution:

mod_disk_cache

implementsadiskbasedstoragemanager.

mod_mem_cache

implementsamemorybasedstoragemanager.mod_mem_cachecanbeconfiguredtooperateintwomodes:cachingopenfiledescriptorsorcachingobjectsinheapstorage.mod_mem_cachecanbeusedtocachelocallygeneratedcontentortocachebackendservercontentformod_proxywhenconfiguredusingProxyPass(akareverseproxy)

ContentisstoredinandretrievedfromthecacheusingURIbasedkeys.Contentwithaccessprotectionisnotcached.

RelatedModulesandDirectives

RelatedModules RelatedDirectivesmod_disk_cache

mod_mem_cache

CacheRoot

CacheSize

CacheGcInterval

CacheDirLevels

CacheDirLength

CacheExpiryCheck

CacheMinFileSize

CacheMaxFileSize

CacheTimeMargin

CacheGcDaily

CacheGcUnused

CacheGcClean

CacheGcMemUsage

MCacheSize

MCacheMaxObjectCount

MCacheMinObjectSize

MCacheMaxObjectSize

MCacheRemovalAlgorithm

MCacheMaxStreamingBuffer

SampleConfiguration

Samplehttpd.conf#

#SampleCacheConfiguration

#

LoadModulecache_modulemodules/mod_cache.so

<IfModulemod_cache.c>

#LoadModuledisk_cache_modulemodules/mod_disk_cache.so

<IfModulemod_disk_cache.c>

CacheRootc:/cacheroot

CacheSize256

CacheEnabledisk/

CacheDirLevels5

CacheDirLength3

</IfModule>

LoadModulemem_cache_modulemodules/mod_mem_cache.so

<IfModulemod_mem_cache.c>

CacheEnablemem/

MCacheSize4096

MCacheMaxObjectCount100

MCacheMinObjectSize1

MCacheMaxObjectSize2048

</IfModule>

</IfModule>

CacheDefaultExpireDirective

Description: Thedefaultdurationtocacheadocumentwhennoexpirydateisspecified.

Syntax: CacheDefaultExpireseconds

Default: CacheDefaultExpire3600(onehour)

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_cache

TheCacheDefaultExpiredirectivespecifiesadefaulttime,inseconds,tocacheadocumentifneitheranexpirydatenorlast-modifieddateareprovidedwiththedocument.ThevaluespecifiedwiththeCacheMaxExpiredirectivedoesnotoverridethissetting.

CacheDefaultExpire86400

CacheDisableDirective

Description: DisablecachingofspecifiedURLsSyntax: CacheDisableurl-string

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_cache

TheCacheDisabledirectiveinstructsmod_cachetonotcacheurlsatorbelowurl-string.

ExampleCacheDisable/local_files

CacheEnableDirective

Description: EnablecachingofspecifiedURLsusingaspecifiedstoragemanager

Syntax: CacheEnablecache_typeurl-string

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_cache

TheCacheEnabledirectiveinstructsmod_cachetocacheurlsatorbelowurl-string.Thecachestoragemanagerisspecifiedwiththecache_typeargument.cache_typememinstructsmod_cachetousethememorybasedstoragemanagerimplementedbymod_mem_cache.cache_typediskinstructsmod_cachetousethediskbasedstoragemanagerimplementedbymod_disk_cache.cache_typefdinstructsmod_cachetousethefiledescriptorcacheimplementedbymod_mem_cache.

IntheeventthattheURLspaceoverlapsbetweendifferentCacheEnabledirectives(asintheexamplebelow),eachpossiblestoragemanagerwillberununtilthefirstonethatactuallyprocessestherequest.TheorderinwhichthestoragemanagersarerunisdeterminedbytheorderoftheCacheEnabledirectivesintheconfigurationfile.

CacheEnablemem/manual

CacheEnablefd/images

CacheEnabledisk/

CacheForceCompletionDirective

Description: Percentageofdocumentserved,afterwhichtheserverwillcompletecachingthefileeveniftherequestiscancelled.

Syntax: CacheForceCompletionPercentage

Default: CacheForceCompletion60

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_cache

Ordinarily,ifarequestiscancelledwhiletheresponseisbeingcachedanddeliveredtotheclienttheprocessingoftheresponsewillstopandthecacheentrywillberemoved.TheCacheForceCompletiondirectivespecifiesathresholdbeyondwhichthedocumentwillcontinuetobecachedtocompletion,eveniftherequestiscancelled.

Thethresholdisapercentagespecifiedasavaluebetween1and100.Avalueof0specifiesthatthedefaultbeused.Avalueof100willonlycachedocumentsthatareservedintheirentirety.Avaluebetween60and90isrecommended.

CacheForceCompletion80

Note:Thisfeatureiscurrentlynotimplemented.

CacheIgnoreCacheControlDirective

Description: Ignorethefactthattheclientrequestedthecontentnotbecached.

Syntax: CacheIgnoreCacheControlOn|Off

Default: CacheIgnoreCacheControlOff

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_cache

Ordinarily,documentswithno-cacheorno-storeheadervalueswillnotbestoredinthecache.TheCacheIgnoreCacheControldirectiveallowsthisbehaviortobeoverridden.CacheIgnoreCacheControlOntellstheservertoattempttocachethedocumentevenifitcontainsno-cacheorno-storeheadervalues.Documentsrequiringauthorizationwillneverbecached.

CacheIgnoreCacheControlOn

CacheIgnoreHeadersDirective

Description: DonotstorethegivenHTTPheader(s)inthecache.

Syntax: CacheIgnoreHeadersheader-string

[header-string]...

Default: CacheIgnoreHeadersNone

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_cache

AccordingtoRFC2616,hop-by-hopHTTPheadersarenotstoredinthecache.ThefollowingHTTPheadersarehop-by-hopheadersandthusdonotgetstoredinthecacheinanycaseregardlessofthesettingofCacheIgnoreHeaders:

Connection

Keep-Alive

Proxy-Authenticate

Proxy-Authorization

TE

Trailers

Transfer-Encoding

Upgrade

CacheIgnoreHeadersspecifiesadditionalHTTPheadersthatshouldnottobestoredinthecache.Forexample,itmakessenseinsomecasestopreventcookiesfrombeingstoredinthecache.

CacheIgnoreHeaderstakesaspaceseparatedlistofHTTPheadersthatshouldnotbestoredinthecache.Ifonlyhop-by-hopheadersnotshouldbestoredinthecache(theRFC2616compliantbehaviour),CacheIgnoreHeaderscanbesettoNone.

Example1CacheIgnoreHeadersSet-Cookie

Example2CacheIgnoreHeadersNone

Warning:IfheaderslikeExpireswhichareneededforpropercachemanagementarenotstoredduetoaCacheIgnoreHeaderssetting,thebehaviourofmod_cacheisundefined.

CacheIgnoreNoLastModDirective

Description: IgnorethefactthataresponsehasnoLastModifiedheader.

Syntax: CacheIgnoreNoLastModOn|Off

Default: CacheIgnoreNoLastModOff

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_cache

Ordinarily,documentswithoutalast-modifieddatearenotcached.Undersomecircumstancesthelast-modifieddateisremoved(duringmod_includeprocessingforexample)ornotprovidedatall.TheCacheIgnoreNoLastModdirectiveprovidesawaytospecifythatdocumentswithoutlast-modifieddatesshouldbeconsideredforcaching,evenwithoutalast-modifieddate.Ifneitheralast-modifieddatenoranexpirydateareprovidedwiththedocumentthenthevaluespecifiedbytheCacheDefaultExpiredirectivewillbeusedtogenerateanexpirationdate.

CacheIgnoreNoLastModOn

CacheLastModifiedFactorDirective

Description: ThefactorusedtocomputeanexpirydatebasedontheLastModifieddate.

Syntax: CacheLastModifiedFactorfloat

Default: CacheLastModifiedFactor0.1

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_cache

Intheeventthatadocumentdoesnotprovideanexpirydatebutdoesprovidealast-modifieddate,anexpirydatecanbecalculatedbasedonthetimesincethedocumentwaslastmodified.TheCacheLastModifiedFactordirectivespecifiesafactortobeusedinthegenerationofthisexpirydateaccordingtothefollowingformula:expiry-period=time-since-last-modified-date*factorexpiry-date=current-date

+expiry-periodForexample,ifthedocumentwaslastmodified10hoursago,andfactoris0.1thentheexpiry-periodwillbesetto10*0.1=1hour.Ifthecurrenttimewas3:00pmthenthecomputedexpiry-datewouldbe3:00pm+1hour=4:00pm.Iftheexpiry-periodwouldbelongerthanthatsetbyCacheMaxExpire,thenthelattertakesprecedence.

CacheLastModifiedFactor0.5

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

CacheMaxExpireDirective

Description: Themaximumtimeinsecondstocacheadocument

Syntax: CacheMaxExpireseconds

Default: CacheMaxExpire86400(oneday)

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_cache

TheCacheMaxExpiredirectivespecifiesthemaximumnumberofsecondsforwhichcachableHTTPdocumentswillberetainedwithoutcheckingtheoriginserver.Thus,documentswillbeoutofdateatmostthisnumberofseconds.Thismaximumvalueisenforcedevenifanexpirydatewassuppliedwiththedocument.

CacheMaxExpire604800

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_cern_meta

Description: CERNhttpdmetafilesemanticsStatus: ExtensionModuleIdentifier: cern_meta_moduleSourceFile: mod_cern_meta.c

SummaryEmulatetheCERNHTTPDMetafilesemantics.MetafilesareHTTPheadersthatcanbeoutputinadditiontothenormalrangeofheadersforeachfileaccessed.TheyappearratherliketheApache.asisfiles,andareabletoprovideacrudewayofinfluencingtheExpires:header,aswellasprovidingothercuriosities.Therearemanywaystomanagemetainformation,thisonewaschosenbecausethereisalreadyalargenumberofCERNuserswhocanexploitthismodule.

MoreinformationontheCERNmetafilesemanticsisavailable.

Seealsomod_headers

mod_asis

MetaDirDirective

Description: NameofthedirectorytofindCERN-stylemetainformationfiles

Syntax: MetaDirdirectory

Default: MetaDir.web

Context: serverconfig,virtualhost,directory,.htaccessOverride: IndexesStatus: ExtensionModule: mod_cern_meta

SpecifiesthenameofthedirectoryinwhichApachecanfindmetainformationfiles.Thedirectoryisusuallya'hidden'subdirectoryofthedirectorythatcontainsthefilebeingaccessed.Setto"."tolookinthesamedirectoryasthefile:

MetaDir.

Or,tosetittoasubdirectoryofthedirectorycontainingthefiles:

MetaDir.meta

MetaFilesDirective

Description: ActivatesCERNmeta-fileprocessingSyntax: MetaFileson|off

Default: MetaFilesoff

Context: serverconfig,virtualhost,directory,.htaccessOverride: IndexesStatus: ExtensionModule: mod_cern_meta

Turnson/offMetafileprocessingonaper-directorybasis.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

MetaSuffixDirective

Description: FilenamesuffixforthefilecontaingCERN-stylemetainformation

Syntax: MetaSuffixsuffix

Default: MetaSuffix.meta

Context: serverconfig,virtualhost,directory,.htaccessOverride: IndexesStatus: ExtensionModule: mod_cern_meta

Specifiesthefilenamesuffixforthefilecontainingthemetainformation.Forexample,thedefaultvaluesforthetwodirectiveswillcausearequesttoDOCUMENT_ROOT/somedir/index.htmltolookinDOCUMENT_ROOT/somedir/.web/index.html.metaandwilluseitscontentstogenerateadditionalMIMEheaderinformation.

Example:MetaSuffix.meta

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_cgi

: CGI: Base: cgi_module: mod_cgi.c

Mime application/x-httpd-cgi cgi-script

(Apache1.1) CGI ScriptAlias

CGI DOCUMENT_ROOT

ApacheCGI CGI

UnixMPM mod_cgid

AcceptPathInfo

Options

ScriptAlias

AddHandler

CGIIDCGI

CGI

CGI CGI

PATH_INFO AcceptPathInfo off

mod_cgi (URI /more/path/info

NOTFOUND AcceptPathInfo

REMOTE_HOSTHostnameLookups on(off) DNS

REMOTE_IDENTIdentityCheck on ident

REMOTE_USERCGI

CGI

CGI ()

CGICGI CGICGI

%%[time]request-line

%%HTTP-statusCGI-script-filename

CGI 2:

%%error

error-message

()

%request

HTTP

()POSTPUT

%response

CGI

%stdout

CGI

%stderr

CGI

( %stdout%stderr)

ScriptLog

: CGI: ScriptLogfile-path

: ,: Base: mod_cgi,mod_cgid

ScriptLogCGIServerRoot

ScriptLoglogs/cgi_log

User

CGI

ScriptLogBuffer

: PUTPOST: ScriptLogBufferbytes

: ScriptLogBuffer1024

: ,: Base: mod_cgi,mod_cgid

PUTPOST

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

ScriptLogLength

: CGI: ScriptLogLengthbytes

: ScriptLogLength10385760

: ,: Base: mod_cgi,mod_cgid

ScriptLogLengthCGI CGI

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_cgid

: CGICGI

: Base: cgid_module: mod_cgid.c: Unix

MPM

ScriptSock mod_cgid mod_cgiCGI mod_cgi

Unix fork unix

MPM mod_cgiCGI

mod_cgi

CGIID

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

ScriptSock

: CGI: ScriptSockfile-path

: ScriptSocklogs/cgisock

: ,: Base: mod_cgid

CGI Apache(root)

ScriptSock/var/run/cgid.sock

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_charset_lite

Description: SpecifycharactersettranslationorrecodingStatus: ExperimentalModuleIdentifier: charset_lite_moduleSourceFile: mod_charset_lite.c

SummaryThisisanexperimentalmoduleandshouldbeusedwithcare.Experimentwithyourmod_charset_liteconfigurationtoensurethatitperformsthedesiredfunction.

mod_charset_liteallowstheadministratortospecifythesourcecharactersetofobjectsaswellasthecharactersettheyshouldbetranslatedintobeforesendingtotheclient.mod_charset_litedoesnottranslatethedataitselfbutinsteadtellsApachewhattranslationtoperform.mod_charset_liteisapplicabletoEBCDICandASCIIhostenvironments.InanEBCDICenvironment,ApachenormallytranslatestextcontentfromthecodepageoftheApacheprocesslocaletoISO-8859-1.mod_charset_litecanbeusedtospecifythatadifferenttranslationistobeperformed.InanASCIIenvironment,Apachenormallyperformsnotranslation,somod_charset_liteisneededinorderforanytranslationtotakeplace.

ThismoduleprovidesasmallsubsetofconfigurationmechanismsimplementedbyRussianApacheanditsassociatedmod_charset.

CommonProblems

InvalidcharactersetnamesThecharactersetnameparametersofCharsetSourceEncandCharsetDefaultmustbeacceptabletothetranslationmechanismusedbyAPRonthesystemwheremod_charset_liteisdeployed.Thesecharactersetnamesarenotstandardizedandareusuallynotthesameasthecorrespondingvaluesusedinhttpheaders.Currently,APRcanonlyuseiconv(3),soyoucaneasilytestyourcharactersetnamesusingtheiconv(1)program,asfollows:

iconv-fcharsetsourceenc-value-tcharsetdefault-value

MismatchbetweencharactersetofcontentandtranslationrulesIfthetranslationrulesdon'tmakesenseforthecontent,translationcanfailinvariousways,including:

Thetranslationmechanismmayreturnabadreturncode,andtheconnectionwillbeaborted.Thetranslationmechanismmaysilentlyplacespecialcharacters(e.g.,questionmarks)intheoutputbufferwhenitcannottranslatetheinputbuffer.

CharsetDefaultDirective

Description: CharsettotranslateintoSyntax: CharsetDefaultcharset

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExperimentalModule: mod_charset_lite

TheCharsetDefaultdirectivespecifiesthecharsetthatcontentintheassociatedcontainershouldbetranslatedto.

ThevalueofthecharsetargumentmustbeacceptedasavalidcharactersetnamebythecharactersetsupportinAPR.Generally,thismeansthatitmustbesupportedbyiconv.

Example<Directory/export/home/trawick/apacheinst/htdocs/convert>

CharsetSourceEncUTF-16BE

CharsetDefaultISO-8859-1

</Directory>

CharsetOptionsDirective

Description: ConfigurescharsettranslationbehaviorSyntax: CharsetOptionsoption[option]...

Default: CharsetOptionsDebugLevel=0

NoImplicitAdd

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExperimentalModule: mod_charset_lite

TheCharsetOptionsdirectiveconfigurescertainbehaviorsofmod_charset_lite.Optioncanbeoneof

DebugLevel=n

TheDebugLevelkeywordallowsyoutospecifythelevelofdebugmessagesgeneratedbymod_charset_lite.Bydefault,nomessagesaregenerated.ThisisequivalenttoDebugLevel=0.Withhighernumbers,moredebugmessagesaregenerated,andserverperformancewillbedegraded.TheactualmeaningsofthenumericvaluesaredescribedwiththedefinitionsoftheDBGLVL_constantsnearthebeginningofmod_charset_lite.c.

ImplicitAdd|NoImplicitAdd

TheImplicitAddkeywordspecifiesthatmod_charset_liteshouldimplicitlyinsertitsfilterwhentheconfigurationspecifiesthatthecharactersetofcontentshouldbetranslated.IfthefilterchainisexplicitlyconfiguredusingtheAddOutputFilterdirective,NoImplicitAddshouldbespecifiedsothatmod_charset_litedoesn'tadditsfilter.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

CharsetSourceEncDirective

Description: SourcecharsetoffilesSyntax: CharsetSourceEnccharset

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExperimentalModule: mod_charset_lite

TheCharsetSourceEncdirectivespecifiesthesourcecharsetoffilesintheassociatedcontainer.

ThevalueofthecharsetargumentmustbeacceptedasavalidcharactersetnamebythecharactersetsupportinAPR.Generally,thismeansthatitmustbesupportedbyiconv.

Example<Directory/export/home/trawick/apacheinst/htdocs/convert>

CharsetSourceEncUTF-16BE

CharsetDefaultISO-8859-1

</Directory>

ThecharactersetnamesinthisexampleworkwiththeiconvtranslationsupportinSolaris8.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_dav

: (WebDAV)

: Extension: dav_module: mod_dav.c

12 WebDAV('')

DavLockDB

LimitXMLRequestBody

WebDAVResources

EnablingWebDAV

mod_dav httpd.conf:

DavOn

DAVDAV

DAV DavLockDB httd.conf

DavLockDB/usr/local/apache2/var/DavLock

Apache User

<Limit> <Location>DAVLimitXMLRequestBody

DavLockDB/usr/local/apache2/var/DavLock

<Location/foo>

DavOn

AuthTypeBasic

AuthNameDAV

AuthUserFileuser.passwd

<LimitExceptGETOPTIONS>

requireuseradmin

</LimitExcept>

</Location>

mod_davGregStein Apache1.3mod_dav

DAV

DAV HTTPWebDAV SSL

mod_dav ApacheGroup )

mod_dav LimitXMLRequestBody

DavDepthInfinity PROPFINDDAV

mod_dav (PHPCGI)URL DAV

Alias/phparea/home/gstein/php_files

Alias/php-source/home/gstein/php_files

<Location/php-source>

DAVOn

ForceTypetext/plain

</Location>

http://example.com/phpareaPHPhttp://example.com/php-sourceDAV

Dav

: WebDAVHTTP: DavOn|Off|provider-name

: DavOff

:: Extension: mod_dav

WebDAVHTTP

<Location/foo>

DavOn

</Location>

On mod_dav_fs filesystem

WebDAV

DavDepthInfinity

: PROPFIND,Depth:Infinity: DavDepthInfinityon|off

: DavDepthInfinityoff

: ,,: Extension: mod_dav

'Depth:Infinity' PROPFINDdenial-of-service

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

DavMinTimeout

: DAV: DavMinTimeoutseconds

: DavMinTimeout0

: ,,: Extension: mod_dav

DAV

DavMinTimeout

(600)

<Location/MSWord>

DavMinTimeout600

</Location>

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_dav_fs

: mod_dav: Extension: dav_fs_module: mod_dav_fs.c

mod_dav mod_dav

Davfilesystem

filesystem mod_dav

mod_dav

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

DavLockDB

: DAV: DavLockDBfile-path

: ,: Extension: mod_dav_fs

DavLockDB

SDBM

DavLockDBlogs/DavLock

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_deflate

:: Extension: deflate_module: mod_deflate.c

mod_deflate DEFLATE

Filters

AddOutputFilterByTypeDEFLATEtext/htmltext/plaintext/xml

<Location/>

#Insertfilter

SetOutputFilterDEFLATE

#Netscape4.xhassomeproblems...

BrowserMatch^Mozilla/4gzip-only-text/html

#Netscape4.06-4.08havesomemoreproblems

BrowserMatch^Mozilla/4\.0[678]no-gzip

#MSIEmasqueradesasNetscape,butitisfine

#BrowserMatch\bMSIE!no-gzip!gzip-only-text/html

#NOTE:Duetoabuginmod_setenvifuptoApache2.0.48

#theaboveregexwon'twork.Youcanusethefollowing

#workaroundtogetthedesiredeffect:

BrowserMatch\bMSI[E]!no-gzip!gzip-only-text/html

#Don'tcompressimages

SetEnvIfNoCaseRequest_URI\

\.(?:gif|jpe?g|png)$no-gzipdont-vary

#Makesureproxiesdon'tdeliverthewrongcontent

HeaderappendVaryUser-Agentenv=!dont-vary

</Location>

OutputCompression DEFLATE

SetOutputFilterDEFLATE

MIME AddOutputFilterByType

<Directory"/your-server-root/manual">

AddOutputFilterByTypeDEFLATEtext/html

</Directory>

BrowserMatch

only-text/html

BrowserMatch^Mozilla/4gzip-only-text/html

BrowserMatch^Mozilla/4\.0[678]no-gzip

BrowserMatch\bMSIE!no-gzip!gzip-only-text/html

User-AgentNetscapeNavigator 4.x 4.06,4.07,4.08html

3 BrowserMatch"Mozilla/4" User-Agent

DEFLATEPHPSSIRESOURCE

mod_deflategzip AddInputFilter DEFLATE

<Location/dav-area>

SetInputFilterDEFLATE

</Location>

Content-Encoding:gzip

Content-Length

Content-Length Content-Length

Proxy

mod_deflate Vary:Accept-EncodingHTTPAccept-Encoding

User-Agent VaryDEFLATE

HeaderappendVaryUser-Agent

( HTTP) Vary *

HeadersetVary*

DeflateBufferSize

: zlib: DeflateBufferSizevalue

: DeflateBufferSize8096

: ,: Extension: mod_deflate

DeflateBufferSize zlib

DeflateCompressionLevel

:: DeflateCompressionLevelvalue

: Zlib

: ,: Extension: mod_deflate: ThisdirectiveisavailablesinceApache2.0.45

DeflateCompressionLevel

1()9()

DeflateFilterNote

:: DeflateFilterNote[type]notename

: ,: Extension: mod_deflate: typeisavailablesinceApache2.0.45

DeflateFilterNote

DeflateFilterNoteratio

LogFormat'"%r"%b(%{ratio}n)"%{User-agent}i"'deflate

CustomLoglogs/deflate_logdeflate

type type

Input

Output

Ratio

( /*100 ) type

DeflateFilterNoteInputinstream

DeflateFilterNoteOutputoutstream

DeflateFilterNoteRatioratio

LogFormat'"%r"%{outstream}n/%{instream}n(%{ratio}n%%)'

deflate

CustomLoglogs/deflate_logdeflate

mod_log_config

DeflateMemLevel

: zlib: DeflateMemLevelvalue

: DeflateMemLevel9

: ,: Extension: mod_deflate

DeflateMemLevel zlib(19))

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

DeflateWindowSize

: Zlib: DeflateWindowSizevalue

: DeflateWindowSize15

: ,: Extension: mod_deflate

DeflateWindowSize zlib(:zlib) (:2

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_dir

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

:

: Base: dir_module: mod_dir.c

:

index.htmlmod_dir

()

http://servername/foo/dirnameURLURL

http://servername/foo/dirname/

DirectoryIndex

: : DirectoryIndexlocal-url[local-url]...

: DirectoryIndexindex.html

: ,,,.htaccess: Indexes: Base: mod_dir

/ URL

DirectoryIndexindex.html

http://myserver/docs/http://myserver/docs/index.htmlURL

:

DirectoryIndexindex.htmlindex.txt/cgi-bin/index.pl

index.html index.txtCGI

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

DirectorySlash

:: DirectorySlashOn|Off

: DirectorySlashOn

: ,,,.htaccess: Indexes: Base: mod_dir: 2.0.51

URL mod_dir

URLmod_autoindex mod_autoindexDirectoryIndexHTMLURL

:

#seesecuritywarningbelow!

<Location/some/path>

DirectorySlashOff

SetHandlersome-handler

</Location>

DirectoryIndex( index.html)URL index.html

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_disk_cache

Description: ContentcachestoragemanagerkeyedtoURIsStatus: ExperimentalModuleIdentifier: disk_cache_moduleSourceFile: mod_disk_cache.c

Summary

Thismoduleisexperimental.Documentationisstillunderdevelopment...

mod_disk_cacheimplementsadiskbasedstoragemanager.Itisprimarilyofuseinconjunctionwithmod_proxy.

ContentisstoredinandretrievedfromthecacheusingURIbasedkeys.Contentwithaccessprotectionisnotcached.

Note:

mod_disk_cacherequirestheservicesofmod_cache.

CacheDirLengthDirective

Description: ThenumberofcharactersinsubdirectorynamesSyntax: CacheDirLengthlength

Default: CacheDirLength2

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

TheCacheDirLengthdirectivesetsthenumberofcharactersforeachsubdirectorynameinthecachehierarchy.

TheresultofCacheDirLevels*CacheDirLengthmustnotbehigherthan20.

CacheDirLength4

CacheDirLevelsDirective

Description: Thenumberoflevelsofsubdirectoriesinthecache.

Syntax: CacheDirLevelslevels

Default: CacheDirLevels3

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

TheCacheDirLevelsdirectivesetsthenumberofsubdirectorylevelsinthecache.CacheddatawillbesavedthismanydirectorylevelsbelowtheCacheRootdirectory.

TheresultofCacheDirLevels*CacheDirLengthmustnotbehigherthan20.

CacheDirLevels5

CacheExpiryCheckDirective

Description: IndicatesifthecacheobservesExpiresdateswhenseekingfiles

Syntax: CacheExpiryCheckOn|Off

Default: CacheExpiryCheckOn

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

Moredetailwillbeaddedhere,whenthefunctionisimplemented.

CacheExpiryCheckOff

TheCacheExpiryCheckdirectiveiscurrentlynotimplemented.

CacheGcCleanDirective

Description: ThetimetoretainunchangedcachedfilesthatmatchaURL

Syntax: CacheGcCleanhoursurl-string

Default: CacheGcClean?

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

Moredetailwillbeaddedhere,whenthefunctionisimplemented.

CacheGcClean12/daily_scripts

TheCacheGcCleandirectiveiscurrentlynotimplemented.

CacheGcDailyDirective

Description: Therecurringtimeeachdayforgarbagecollectiontoberun.(24hourclock)

Syntax: CacheGcDailytime

Default: CacheGcDaily?

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

Moredetailwillbeaddedhere,whenthefunctionisimplemented.

CacheGcDaily23:59

TheCacheGcDailydirectiveiscurrentlynotimplemented.

CacheGcIntervalDirective

Description: Theintervalbetweengarbagecollectionattempts.Syntax: CacheGcIntervalhours

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

TheCacheGcIntervaldirectivespecifiesthenumberofhourstowaitbetweenattemptstofreeupdiskspace.

Moredetailwillbeaddedhere,whenthefunctionisimplemented.

CacheGcInterval24

TheCacheGcIntervaldirectiveiscurrentlynotimplemented.

CacheGcMemUsageDirective

Description: Themaximumkilobytesofmemoryusedforgarbagecollection

Syntax: CacheGcMemUsageKBytes

Default: CacheGcMemUsage?

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

Moredetailwillbeaddedhere,whenthefunctionisimplemented.

CacheGcMemUsage16

TheCacheGcMemUsagedirectiveiscurrentlynotimplemented.

CacheGcUnusedDirective

Description: ThetimetoretainunreferencedcachedfilesthatmatchaURL.

Syntax: CacheGcUnusedhoursurl-string

Default: CacheGcUnused?

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

Moredetailwillbeaddedhere,whenthefunctionisimplemented.

CacheGcUnused12/local_images

TheCacheGcUnuseddirectiveiscurrentlynotimplemented.

CacheMaxFileSizeDirective

Description: Themaximumsize(inbytes)ofadocumenttobeplacedinthecache

Syntax: CacheMaxFileSizebytes

Default: CacheMaxFileSize1000000

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

TheCacheMaxFileSizedirectivesetsthemaximumsize,inbytes,foradocumenttobeconsideredforstorageinthecache.

CacheMaxFileSize64000

CacheMinFileSizeDirective

Description: Theminimumsize(inbytes)ofadocumenttobeplacedinthecache

Syntax: CacheMinFileSizebytes

Default: CacheMinFileSize1

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

TheCacheMinFileSizedirectivesetstheminimumsize,inbytes,foradocumenttobeconsideredforstorageinthecache.

CacheMinFileSize64

CacheRootDirective

Description: Thedirectoryrootunderwhichcachefilesarestored

Syntax: CacheRootdirectory

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

TheCacheRootdirectivedefinesthenameofthedirectoryonthedisktocontaincachefiles.Ifthemod_disk_cachemodulehasbeenloadedorcompiledintotheApacheserver,thisdirectivemustbedefined.FailingtoprovideavalueforCacheRootwillresultinaconfigurationfileprocessingerror.TheCacheDirLevelsandCacheDirLengthdirectivesdefinethestructureofthedirectoriesunderthespecifiedrootdirectory.

CacheRootc:/cacheroot

CacheSizeDirective

Description: ThemaximumamountofdiskspacethatwillbeusedbythecacheinKBytes

Syntax: CacheSizeKBytes

Default: CacheSize1000000

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

TheCacheSizedirectivesetsthedesireddiskspaceusageofthecache,inKBytes(1024-byteunits).Thisdirectivedoesnotputahardlimitonthesizeofthecache.Thegarbagecollectorwilldeletefilesuntiltheusageisatorbelowthesettings.Alwaysuseavaluethatislowerthantheavailablediskspace.

CacheSize5000000

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

CacheTimeMarginDirective

Description: TheminimumtimemargintocacheadocumentSyntax: CacheTimeMargin?

Default: CacheTimeMargin?

Context: serverconfig,virtualhostStatus: ExperimentalModule: mod_disk_cache

Moredetailwillbeaddedhere,whenthefunctionisimplemented.

CacheTimeMarginX

TheCacheTimeMargindirectiveiscurrentlynotimplemented.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_dumpio

Description: DumpsallI/Otoerrorlogasdesired.Status: ExperimentalModuleIdentifier: dumpio_moduleSourceFile: mod_dumpio.c

Summarymod_dumpioallowsfortheloggingofallinputreceivedbyApacheand/oralloutputsentbyApachetobelogged(dumped)totheerror.logfile.

ThedataloggingisdonerightafterSSLdecoding(forinput)andrightbeforeSSLencoding(foroutput).Ascanbeexpected,thiscanproduceextremevolumesofdata,andshouldonlybeusedwhendebuggingproblems.

EnablingdumpioSupport

Toenablethemodule,itshouldbecompiledandloadedintoyourrunningApacheconfiguration.Loggingcanthenbeenabledordisabledviathebelowdirectives.

InorderfordumpingtoworkLogLevelmustbesettodebug.

DumpIOInputDirective

Description: DumpallinputdatatotheerrorlogSyntax: DumpIOInputOn|Off

Default: DumpIOInputOff

Context: serverconfigStatus: ExperimentalModule: mod_dumpioCompatibility: DumpIOInputisonlyavailableinApache2.0.53

andlater.

Enabledumpingofallinput.

ExampleDumpIOInputOn

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

DumpIOOutputDirective

Description: DumpalloutputdatatotheerrorlogSyntax: DumpIOOutputOn|Off

Default: DumpIOOutputOff

Context: serverconfigStatus: ExperimentalModule: mod_dumpioCompatibility: DumpIOOutputisonlyavailableinApache2.0.53

andlater.

Enabledumpingofalloutput.

ExampleDumpIOOutputOn

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_echo

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

:: Experimental: echo_module: mod_echo.c: Apache2.0

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

ProtocolEcho

:: ProtocolEchoOn|Off

: ,: Experimental: mod_echo: Apache2.0

ProtocolEcho

ProtocolEchoOn

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_env

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: CGISSI

: Base: env_module: mod_env.c

CGISSI

PassEnv

:: PassEnvenv-variable[env-variable]...

: ,,,.htaccess: FileInfo: Base: mod_env

httpdCGI SSI

PassEnvLD_LIBRARY_PATH

SetEnv

:: SetEnvenv-variablevalue

: ,,,.htaccess: FileInfo: Base: mod_env

CGISSI

SetEnvSPECIAL_PATH/foo/bin

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

UnsetEnv

:: UnsetEnvenv-variable[env-variable]...

: ,,,.htaccess: FileInfo: Base: mod_env

CGISSI

UnsetEnvLD_LIBRARY_PATH

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_example

Description: IllustratestheApachemoduleAPIStatus: ExperimentalModuleIdentifier: example_moduleSourceFile: mod_example.c

Summary

Thisdocumenthasnotbeenupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

Thefilesinthesrc/modules/exampledirectoryundertheApachedistributiondirectorytreeareprovidedasanexampletothosethatwishtowritemodulesthatusetheApacheAPI.

Themainfileismod_example.c,whichillustratesallthedifferentcallbackmechanismsandcallsyntaxes.Bynomeansdoesanadd-onmoduleneedtoincluderoutinesforallofthecallbacks-quitethecontrary!

Theexamplemoduleisanactualworkingmodule.Ifyoulinkitintoyourserver,enablethe"example-handler"handlerforalocation,andthenbrowsetothatlocation,youwillseeadisplayofsomeofthetracingtheexamplemoduledidasthevariouscallbacksweremade.

Compilingtheexamplemodule

Toincludetheexamplemoduleinyourserver,followthestepsbelow:

1. Uncommentthe"AddModulemodules/example/mod_example"linenearthebottomofthesrc/Configurationfile.Ifthereisn'tone,addit;itshouldlooklikethis:

AddModulemodules/example/mod_example.o

2. Runthesrc/Configurescript("cdsrc;./Configure").ThiswillbuildtheMakefilefortheserveritself,andupdatethesrc/modules/Makefileforanyadditionalmodulesyouhaverequestedfrombeneaththatsubdirectory.

3. Maketheserver(run"make"inthesrcdirectory).

Toaddanothermoduleofyourown:

A. mkdirsrc/modules/mymodule

B. cpsrc/modules/example/*src/modules/mymodule

C. Modifythefilesinthenewdirectory.

D. Followsteps[1]through[3]above,withappropriatechanges.

Usingthemod_exampleModule

Toactivatetheexamplemodule,includeablocksimilartothefollowinginyoursrm.conffile:

<Location/example-info>

SetHandlerexample-handler

</Location>

Asanalternative,youcanputthefollowingintoa.htaccessfileandthenrequestthefile"test.example"fromthatlocation:

AddHandlerexample-handler.example

Afterreloading/restartingyourserver,youshouldbeabletobrowsetothislocationandseethebriefdisplaymentionedearlier.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ExampleDirective

Description: DemonstrationdirectivetoillustratetheApachemoduleAPI

Syntax: Example

Context: serverconfig,virtualhost,directory,.htaccessStatus: ExperimentalModule: mod_example

TheExampledirectivejustsetsademonstrationflagwhichtheexamplemodule'scontenthandlerdisplays.Ittakesnoarguments.IfyoubrowsetoanURLtowhichtheexamplecontent-handlerapplies,youwillgetadisplayoftheroutineswithinthemoduleandhowandinwhatordertheywerecalledtoservicethedocumentrequest.Theeffectofthisdirectiveonecanobserveunderthepoint"Exampledirectivedeclaredhere:YES/NO".

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_expires

: Expires Cache-Control

HTTP: Extension: expires_module: mod_expires.c

ExpiresHTTP Cache-Control max-age

max-age( RFC2616section14.9) Cache-ControlHeader

ExpiresDefault ExpiresByType :

ExpiresDefault"<base>[plus]{<num><type>}*"

ExpiresByTypetype/encoding"<base>[plus]{<num><type>}*"

<base>:

access

now('access')modification

plus<num> ( atoi()) <type>:

years

months

weeks

days

hours

minutes

seconds

1 :

ExpiresDefault"accessplus1month"

ExpiresDefault"accessplus4weeks"

ExpiresDefault"accessplus30days"

'<num><type>' :

ExpiresByTypetext/html"accessplus1month15days2hours"

ExpiresByTypeimage/gif"modificationplus5hours3minutes"

Expires

ExpiresActive

: Expires: ExpiresActiveOn|Off

: ,,,.htaccess: Indexes: Extension: mod_expires

Expires Cache-Control

( .htaccessExpiresDefault ()

Expires Cache-Control

ExpiresByType

: MIME Expires: ExpiresByTypeMIME-type<code>seconds

: ,,,.htaccess: Indexes: Extension: mod_expires

(text/html)

M

:#enableexpirations

ExpiresActiveOn

#expireGIFimagesafteramonthintheclient'scache

ExpiresByTypeimage/gifA2592000

#HTMLdocumentsaregoodforaweekfromthe

#timetheywerechanged

ExpiresByTypetext/htmlM604800

ExpiresActiveOn

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

ExpiresDefault

:: ExpiresDefault<code>seconds

: ,,,.htaccess: Indexes: Extension: mod_expires

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_ext_filter

Description: Passtheresponsebodythroughanexternalprogrambeforedeliverytotheclient

Status: ExtensionModuleIdentifier: ext_filter_moduleSourceFile: mod_ext_filter.c

Summarymod_ext_filterpresentsasimpleandfamiliarprogrammingmodelforfilters.Withthismodule,aprogramwhichreadsfromstdinandwritestostdout(i.e.,aUnix-stylefiltercommand)canbeafilterforApache.ThisfilteringmechanismismuchslowerthanusingafilterwhichisspeciallywrittenfortheApacheAPIandrunsinsideoftheApacheserverprocess,butitdoeshavethefollowingbenefits:

theprogrammingmodelismuchsimpleranyprogramming/scriptinglanguagecanbeused,providedthatitallowstheprogramtoreadfromstandardinputandwritetostandardoutputexistingprogramscanbeusedunmodifiedasApachefilters

Evenwhentheperformancecharacteristicsarenotsuitableforproductionuse,mod_ext_filtercanbeusedasaprototypeenvironmentforfilters.

SeealsoFilters

Examples

GeneratingHTMLfromsomeothertypeofresponse

#mod_ext_filterdirectivetodefineafilter

#toHTML-izetext/cfilesusingtheexternal

#program/usr/bin/enscript,withthetypeof

#theresultsettotext/html

ExtFilterDefinec-to-htmlmode=output\

intype=text/couttype=text/html\

cmd="/usr/bin/enscript--color-Whtml-Ec-o--"

<Directory"/export/home/trawick/apacheinst/htdocs/c">

#coredirectivetocausethenewfilterto

#berunonoutput

SetOutputFilterc-to-html

#mod_mimedirectivetosetthetypeof.c

#filestotext/c

AddTypetext/c.c

#mod_ext_filterdirectivetosetthedebug

#leveljusthighenoughtoseealogmessage

#perrequestshowingtheconfigurationinforce

ExtFilterOptionsDebugLevel=1

</Directory>

ImplementingacontentencodingfilterNote:thisgzipexampleisjustforthepurposesofillustration.Pleaserefertomod_deflateforapracticalimplementation.

#mod_ext_filterdirectivetodefinetheexternalfilter

ExtFilterDefinegzipmode=outputcmd=/bin/gzip

<Location/gzipped>

#coredirectivetocausethegzipfiltertobe

#runonoutput

SetOutputFiltergzip

#mod_headerdirectivetoadd

#"Content-Encoding:gzip"headerfield

HeadersetContent-Encodinggzip

</Location>

Slowingdowntheserver

#mod_ext_filterdirectivetodefineafilter

#whichrunseverythingthroughcat;catdoesn't

#modifyanything;itjustintroducesextrapathlength

#andconsumesmoreresources

ExtFilterDefineslowdownmode=outputcmd=/bin/cat\

preservescontentlength

<Location/>

#coredirectivetocausetheslowdownfilterto

#berunseveraltimesonoutput

#

SetOutputFilterslowdown;slowdown;slowdown

</Location>

Usingsedtoreplacetextintheresponse

#mod_ext_filterdirectivetodefineafilterwhich

#replacestextintheresponse

#

ExtFilterDefinefixtextmode=outputintype=text/html\

cmd="/bin/seds/verdana/arial/g"

<Location/>

#coredirectivetocausethefixtextfilterto

#berunonoutput

SetOutputFilterfixtext

</Location>

Tracinganotherfilter

#Tracethedatareadandwrittenbymod_deflate

#foraparticularclient(IP192.168.1.31)

#experiencingcompressionproblems.

#Thisfilterwilltracewhatgoesintomod_deflate.

ExtFilterDefinetracebefore\

cmd="/bin/tracefilter.pl/tmp/tracebefore"\

EnableEnv=trace_this_client

#Thisfilterwilltracewhatgoesaftermod_deflate.

#Notethatwithouttheftypeparameter,thedefault

#filtertypeofAP_FTYPE_RESOURCEwouldcausethe

#filtertobeplaced*before*mod_deflateinthefilter

#chain.Givingitanumericvalueslightlyhigherthan

#AP_FTYPE_CONTENT_SETwillensurethatitisplaced

#aftermod_deflate.

ExtFilterDefinetraceafter\

cmd="/bin/tracefilter.pl/tmp/traceafter"\

EnableEnv=trace_this_clientftype=21

<Directory/usr/local/docs>

SetEnvIfRemote_Addr192.168.1.31trace_this_client

SetOutputFiltertracebefore;deflate;traceafter

</Directory>

Hereisthefilterwhichtracesthedata:#!/usr/local/bin/perl-w

usestrict;

open(SAVE,">$ARGV[0]")

ordie"can'topen$ARGV[0]:$?";

while(<STDIN>){

printSAVE$_;

print$_;

}

close(SAVE);

ExtFilterDefineDirective

Description: DefineanexternalfilterSyntax: ExtFilterDefinefilternameparameters

Context: serverconfigStatus: ExtensionModule: mod_ext_filter

TheExtFilterDefinedirectivedefinesthecharacteristicsofanexternalfilter,includingtheprogramtorunanditsarguments.

filternamespecifiesthenameofthefilterbeingdefined.ThisnamecanthenbeusedinSetOutputFilterdirectives.Itmustbeuniqueamongallregisteredfilters.Atthepresenttime,noerrorisreportedbytheregister-filterAPI,soaproblemwithduplicatenamesisn'treportedtotheuser.

Subsequentparameterscanappearinanyorderanddefinetheexternalcommandtorunandcertainothercharacteristics.Theonlyrequiredparameteriscmd=.Theseparametersare:

cmd=cmdline

Thecmd=keywordallowsyoutospecifytheexternalcommandtorun.Ifthereareargumentsaftertheprogramname,thecommandlineshouldbesurroundedinquotationmarks(e.g.,cmd="/bin/mypgmarg1arg2".Normalshellquotingisnotnecessarysincetheprogramisrundirectly,bypassingtheshell.Programargumentsareblank-delimited.Abackslashcanbeusedtoescapeblankswhichshouldbepartofaprogramargument.Anybackslasheswhicharepartoftheargumentmustbeescapedwithbackslashthemselves.InadditiontothestandardCGIenvironmentvariables,DOCUMENT_URI,DOCUMENT_PATH_INFO,andQUERY_STRING_UNESCAPEDwillalsobesetfortheprogram.

mode=mode

modeshouldbeoutputfornow(thedefault).Inthefuture,mode=inputwillbeusedtospecifyafilterforrequestbodies.

intype=imt

Thisparameterspecifiestheinternetmediatype(i.e.,MIMEtype)ofdocumentswhichshouldbefiltered.Bydefault,alldocumentsarefiltered.Ifintype=isspecified,thefilterwillbedisabledfordocumentsofothertypes.

outtype=imt

Thisparameterspecifiestheinternetmediatype(i.e.,MIMEtype)offiltereddocuments.Itisusefulwhenthefilterchangestheinternetmediatypeaspartofthefilteringoperation.Bydefault,theinternetmediatypeisunchanged.

PreservesContentLength

ThePreservesContentLengthkeywordspecifiesthatthefilterpreservesthecontentlength.Thisisnotthedefault,asmostfilterschangethecontentlength.Intheeventthatthefilterdoesn'tmodifythelength,thiskeywordshouldbespecified.

ftype=filtertype

Thisparameterspecifiesthenumericvalueforfiltertypethatthefiltershouldberegisteredas.Thedefaultvalue,AP_FTYPE_RESOURCE,issufficientinmostcases.Ifthefilterneedstooperateatadifferentpointinthefilterchainthanresourcefilters,thenthisparameterwillbenecessary.SeetheAP_FTYPE_foodefinitionsinutil_filter.hforappropriatevalues.

disableenv=env

Thisparameterspecifiesthenameofanenvironmentvariablewhich,ifset,willdisablethefilter.

enableenv=env

Thisparameterspecifiesthenameofanenvironmentvariablewhichmustbeset,orthefilterwillbedisabled.

ExtFilterOptionsDirective

Description: Configuremod_ext_filteroptionsSyntax: ExtFilterOptionsoption[option]...

Default: ExtFilterOptionsDebugLevel=0

NoLogStderr

Context: directoryStatus: ExtensionModule: mod_ext_filter

TheExtFilterOptionsdirectivespecifiesspecialprocessingoptionsformod_ext_filter.Optioncanbeoneof

DebugLevel=n

TheDebugLevelkeywordallowsyoutospecifythelevelofdebugmessagesgeneratedbymod_ext_filter.Bydefault,nodebugmessagesaregenerated.ThisisequivalenttoDebugLevel=0.Withhighernumbers,moredebugmessagesaregenerated,andserverperformancewillbedegraded.TheactualmeaningsofthenumericvaluesaredescribedwiththedefinitionsoftheDBGLVL_constantsnearthebeginningofmod_ext_filter.c.Note:ThecoredirectiveLogLevelshouldbeusedtocausedebugmessagestobestoredintheApacheerrorlog.

LogStderr|NoLogStderr

TheLogStderrkeywordspecifiesthatmessageswrittentostandarderrorbytheexternalfilterprogramwillbesavedintheApacheerrorlog.NoLogStderrdisablesthisfeature.

ExampleExtFilterOptionsLogStderrDebugLevel=0

Messageswrittentothefilter'sstandarderrorwillbestoredinthe

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Apacheerrorlog.Nodebugmessageswillbegeneratedbymod_ext_filter.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_file_cache

Description: CachesastaticlistoffilesinmemoryStatus: ExperimentalModuleIdentifier: file_cache_moduleSourceFile: mod_file_cache.c

Summary

Thismoduleshouldbeusedwithcare.Youcaneasilycreateabrokensiteusingmod_file_cache,soreadthisdocumentcarefully.

Cachingfrequentlyrequestedfilesthatchangeveryinfrequentlyisatechniqueforreducingserverload.mod_file_cacheprovidestwotechniquesforcachingfrequentlyrequestedstaticfiles.Throughconfigurationdirectives,youcandirectmod_file_cachetoeitheropenthenmmap()afile,ortopre-openafileandsavethefile'sopenfilehandle.Bothtechniquesreduceserverloadwhenprocessingrequestsforthesefilesbydoingpartofthework(specifically,thefileI/O)forservingthefilewhentheserverisstartedratherthanduringeachrequest.

Notice:YoucannotusethisforspeedingupCGIprogramsorotherfileswhichareservedbyspecialcontenthandlers.ItcanonlybeusedforregularfileswhichareusuallyservedbytheApachecorecontenthandler.

Thismoduleisanextensionofandborrowsheavilyfromthemod_mmap_staticmoduleinApache1.3.

Usingmod_file_cache

mod_file_cachecachesalistofstaticallyconfiguredfilesviaMMapFileorCacheFiledirectivesinthemainserverconfiguration.

Notallplatformssupportbothdirectives.Forexample,ApacheonWindowsdoesnotcurrentlysupporttheMMapStaticdirective,whileotherplatforms,likeAIX,supportboth.Youwillreceiveanerrormessageintheservererrorlogifyouattempttouseanunsupporteddirective.Ifgivenanunsupporteddirective,theserverwillstartbutthefilewillnotbecached.Onplatformsthatsupportbothdirectives,youshouldexperimentwithbothtoseewhichworksbestforyou.

MMapFileDirectiveTheMMapFiledirectiveofmod_file_cachemapsalistofstaticallyconfiguredfilesintomemorythroughthesystemcallmmap().ThissystemcallisavailableonmostmodernUnixderivates,butnotonall.Therearesometimessystem-specificlimitsonthesizeandnumberoffilesthatcanbemmap()ed,experimentationisprobablytheeasiestwaytofindout.

Thismmap()ingisdoneonceatserverstartorrestart,only.Sowheneveroneofthemappedfileschangesonthefilesystemyouhavetorestarttheserver(seetheStoppingandRestartingdocumentation).Toreiteratethatpoint:ifthefilesaremodifiedinplacewithoutrestartingtheserveryoumayendupservingrequeststhatarecompletelybogus.Youshouldupdatefilesbyunlinkingtheoldcopyandputtinganewcopyinplace.Mosttoolssuchasrdistandmvdothis.Thereasonwhythismodulesdoesn'ttakecareofchangestothefilesisthatthischeckwouldneedanextrastat()everytimewhichisawasteandagainsttheintentofI/Oreduction.

CacheFileDirectiveTheCacheFiledirectiveofmod_file_cacheopensanactivehandleorfiledescriptortothefile(orfiles)listedintheconfigurationdirectiveandplacestheseopenfilehandlesinthecache.Whenthefileisrequested,theserverretrievesthehandlefromthecacheandpassesittothesendfile()(orTransmitFile()onWindows),socketAPI.

Thisfilehandlecachingisdoneonceatserverstartorrestart,only.Sowheneveroneofthecachedfileschangesonthefilesystemyouhavetorestarttheserver(seetheStoppingandRestartingdocumentation).Toreiteratethatpoint:ifthefilesaremodifiedinplacewithoutrestartingtheserveryoumayendupservingrequeststhatarecompletelybogus.Youshouldupdatefilesbyunlinkingtheoldcopyandputtinganewcopyinplace.Mosttoolssuchasrdistandmvdothis.

Note

Don'tbotheraskingforadirectivewhichrecursivelycachesallthefilesinadirectory.Trythisinstead...SeetheIncludedirective,andconsiderthiscommand:

find/www/htdocs-typef-print\

|sed-e's/.*/mmapfile&/'>/www/conf/mmap.conf

CacheFileDirective

Description: CachealistoffilehandlesatstartuptimeSyntax: CacheFilefile-path[file-path]...

Context: serverconfigStatus: ExperimentalModule: mod_file_cache

TheCacheFiledirectiveopenshandlestooneormorefiles(givenaswhitespaceseparatedarguments)andplacesthesehandlesintothecacheatserverstartuptime.Handlestocachedfilesareautomaticallyclosedonaservershutdown.Whenthefileshavechangedonthefilesystem,theservershouldberestartedtotore-cachethem.

Becarefulwiththefile-patharguments:TheyhavetoliterallymatchthefilesystempathApache'sURL-to-filenametranslationhandlerscreate.Wecannotcompareinodesorotherstufftomatchpathsthroughsymboliclinksetc.becausethatagainwouldcostextrastat()systemcallswhichisnotacceptable.Thismodulemayormaynotworkwithfilenamesrewrittenbymod_aliasormod_rewrite.

ExampleCacheFile/usr/local/apache/htdocs/index.html

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

MMapFileDirective

Description: MapalistoffilesintomemoryatstartuptimeSyntax: MMapFilefile-path[file-path]...

Context: serverconfigStatus: ExperimentalModule: mod_file_cache

TheMMapFiledirectivemapsoneormorefiles(givenaswhitespaceseparatedarguments)intomemoryatserverstartuptime.Theyareautomaticallyunmappedonaservershutdown.WhenthefileshavechangedonthefilesystematleastaHUPorUSR1signalshouldbesendtotheservertore-mmap()them.

Becarefulwiththefile-patharguments:TheyhavetoliterallymatchthefilesystempathApache'sURL-to-filenametranslationhandlerscreate.Wecannotcompareinodesorotherstufftomatchpathsthroughsymboliclinksetc.becausethatagainwouldcostextrastat()systemcallswhichisnotacceptable.Thismodulemayormaynotworkwithfilenamesrewrittenbymod_aliasormod_rewrite.

ExampleMMapFile/usr/local/apache/htdocs/index.html

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_headers

Description: CustomizationofHTTPrequestandresponseheaders

Status: ExtensionModuleIdentifier: headers_moduleSourceFile: mod_headers.c

SummaryThismoduleprovidesdirectivestocontrolandmodifyHTTPrequestandresponseheaders.Headerscanbemerged,replacedorremoved.

OrderofProcessing

Thedirectivesprovidedbymod_headerscanoccuralmostanywherewithintheserverconfiguration.Theyarevalidinthemainserverconfigandvirtualhostsections,inside<Directory>,<Location>and<Files>sections,andwithin.htaccessfiles.

Thedirectivesareprocessedinthefollowingorder:

1. mainserver

2. virtualhost

3. <Directory>sectionsand.htaccess

4. <Files>

5. <Location>

Orderisimportant.Thesetwoheadershaveadifferenteffectifreversed:

RequestHeaderappendMirrorID"mirror12"

RequestHeaderunsetMirrorID

Thiswayround,theMirrorIDheaderisnotset.Ifreversed,theMirrorIDheaderissetto"mirror12".

Examples

1. Copyallrequestheadersthatbeginwith"TS"totheresponseheaders:

Headerecho^TS

2. Addaheader,MyHeader,totheresponseincludingatimestampforwhentherequestwasreceivedandhowlongittooktobeginservingtherequest.Thisheadercanbeusedbytheclienttointuitloadontheserverorinisolatingbottlenecksbetweentheclientandtheserver.

HeaderaddMyHeader"%D%t"

resultsinthisheaderbeingaddedtotheresponse:

MyHeader:D=3775428t=991424704447256

3. SayhellotoJoe

HeaderaddMyHeader"HelloJoe.Ittook%Dmicroseconds\

forApachetoservethisrequest."

resultsinthisheaderbeingaddedtotheresponse:

MyHeader:HelloJoe.IttookD=3775428microsecondsfor

Apachetoservethisrequest.

4. ConditionallysendMyHeaderontheresponseifandonlyifheader"MyRequestHeader"ispresentontherequest.Thisisusefulforconstructingheadersinresponsetosomeclientstimulus.Notethatthisexamplerequirestheservicesofthemod_setenvifmodule.

SetEnvIfMyRequestHeadervalueHAVE_MyRequestHeader

HeaderaddMyHeader"%D%tmytext"

env=HAVE_MyRequestHeader

IftheheaderMyRequestHeader:valueispresentontheHTTPrequest,theresponsewillcontainthefollowingheader:

MyHeader:D=3775428t=991424704447256mytext

HeaderDirective

Description: ConfigureHTTPresponseheadersSyntax: Header[condition]

set|append|add|unset|echoheader

[value][env=[!]variable]

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_headersCompatibility: Conditionisavailableinversion2.0.51andlater

Thisdirectivecanreplace,mergeorremoveHTTPresponseheaders.Theheaderismodifiedjustafterthecontenthandlerandoutputfiltersarerun,allowingoutgoingheaderstobemodified.

Theoptionalconditioncanbeeitheronsuccessoralways.Itdetermines,whichinternalheadertableshouldbeoperatedon.onsuccessstandsfor2xxstatuscodesandalwaysforallstatuscodes(including2xx).Especiallyifyouwanttounsetheaderssetbycertainmodules,youshouldtryout,whichtableisaffected.

Theactionitperformsisdeterminedbythesecondargument.Thiscanbeoneofthefollowingvalues:

set

Theresponseheaderisset,replacinganypreviousheaderwiththisname.Thevaluemaybeaformatstring.

append

Theresponseheaderisappendedtoanyexistingheaderofthesamename.Whenanewvalueismergedontoanexistingheaderitisseparatedfromtheexistingheaderwithacomma.ThisistheHTTPstandardwayofgivingaheader

multiplevalues.

add

Theresponseheaderisaddedtotheexistingsetofheaders,evenifthisheaderalreadyexists.Thiscanresultintwo(ormore)headershavingthesamename.Thiscanleadtounforeseenconsequences,andingeneral"append"shouldbeusedinstead.

unset

Theresponseheaderofthisnameisremoved,ifitexists.Iftherearemultipleheadersofthesamename,allwillberemoved.

echo

Requestheaderswiththisnameareechoedbackintheresponseheaders.headermaybearegularexpression.

Thisargumentisfollowedbyaheadername,whichcanincludethefinalcolon,butitisnotrequired.Caseisignoredforset,append,addandunset.Theheadernameforechoiscasesensitiveandmaybearegularexpression.

Foradd,appendandsetavalueisspecifiedasthethirdargument.Ifvaluecontainsspaces,itshouldbesurroundedbydoublequotes.valuemaybeacharacterstring,astringcontainingformatspecifiersoracombinationofboth.Thefollowingformatspecifiersaresupportedinvalue:

%t ThetimetherequestwasreceivedinUniversalCoordinatedTimesincetheepoch(Jan.1,1970)measuredinmicroseconds.Thevalueisprecededbyt=.

%D Thetimefromwhentherequestwasreceivedtothetimetheheadersaresentonthewire.Thisisameasureofthedurationoftherequest.Thevalueis

precededbyD=.%

{FOOBAR}e

ThecontentsoftheenvironmentvariableFOOBAR.

WhentheHeaderdirectiveisusedwiththeadd,append,orsetargument,afourthargumentmaybeusedtospecifyconditionsunderwhichtheactionwillbetaken.Iftheenvironmentvariablespecifiedintheenv=...argumentexists(oriftheenvironmentvariabledoesnotexistandenv=!...isspecified)thentheactionspecifiedbytheHeaderdirectivewilltakeeffect.Otherwise,thedirectivewillhavenoeffectontherequest.

TheHeaderdirectivesareprocessedjustbeforetheresponseissenttothenetwork.Thesemeansthatitispossibletosetand/oroverridemostheaders,exceptforthoseheadersaddedbytheheaderfilter.

RequestHeaderDirective

Description: ConfigureHTTPrequestheadersSyntax: RequestHeaderset|append|add|unset

header[value[env=[!]variable]]

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_headers

Thisdirectivecanreplace,mergeorremoveHTTPrequestheaders.Theheaderismodifiedjustbeforethecontenthandlerisrun,allowingincomingheaderstobemodified.Theactionitperformsisdeterminedbythefirstargument.Thiscanbeoneofthefollowingvalues:

set

Therequestheaderisset,replacinganypreviousheaderwiththisname

append

Therequestheaderisappendedtoanyexistingheaderofthesamename.Whenanewvalueismergedontoanexistingheaderitisseparatedfromtheexistingheaderwithacomma.ThisistheHTTPstandardwayofgivingaheadermultiplevalues.

add

Therequestheaderisaddedtotheexistingsetofheaders,evenifthisheaderalreadyexists.Thiscanresultintwo(ormore)headershavingthesamename.Thiscanleadtounforeseenconsequences,andingeneralappendshouldbeusedinstead.

unset

Therequestheaderofthisnameisremoved,ifitexists.If

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

therearemultipleheadersofthesamename,allwillberemoved.

Thisargumentisfollowedbyaheadername,whichcanincludethefinalcolon,butitisnotrequired.Caseisignored.Foradd,appendandsetavalueisgivenasthethirdargument.Ifvaluecontainsspaces,itshouldbesurroundedbydoublequotes.Forunset,novalueshouldbegiven.

WhentheRequestHeaderdirectiveisusedwiththeadd,append,orsetargument,afourthargumentmaybeusedtospecifyconditionsunderwhichtheactionwillbetaken.Iftheenvironmentvariablespecifiedintheenv=...argumentexists(oriftheenvironmentvariabledoesnotexistandenv=!...isspecified)thentheactionspecifiedbytheRequestHeaderdirectivewilltakeeffect.Otherwise,thedirectivewillhavenoeffectontherequest.

TheRequestHeaderdirectiveisprocessedjustbeforetherequestisrunbyitshandlerinthefixupphase.Thisshouldallowheadersgeneratedbythebrowser,orbyApacheinputfilterstobeoverriddenormodified.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_imap

Description: Server-sideimagemapprocessingStatus: BaseModuleIdentifier: imap_moduleSourceFile: mod_imap.c

SummaryThismoduleprocesses.mapfiles,therebyreplacingthefunctionalityoftheimagemapCGIprogram.Anydirectoryordocumenttypeconfiguredtousethehandlerimap-file(usingeitherAddHandlerorSetHandler)willbeprocessedbythismodule.

Thefollowingdirectivewillactivatefilesendingwith.mapasimagemapfiles:

AddHandlerimap-filemap

Notethatthefollowingisstillsupported:

AddTypeapplication/x-httpd-imapmap

However,wearetryingtophaseout"magicMIMEtypes"sowearedeprecatingthismethod.

NewFeatures

Theimagemapmoduleaddssomenewfeaturesthatwerenotpossiblewithpreviouslydistributedimagemapprograms.

URLreferencesrelativetotheReferer:information.Default<base>assignmentthroughanewmapdirectivebase.Noneedforimagemap.conffile.Pointreferences.Configurablegenerationofimagemapmenus.

ImagemapFile

Thelinesintheimagemapfilescanhaveoneofseveralformats:

directivevalue[x,y...]

directivevalue"Menutext"[x,y...]

directivevaluex,y..."Menutext"

Thedirectiveisoneofbase,default,poly,circle,rect,orpoint.ThevalueisanabsoluteorrelativeURL,oroneofthespecialvalueslistedbelow.Thecoordinatesarex,ypairsseparatedbywhitespace.Thequotedtextisusedasthetextofthelinkifaimagemapmenuisgenerated.Linesbeginningwith'#'arecomments.

ImagemapFileDirectivesTherearesixdirectivesallowedintheimagemapfile.Thedirectivescancomeinanyorder,butareprocessedintheordertheyarefoundintheimagemapfile.

baseDirectiveHastheeffectof<basehref="value">.Thenon-absoluteURLsofthemap-filearetakenrelativetothisvalue.ThebasedirectiveoverridesImapBaseassetina.htaccessfileorintheserverconfigurationfiles.IntheabsenceofanImapBaseconfigurationdirective,basedefaultstohttp://server_name/.

base_uriissynonymouswithbase.NotethatatrailingslashontheURLissignificant.

defaultDirectiveTheactiontakenifthecoordinatesgivendonotfitanyofthepoly,circleorrectdirectives,andtherearenopointdirectives.Defaultstonocontentintheabsenceofan

ImapDefaultconfigurationsetting,causingastatuscodeof204NoContenttobereturned.Theclientshouldkeepthesamepagedisplayed.

polyDirectiveTakesthreetoone-hundredpoints,andisobeyediftheuserselectedcoordinatesfallwithinthepolygondefinedbythesepoints.

circle

Takesthecentercoordinatesofacircleandapointonthecircle.Isobeyediftheuserselectedpointiswiththecircle.

rectDirectiveTakesthecoordinatesoftwoopposingcornersofarectangle.Obeyedifthepointselectediswithinthisrectangle.

pointDirectiveTakesasinglepoint.Thepointdirectiveclosesttotheuserselectedpointisobeyedifnootherdirectivesaresatisfied.Notethatdefaultwillnotbefollowedifapointdirectiveispresentandvalidcoordinatesaregiven.

ValuesThevaluesforeachofthedirectivescananyofthefollowing:

aURLTheURLcanberelativeorabsoluteURL.RelativeURLscancontain'..'syntaxandwillberesolvedrelativetothebasevalue.

baseitselfwillnotresolvedaccordingtothecurrentvalue.Astatementbasemailto:willworkproperly,though.

map

EquivalenttotheURLoftheimagemapfileitself.No

coordinatesaresentwiththis,soamenuwillbegeneratedunlessImapMenuissettonone.

menu

Synonymouswithmap.

referer

EquivalenttotheURLofthereferringdocument.Defaultstohttp://servername/ifnoReferer:headerwaspresent.

nocontent

Sendsastatuscodeof204NoContent,tellingtheclienttokeepthesamepagedisplayed.Validforallbutbase.

error

Failswitha500ServerError.Validforallbutbase,butsortofsillyforanythingbutdefault.

Coordinates0,0200,200

Acoordinateconsistsofanxandayvalueseparatedbyacomma.Thecoordinatesareseparatedfromeachotherbywhitespace.ToaccommodatethewayLynxhandlesimagemaps,shouldauserselectthecoordinate0,0,itisasifnocoordinatehadbeenselected.

QuotedText"MenuText"

Afterthevalueorafterthecoordinates,thelineoptionallymaycontaintextwithindoublequotes.Thisstringisusedasthetextforthelinkifamenuisgenerated:

<ahref="http://foo.com/">Menutext</a>

Ifnoquotedtextispresent,thenameofthelinkwillbeused

asthetext:

<ahref="http://foo.com/">http://foo.com</a>

Ifyouwanttousedoublequoteswithinthistext,youhavetowritethemas&quot;.

ExampleMapfile

#Commentsareprintedina'formatted'or'semiformatted'menu.

#Andcancontainhtmltags.<hr>

basereferer

polymap"CouldIhaveamenu,please?"0,00,1010,1010,0

rect..0,077,27"thedirectoryofthereferer"

circlehttp://www.inetnebr.com/lincoln/feedback/195,0305,27

rectanother_file"insamedirectoryasreferer"306,0419,27

pointhttp://www.zyzzyva.com/100,100

pointhttp://www.tripod.com/200,200

rectmailto:nate@tripod.com100,150200,0"Bugs?"

Referencingyourmapfile

HTMLexample<ahref="/maps/imagemap1.map">

<imgismapsrc="/images/imagemap1.gif">

</a>

XHTMLexample<ahref="/maps/imagemap1.map">

<imgismap="ismap"src="/images/imagemap1.gif"/>

</a>

ImapBaseDirective

Description: DefaultbaseforimagemapfilesSyntax: ImapBasemap|referer|URL

Default: ImapBasehttp://servername/

Context: serverconfig,virtualhost,directory,.htaccessOverride: IndexesStatus: BaseModule: mod_imap

TheImapBasedirectivesetsthedefaultbaseusedintheimagemapfiles.Itsvalueisoverriddenbyabasedirectivewithintheimagemapfile.Ifnotpresent,thebasedefaultstohttp://servername/.

SeealsoUseCanonicalName

ImapDefaultDirective

Description: Defaultactionwhenanimagemapiscalledwithcoordinatesthatarenotexplicitlymapped

Syntax: ImapDefault

error|nocontent|map|referer|URL

Default: ImapDefaultnocontent

Context: serverconfig,virtualhost,directory,.htaccessOverride: IndexesStatus: BaseModule: mod_imap

TheImapDefaultdirectivesetsthedefaultdefaultusedintheimagemapfiles.Itsvalueisoverriddenbyadefaultdirectivewithintheimagemapfile.Ifnotpresent,thedefaultactionisnocontent,whichmeansthata204NoContentissenttotheclient.Inthiscase,theclientshouldcontinuetodisplaytheoriginalpage.

ImapMenuDirective

Description: Actionifnocoordinatesaregivenwhencallinganimagemap

Syntax: ImapMenu

none|formatted|semiformatted|unformatted

Context: serverconfig,virtualhost,directory,.htaccessOverride: IndexesStatus: BaseModule: mod_imap

TheImapMenudirectivedeterminestheactiontakenifanimagemapfileiscalledwithoutvalidcoordinates.

none

IfImapMenuisnone,nomenuisgenerated,andthedefaultactionisperformed.

formatted

Aformattedmenuisthesimplestmenu.Commentsintheimagemapfileareignored.Aleveloneheaderisprinted,thenanhrule,thenthelinkseachonaseparateline.Themenuhasaconsistent,plainlookclosetothatofadirectorylisting.

semiformatted

Inthesemiformattedmenu,commentsareprintedwheretheyoccurintheimagemapfile.BlanklinesareturnedintoHTMLbreaks.Noheaderorhruleisprinted,butotherwisethemenuisthesameasaformattedmenu.

unformatted

Commentsareprinted,blanklinesareignored.Nothingisprintedthatdoesnotappearintheimagemapfile.Allbreaksandheadersmustbeincludedascommentsintheimagemapfile.Thisgivesyouthemostflexibilityovertheappearanceofyourmenus,butrequiresyoutotreatyourmapfilesasHTML

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

insteadofplaintext.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_include

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: html(ServerSideIncludes)

: Base: include_module: mod_include.c: Apache2.0

Options

AcceptPathInfo

SSI

Server-SideIncludes

ServerSideIncludes INCLUDES Server-sideinclude.shtmlApache

AddTypetext/html.shtml

AddOutputFilterINCLUDES.shtml

shtml (Options .htaccess):

Options+Includes

server-parsedINCLUDES MIMEserver-parsed-html text/x-server-parsed-html3ApacheINCLUDES( MIME

TutorialonServerSideIncludes.

(SSI)PATH_INFO

SSI PATH_INFO()

SGML HTML

<!--#elementattribute=valueattribute=value...-->

(:value) (')(`) ( -->)SSI

(:element)

config configureoutputformatsecho printvariablesexec executeexternalprogramsfsize printsizeofafileflastmod printlastmodificationtimeofafileinclude includeafileprintenv printallavailablevariablesset setavalueofavariable

SSI mod_include exec

config

errmsg

sizefmt

)

timefmt

strftime(3)

echo include SSIUndefinedEcho

var

encoding

echo entityencoding encoding

encoding var ISO-8859-1

execexecCGI mod_cgi

cgi

(%-)URL (/)(ScriptAlias OptionExecCGI)CGI

CGI PATH_INFO( CGIinclude

<!--#execcgi="/cgi-bin/example.cgi"-->

Location: HTML()

execcgi includevirtualCGI

cgi includevirtual

<!--#includevirtual="/cgi-bin/example.cgi?argument=value"

-->

cmd

/bin/sh CGI include

#includevirtual #execcgi #execcmd( #includevirtual)Apache

Win32 suexecunix execunixsuexec Win32suexecunix:

<!--#execcmd="perl/path/to/perlscriptarg1arg2"-->

fsize sizefmt

file

virtual

(%)URL-path(/)

flastmod timefmt

include (text/plain,text/html)

include

file

../

virtual

(%)URL URL

URLURL

URLCGI

<!--#includevirtual="/cgi-bin/example.cgi?argument=value"

-->

HTMLCGI includevirtual

printenvApache1.3.12 (

<!--#printenv-->

set

var

value

<!--#setvar="category"value="help"-->

Include

CGI echo if elif,

DATE_GMT

DATE_LOCAL

DOCUMENT_NAME

()

DOCUMENT_URI

(%)URL-path

LAST_MODIFIED

QUERY_STRING_UNESCAPED

(%-) shell

SSI echo,set :

<!--#ifexpr="$a=\$test"-->

:

<!--#setvar="Zed"value="${REMOTE_HOST}_${REQUEST_METHOD}"-->

REMOTE_HOST "X" REQUEST_METHOD "Y" Zed"X_Y"

DOCUMENT_URI /foo/file.html"infoo"/bar/file.html"inbar" "inneither"

<!--#ifexpr='"$DOCUMENT_URI"="/foo/file.html"'-->

infoo

<!--#elifexpr='"$DOCUMENT_URI"="/bar/file.html"'-->

inbar

<!--#else-->

inneither

<!--#endif-->

<!--#ifexpr="test_condition"-->

<!--#elifexpr="test_condition"-->

<!--#else-->

<!--#endif-->

if if

elif else test_condition

endif if

test_condition:

string

string

string1=string2

string1==string2

string1!=string2

string1 string2 string2 /string/ perl5 == =

( = ==)

<!--#ifexpr="$QUERY_STRING=/^sid=([a-zA-Z0-9]+)/"-->

<!--#setvar="session"value="$1"-->

<!--#endif-->

string1<string2

string1<=string2

string1>string2

string1>=string2

string1 string2 ( strcmp(3)) "100"

"20"

(test_condition)

test_condition

!test_condition

test_condition

test_condition1&&test_condition2

test_condition1 test_condition2

test_condition1||test_condition2

test_condition1 test_condition2

"="" !="" &&" " !" :

<!--#ifexpr="$a=test1&&$b=test2"-->

<!--#ifexpr="($a=test1)&&($b=test2)"-->

&& ||

:

string1string2 string1string2

'string1string2' string1string2

SSIEndTag

: include: SSIEndTagtag

: SSIEndTag"-->"

: ,: Base: mod_include: 2.0.30

mod_include include

SSIEndTag"%>"

SSIStartTag

SSIErrorMsg

: SSI: SSIErrorMsgmessage

: SSIErrorMsg"[anerroroccurredwhile

processingthisdirective]"

: ,,,.htaccess: All: Base: mod_include: 2.0.30

SSIErrorMsg mod_include

<!--#configerrmsg=message-->

SSIErrorMsg"<!--Error-->"

SSIStartTag

: include: SSIStartTagtag

: SSIStartTag"<!--#"

: ,: Base: mod_include: 2.0.30

mod_includeinclude

()

SSIStartTag"<%"

SSIEndTag"%>"

SSIEndTag SSI:

SSI<%printenv%>

SSIEndTag

SSITimeFormat

:: SSITimeFormatformatstring

: SSITimeFormat"%A,%d-%b-%Y%H:%M:%S%Z"

: ,,,.htaccess: All: Base: mod_include: 2.0.30

DATEecho

<!--#configtimefmt=formatstring-->

SSITimeFormat"%R,%B%d,%Y"

"22:26,June14,2002"

SSIUndefinedEcho

: echo: SSIUndefinedEchostring

: SSIUndefinedEcho"(none)"

: ,: All: Base: mod_include: 2.0.34

"echo" mod_include

SSIUndefinedEcho"<!--undef-->"

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

XBitHack

: SSI: XBitHackon|off|full

: XBitHackoff

: ,,,.htaccess: Options: Base: mod_include

XBitHackHTML MIME

off

on

text/htmlhtml

full

on

CGI #include

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_info

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

:: Extension: info_module: mod_info.c

mod_info httpd.conf

<Location/server-info>

SetHandlerserver-info

</Location>

<Location> <Limit>

http://your.host.dom/server-info

mod_info ( .htaccess

/ Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

AddModuleInfo

: server-info: AddModuleInfomodule-namestring

: ,: Extension: mod_info: Apache1.3

string module-nameHTML :

AddModuleInfomod_authn_file.c'See<a\

href="http://www.apache.org/docs/2.0/mod/mod_authn_file.html">\

http://www.apache.org/docs/2.0/mod/mod_authn_file.html</a>'

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_isapi

Description: ISAPIExtensionswithinApacheforWindowsStatus: BaseModuleIdentifier: isapi_moduleSourceFile: mod_isapi.cCompatibility: Win32only

SummaryThismoduleimplementstheInternetServerextensionAPI.ItallowsInternetServerextensions(e.g.ISAPI.dllmodules)tobeservedbyApacheforWindows,subjecttothenotedrestrictions.

ISAPIextensionmodules(.dllfiles)arewrittenbythirdparties.TheApacheGroupdoesnotauthorthesemodules,soweprovidenosupportforthem.PleasecontacttheISAPI'sauthordirectlyifyouareexperiencingproblemsrunningtheirISAPIextension.PleasedonotpostsuchproblemstoApache'slistsorbugreportingpages.

Usage

Intheserverconfigurationfile,usetheAddHandlerdirectivetoassociateISAPIfileswiththeisapi-handlerhandler,andmapittothemwiththeirfileextensions.Toenableany.dllfiletobeprocessedasanISAPIextension,editthehttpd.conffileandaddthefollowingline:

AddHandlerisapi-handler.dll

InversionsoftheApacheserverpriorto2.0.37,useisapi-isainsteadofisapi-handler.Thenewhandlernameisnotavailablepriortoversion2.0.37.Forcompatibility,configurationsmaycontinueusingisapi-isathroughallversionsofApachepriorto2.3.0.

ThereisnocapabilitywithintheApacheservertoleavearequestedmoduleloaded.However,youmaypreloadandkeepaspecificmoduleloadedbyusingthefollowingsyntaxinyourhttpd.conf:

ISAPICacheFilec:/WebWork/Scripts/ISAPI/mytest.dll

WhetherornotyouhavepreloadedanISAPIextension,allISAPIextensionsaregovernedbythesamepermissionsandrestrictionsasCGIscripts.Thatis,OptionsExecCGImustbesetforthedirectorythatcontainstheISAPI.dllfile.

ReviewtheAdditionalNotesandtheProgrammer'sJournalforadditionaldetailsandclarificationofthespecificISAPIsupportofferedbymod_isapi.

AdditionalNotes

Apache'sISAPIimplementationconformstoalloftheISAPI2.0specification,exceptforsome"Microsoft-specific"extensionsdealingwithasynchronousI/O.Apache'sI/OmodeldoesnotallowasynchronousreadingandwritinginamannerthattheISAPIcouldaccess.IfanISAtriestoaccessunsupportedfeatures,includingasyncI/O,amessageisplacedintheerrorlogtohelpwithdebugging.Sincethesemessagescanbecomeaflood,thedirectiveISAPILogNotSupportedOffexiststoquietthisnoise.

Someservers,likeMicrosoftIIS,loadtheISAPIextensionintotheserverandkeepitloadeduntilmemoryusageistoohigh,orunlessconfigurationoptionsarespecified.ApachecurrentlyloadsandunloadstheISAPIextensioneachtimeitisrequested,unlesstheISAPICacheFiledirectiveisspecified.Thisisinefficient,butApache'smemorymodelmakesthisthemosteffectivemethod.ManyISAPImodulesaresubtlyincompatiblewiththeApacheserver,andunloadingthesemoduleshelpstoensurethestabilityoftheserver.

Also,rememberthatwhileApachesupportsISAPIExtensions,itdoesnotsupportISAPIFilters.Supportforfiltersmaybeaddedatalaterdate,butnosupportisplannedatthistime.

Programmer'sJournal

IfyouareprogrammingApache2.0mod_isapimodules,youmustlimityourcallstoServerSupportFunctiontothefollowingdirectives:

HSE_REQ_SEND_URL_REDIRECT_RESP

Redirecttheusertoanotherlocation.ThismustbeafullyqualifiedURL(e.g.http://server/location).

HSE_REQ_SEND_URL

Redirecttheusertoanotherlocation.ThiscannotbeafullyqualifiedURL,youarenotallowedtopasstheprotocoloraservername(e.g.simply/location).Thisredirectionishandledbytheserver,notthebrowser.

Warning

Intheirrecentdocumentation,MicrosoftappearstohaveabandonedthedistinctionbetweenthetwoHSE_REQ_SEND_URLfunctions.Apachecontinuestotreatthemastwodistinctfunctionswithdifferentrequirementsandbehaviors.

HSE_REQ_SEND_RESPONSE_HEADER

Apacheacceptsaresponsebodyfollowingtheheaderifitfollowstheblankline(twoconsecutivenewlines)intheheadersstringargument.ThisbodycannotcontainNULLs,sincetheheadersargumentisNULLterminated.

HSE_REQ_DONE_WITH_SESSION

Apacheconsidersthisano-op,sincethesessionwillbefinishedwhentheISAPIreturnsfromprocessing.

HSE_REQ_MAP_URL_TO_PATH

Apachewilltranslateavirtualnametoaphysicalname.

HSE_APPEND_LOG_PARAMETER

Thisloggedmessagemaybecapturedinanyofthefollowinglogs:

inthe\"%{isapi-parameter}n\"componentinaCustomLogdirectiveinthe%qlogcomponentwiththeISAPIAppendLogToQueryOndirectiveintheerrorlogwiththeISAPIAppendLogToErrorsOndirective

Thefirstoption,the%{isapi-parameter}ncomponent,isalwaysavailableandpreferred.

HSE_REQ_IS_KEEP_CONN

WillreturnthenegotiatedKeep-Alivestatus.

HSE_REQ_SEND_RESPONSE_HEADER_EX

Willbehaveasdocumented,althoughthefKeepConnflagisignored.

HSE_REQ_IS_CONNECTED

Willreportfalseiftherequesthasbeenaborted.

ApachereturnsFALSEtoanyunsupportedcalltoServerSupportFunction,andsetstheGetLastErrorvaluetoERROR_INVALID_PARAMETER.

ReadClientretrievestherequestbodyexceedingtheinitialbuffer(definedbyISAPIReadAheadBuffer).BasedontheISAPIReadAheadBuffersetting(numberofbytestobufferpriortocallingtheISAPIhandler)shorterrequestsaresentcompletetotheextensionwhenitisinvoked.Iftherequestislonger,theISAPIextensionmustuseReadClienttoretrievetheremainingrequestbody.

WriteClientissupported,butonlywiththeHSE_IO_SYNCflagornooptionflag(valueof0).AnyotherWriteClientrequestwillberejectedwithareturnvalueofFALSE,andaGetLastErrorvalueofERROR_INVALID_PARAMETER.

GetServerVariableissupported,althoughextendedservervariablesdonotexist(asdefinedbyotherservers.)AlltheusualApacheCGIenvironmentvariablesareavailablefromGetServerVariable,aswellastheALL_HTTPandALL_RAWvalues.

Apache2.0mod_isapisupportsadditionalfeaturesintroducedinlaterversionsoftheISAPIspecification,aswellaslimitedemulationofasyncI/OandtheTransmitFilesemantics.ApachealsosupportspreloadingISAPI.dllsforperformance,neitherofwhichwerenotavailableunderApache1.3mod_isapi.

ISAPIAppendLogToErrorsDirective

Description: RecordHSE_APPEND_LOG_PARAMETERrequestsfromISAPIextensionstotheerrorlog

Syntax: ISAPIAppendLogToErrorson|off

Default: ISAPIAppendLogToErrorsoff

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: BaseModule: mod_isapi

RecordHSE_APPEND_LOG_PARAMETERrequestsfromISAPIextensionstotheservererrorlog.

ISAPIAppendLogToQueryDirective

Description: RecordHSE_APPEND_LOG_PARAMETERrequestsfromISAPIextensionstothequeryfield

Syntax: ISAPIAppendLogToQueryon|off

Default: ISAPIAppendLogToQueryon

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: BaseModule: mod_isapi

RecordHSE_APPEND_LOG_PARAMETERrequestsfromISAPIextensionstothequeryfield(appendedtotheCustomLog%qcomponent).

ISAPICacheFileDirective

Description: ISAPI.dllfilestobeloadedatstartupSyntax: ISAPICacheFilefile-path[file-path]

...

Context: serverconfig,virtualhostStatus: BaseModule: mod_isapi

Specifiesaspace-separatedlistoffilenamestobeloadedwhentheApacheserverislaunched,andremainloadeduntiltheserverisshutdown.ThisdirectivemayberepeatedforeveryISAPI.dllfiledesired.Thefullpathnameofeachfileshouldbespecified.Ifthepathnameisnotabsolute,itwillbetreatedrelativetoServerRoot.

ISAPIFakeAsyncDirective

Description: FakeasynchronoussupportforISAPIcallbacksSyntax: ISAPIFakeAsyncon|off

Default: ISAPIFakeAsyncoff

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: BaseModule: mod_isapi

Whilesettoon,asynchronoussupportforISAPIcallbacksissimulated.

ISAPILogNotSupportedDirective

Description: LogunsupportedfeaturerequestsfromISAPIextensions

Syntax: ISAPILogNotSupportedon|off

Default: ISAPILogNotSupportedoff

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: BaseModule: mod_isapi

LogsallrequestsforunsupportedfeaturesfromISAPIextensionsintheservererrorlog.Thismayhelpadministratorstotrackdownproblems.OncesettoonandalldesiredISAPImodulesarefunctioning,itshouldbesetbacktooff.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ISAPIReadAheadBufferDirective

Description: SizeoftheReadAheadBuffersenttoISAPIextensions

Syntax: ISAPIReadAheadBuffersize

Default: ISAPIReadAheadBuffer49152

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: BaseModule: mod_isapi

DefinesthemaximumsizeoftheReadAheadBuffersenttoISAPIextensionswhentheyareinitiallyinvoked.AllremainingdatamustberetrievedusingtheReadClientcallback;someISAPIextensionsmaynotsupporttheReadClientfunction.ReferquestionstotheISAPIextension'sauthor.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_ldap

Description: LDAPconnectionpoolingandresultcachingservicesforusebyotherLDAPmodules

Status: ExperimentalModuleIdentifier: ldap_moduleSourceFile: util_ldap.cCompatibility: Availableinversion2.0.41andlater

SummaryThismodulewascreatedtoimprovetheperformanceofwebsitesrelyingonbackendconnectionstoLDAPservers.InadditiontothefunctionsprovidedbythestandardLDAPlibraries,thismoduleaddsanLDAPconnectionpoolandanLDAPsharedmemorycache.

Toenablethismodule,LDAPsupportmustbecompiledintoapr-util.Thisisachievedbyaddingthe--with-ldapflagtotheconfigurescriptwhenbuildingApache.

SSLsupportrequiresthatmod_ldapbelinkedwithoneofthefollowingLDAPSDKs:OpenLDAPSDK(both1.xand2.x),NovellLDAPSDKortheiPlanet(Netscape)SDK.

ExampleConfiguration

Thefollowingisanexampleconfigurationthatusesmod_ldaptoincreasetheperformanceofHTTPBasicauthenticationprovidedbymod_auth_ldap.

#EnabletheLDAPconnectionpoolandshared

#memorycache.EnabletheLDAPcachestatus

#handler.Requiresthatmod_ldapandmod_auth_ldap

#beloaded.Changethe"yourdomain.example.com"to

#matchyourdomain.

LDAPSharedCacheSize200000

LDAPCacheEntries1024

LDAPCacheTTL600

LDAPOpCacheEntries1024

LDAPOpCacheTTL600

<Location/ldap-status>

SetHandlerldap-status

Orderdeny,allow

Denyfromall

Allowfromyourdomain.example.com

AuthLDAPEnabledon

AuthLDAPURLldap://127.0.0.1/dc=example,dc=com?uid?one

AuthLDAPAuthoritativeon

Requirevalid-user

</Location>

LDAPConnectionPool

LDAPconnectionsarepooledfromrequesttorequest.ThisallowstheLDAPservertoremainconnectedandboundreadyforthenextrequest,withouttheneedtounbind/connect/rebind.TheperformanceadvantagesaresimilartotheeffectofHTTPkeepalives.

OnabusyserveritispossiblethatmanyrequestswilltryandaccessthesameLDAPserverconnectionsimultaneously.WhereanLDAPconnectionisinuse,Apachewillcreateanewconnectionalongsidetheoriginalone.Thisensuresthattheconnectionpooldoesnotbecomeabottleneck.

ThereisnoneedtomanuallyenableconnectionpoolingintheApacheconfiguration.AnymoduleusingthismoduleforaccesstoLDAPserviceswillsharetheconnectionpool.

LDAPCache

Forimprovedperformance,mod_ldapusesanaggressivecachingstrategytominimizethenumberoftimesthattheLDAPservermustbecontacted.CachingcaneasilydoubleortriplethethroughputofApachewhenitisservingpagesprotectedwithmod_auth_ldap.Inaddition,theloadontheLDAPserverwillbesignificantlydecreased.

mod_ldapsupportstwotypesofLDAPcachingduringthesearch/bindphasewithasearch/bindcacheandduringthecomparephasewithtwooperationcaches.EachLDAPURLthatisusedbytheserverhasitsownsetofthesethreecaches.

TheSearch/BindCacheTheprocessofdoingasearchandthenabindisthemosttime-consumingaspectofLDAPoperation,especiallyifthedirectoryislarge.Thesearch/bindcacheisusedtocacheallsearchesthatresultedinsuccessfulbinds.Negativeresults(i.e.,unsuccessfulsearches,orsearchesthatdidnotresultinasuccessfulbind)arenotcached.Therationalebehindthisdecisionisthatconnectionswithinvalidcredentialsareonlyatinypercentageofthetotalnumberofconnections,sobynotcachinginvalidcredentials,thesizeofthecacheisreduced.

mod_ldapstorestheusername,theDNretrieved,thepasswordusedtobind,andthetimeofthebindinthecache.Wheneveranewconnectionisinitiatedwiththesameusername,mod_ldapcomparesthepasswordofthenewconnectionwiththepasswordinthecache.Ifthepasswordsmatch,andifthecachedentryisnottooold,mod_ldapbypassesthesearch/bindphase.

ThesearchandbindcacheiscontrolledwiththeLDAPCacheEntriesandLDAPCacheTTLdirectives.

OperationCachesDuringattributeanddistinguishednamecomparisonfunctions,mod_ldapusestwooperationcachestocachethecompareoperations.ThefirstcomparecacheisusedtocachetheresultsofcomparesdonetotestforLDAPgroupmembership.Thesecondcomparecacheisusedtocachetheresultsofcomparisonsdonebetweendistinguishednames.

ThebehaviorofbothofthesecachesiscontrolledwiththeLDAPOpCacheEntriesandLDAPOpCacheTTLdirectives.

MonitoringtheCachemod_ldaphasacontenthandlerthatallowsadministratorstomonitorthecacheperformance.Thenameofthecontenthandlerisldap-status,sothefollowingdirectivescouldbeusedtoaccessthemod_ldapcacheinformation:

<Location/server/cache-info>

SetHandlerldap-status

</Location>

ByfetchingtheURLhttp://servername/cache-info,theadministratorcangetastatusreportofeverycachethatisusedbymod_ldapcache.NotethatifApachedoesnotsupportsharedmemory,theneachhttpdinstancehasitsowncache,soreloadingtheURLwillresultindifferentinformationeachtime,dependingonwhichhttpdinstanceprocessestherequest.

UsingSSL

TheabilitytocreateanSSLconnectionstoanLDAPserverisdefinedbythedirectivesLDAPTrustedCAandLDAPTrustedCAType.Thesedirectivesspecifythecertificatefileordatabaseandthecertificatetype.WhenevertheLDAPurlincludesldaps://,mod_ldapwillestablishasecureconnectiontotheLDAPserver.

#EstablishanSSLLDAPconnection.Requiresthat

#mod_ldapandmod_auth_ldapbeloaded.Changethe

#"yourdomain.example.com"tomatchyourdomain.

LDAPTrustedCA/certs/certfile.der

LDAPTrustedCATypeDER_FILE

<Location/ldap-status>

SetHandlerldap-status

Orderdeny,allow

Denyfromall

Allowfromyourdomain.example.com

AuthLDAPEnabledon

AuthLDAPURLldaps://127.0.0.1/dc=example,dc=com?uid?one

AuthLDAPAuthoritativeon

Requirevalid-user

</Location>

Ifmod_ldapislinkedagainsttheNetscape/iPlanetLDAPSDK,itwillnottalktoanySSLserverunlessthatserverhasacertificatesignedbyaknownCertificateAuthority.Aspartoftheconfigurationmod_ldapneedstobetoldwhereitcanfindadatabasecontainingtheknownCAs.ThisdatabaseisinthesameformatasNetscapeCommunicator'scert7.dbdatabase.TheeasiestwaytogetthisfileistostartupafreshcopyofNetscape,andgrabtheresulting$HOME/.netscape/cert7.dbfile.

LDAPCacheEntriesDirective

Description: MaximumnumberofentriesintheprimaryLDAPcache

Syntax: LDAPCacheEntriesnumber

Default: LDAPCacheEntries1024

Context: serverconfigStatus: ExperimentalModule: mod_ldap

SpecifiesthemaximumsizeoftheprimaryLDAPcache.Thiscachecontainssuccessfulsearch/binds.Setitto0toturnoffsearch/bindcaching.Thedefaultsizeis1024cachedsearches.

LDAPCacheTTLDirective

Description: TimethatcacheditemsremainvalidSyntax: LDAPCacheTTLseconds

Default: LDAPCacheTTL600

Context: serverconfigStatus: ExperimentalModule: mod_ldap

Specifiesthetime(inseconds)thataniteminthesearch/bindcacheremainsvalid.Thedefaultis600seconds(10minutes).

LDAPConnectionTimeoutDirective

Description: SpecifiesthesocketconnectiontimeoutinsecondsSyntax: LDAPConnectionTimeoutseconds

Context: serverconfigStatus: ExperimentalModule: mod_ldap

Specifiesthetimeoutvalue(inseconds)inwhichthemodulewillattempttoconnecttotheLDAPserver.Ifaconnectionisnotsuccessfulwiththetimeoutperiod,eitheranerrorwillbereturnedorthemodulewillattempttoconnecttoasecondaryLDAPserverifoneisspecified.Thedefaultis10seconds.

LDAPOpCacheEntriesDirective

Description: NumberofentriesusedtocacheLDAPcompareoperations

Syntax: LDAPOpCacheEntriesnumber

Default: LDAPOpCacheEntries1024

Context: serverconfigStatus: ExperimentalModule: mod_ldap

Thisspecifiesthenumberofentriesmod_ldapwillusetocacheLDAPcompareoperations.Thedefaultis1024entries.Settingitto0disablesoperationcaching.

LDAPOpCacheTTLDirective

Description: Timethatentriesintheoperationcacheremainvalid

Syntax: LDAPOpCacheTTLseconds

Default: LDAPOpCacheTTL600

Context: serverconfigStatus: ExperimentalModule: mod_ldap

Specifiesthetime(inseconds)thatentriesintheoperationcacheremainvalid.Thedefaultis600seconds.

LDAPSharedCacheFileDirective

Description: SetsthesharedmemorycachefileSyntax: LDAPSharedCacheFiledirectory-

path/filename

Context: serverconfigStatus: ExperimentalModule: mod_ldap

Specifiesthedirectorypathandfilenameofthesharedmemorycachefile.Ifnotset,anonymoussharedmemorywillbeusediftheplatformsupportsit.

LDAPSharedCacheSizeDirective

Description: Sizeinbytesoftheshared-memorycacheSyntax: LDAPSharedCacheSizebytes

Default: LDAPSharedCacheSize102400

Context: serverconfigStatus: ExperimentalModule: mod_ldap

Specifiesthenumberofbytestoallocateforthesharedmemorycache.Thedefaultis100kb.Ifsetto0,sharedmemorycachingwillnotbeused.

LDAPTrustedCADirective

Description: SetsthefilecontainingthetrustedCertificateAuthoritycertificateordatabase

Syntax: LDAPTrustedCAdirectory-path/filename

Context: serverconfigStatus: ExperimentalModule: mod_ldap

ItspecifiesthedirectorypathandfilenameofthetrustedCAmod_ldapshouldusewhenestablishinganSSLconnectiontoanLDAPserver.IfusingtheNetscape/iPlanetDirectorySDK,thefilenameshouldbecert7.db.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

LDAPTrustedCATypeDirective

Description: SpecifiesthetypeoftheCertificateAuthorityfileSyntax: LDAPTrustedCATypetype

Context: serverconfigStatus: ExperimentalModule: mod_ldap

Thefollowingtypesaresupported:DER_FILE-fileinbinaryDERformatBASE64_FILE-fileinBase64formatCERT7_DB_PATH-Netscapecertificatedatabasefile")

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_log_config

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

:: Base: log_config_module: mod_log_config.c

: TransferLog

TransferLog CustomLog

Apache

LogFormat CustomLog

" %" "%"

%% ( Apache2.0.44)%...a IP%...A IP%...B HTTP%...b HTTPCLF 10%...

{Foobar}C

Foobar

%...D

%...

{FOOBAR}e

FOOBAR

%...f

%...h

%...H

%...

{Foobar}i

Foobar:

%...l (identd) IdentityCheck

-%...m

%...

{Foobar}n

Foobar

%...

{Foobar}o

Foobar:

%...p

%...P ID%...

{format}P IDID format2.0.46 )

%...q ( ? )%...r

%...s ---%...t CLF()%...

{format}t

formatformat strftime(3)

%...T

%...u (( %s) 401)%...U URL%...v ServerName

%...V UseCanonicalName%...X :

X=+=-=

(Apache 1.3{var}c)

%...I 0%...O 0

"..."( "%h%u%r%s%b") ("!" "%400,501{User-agent}i"400501RequestNotImplemented) User-agent:"%!200,304,302{Referer}i" Referer:

"<"">"

%>s

httpd2.01.3.25 %...r,%...i,%...oLogFormat

2.0.46 C( \n,\t)

:

CommonLogFormat(CLF)"%h%l%u%t\"%r\"%>s%b"

CommonLogFormat"%v%h%l%u%t\"%r\"%>s%b"

NCSAextended/combined"%h%l%u%t\"%r\"%>s%b\"%{Referer}i\"

\"%{User-agent}i\""

Referer"%{Referer}i->%U"

Agent()"%{User-agent}i"

%v %p ServerName

UseCanonicalName

BufferedLogs

: Bufferlogentriesinmemorybeforewritingtodisk: BufferedLogsOn|Off

: BufferedLogsOff

:: Base: mod_log_config: Availableinversions2.0.41andlater.

Thedocumentationforthisdirectivehasnotbeentranslatedyet.PleasehavealookattheEnglishversion.

CookieLog

:: CookieLogfilename

: ,: Base: mod_log_config:

CookieLog filename

CustomLog

:: CustomLogfile|pipeformat|nickname[env=

[!]environment-variable]

: ,: Base: mod_log_config

CustomLog

:

fileServerRoot

pipe" |"

httpd

Unix

LogFormat

:

#CustomLogwithformatnickname

LogFormat"%h%l%u%t\"%r\"%>s%b"common

CustomLoglogs/access_logcommon

#CustomLogwithexplicitformatstring

CustomLoglogs/access_log"%h%l%u%t\"%r\"%>s%b"

mod_setenvif mod_rewrite

SetEnvIfRequest_URI\.gif$gif-image

CustomLoggif-requests.logcommonenv=gif-image

CustomLognongif-requests.logcommonenv=!gif-image

LogFormat

:: LogFormatformat|nickname[nickname]

: LogFormat"%h%l%u%t\"%r\"%>s%b"

: ,: Base: mod_log_config

LogFormat LogFormat nickname

LogFormat format nickname LogFormat CustomLog nicknameNickname (

LogFormat"%v%h%l%u%t\"%r\"%>s%b"vhost_common

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

TransferLog

:: TransferLogfile|pipe

: ,: Base: mod_log_config

LogFormat

LogFormat"%h%l%u%t\"%r\"%>s%b\"%{Referer}i\"\"%{User-

agent}i\""

TransferLoglogs/access_log

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_log_forensic

Description: ForensicLoggingoftherequestsmadetotheserver

Status: ExtensionModuleIdentifier: log_forensic_moduleSourceFile: mod_log_forensic.cCompatibility: Availableinversion2.0.50andlater

SummaryThismoduleprovidesforforensicloggingofclientrequests.Loggingisdonebeforeandafterprocessingarequest,sotheforensiclogcontainstwologlinesforeachrequest.Theforensicloggerisverystrict,whichmeans:

Theformatisfixed.Youcannotmodifytheloggingformatatruntime.Ifitcannotwriteitsdata,thechildprocessexitsimmediatelyandmaydumpcore(dependingonyourCoreDumpDirectoryconfiguration).

Thecheck_forensicscript,whichcanbefoundinthedistribution'ssupportdirectory,maybehelpfulinevaluatingtheforensiclogoutput.

Thismodulewasbackportedfromversion2.1whichusesamorepowerfulAPRversioninordertogeneratetheforensicIDs.Ifyouwanttorunmod_log_forensicinversion2.0,youneedtoincludemod_unique_idaswell.

SeealsoApacheLogFiles

mod_log_config

ForensicLogFormat

Eachrequestisloggedtwotimes.Thefirsttimeisbeforeit'sprocessedfurther(thatis,afterreceivingtheheaders).Thesecondlogentryiswrittenaftertherequestprocessingatthesametimewherenormalloggingoccurs.

Inordertoidentifyeachrequest,auniquerequestIDisassigned.ThisforensicIDcanbecrossloggedinthenormaltransferlogusingthe%{forensic-id}nformatstring.Ifyou'reusingmod_unique_id,itsgeneratedIDwillbeused.

ThefirstlinelogstheforensicID,therequestlineandallreceivedheaders,separatedbypipecharacters(|).Asamplelinelookslikethefollowing(allononeline):

+yQtJf8CoAB4AAFNXBIEAAAAA|GET/manual/de/images/down.gif

HTTP/1.1|Host:localhost%3a8080|User-Agent:Mozilla/5.0(X11;U;

Linuxi686;en-US;rv%3a1.6)Gecko/20040216

Firefox/0.8|Accept:image/png,etc...

Thepluscharacteratthebeginningindicatesthatthisisthefirstloglineofthisrequest.ThesecondlinejustcontainsaminuscharacterandtheIDagain:

-yQtJf8CoAB4AAFNXBIEAAAAA

Thecheck_forensicscripttakesasitsargumentthenameofthelogfile.Itlooksforthose+/-IDpairsandcomplainsifarequestwasnotcompleted.

SecurityConsiderations

Seethesecuritytipsdocumentfordetailsonwhyyoursecuritycouldbecompromisedifthedirectorywherelogfilesarestorediswritablebyanyoneotherthantheuserthatstartstheserver.

ForensicLogDirective

Description: SetsfilenameoftheforensiclogSyntax: ForensicLogfilename|pipe

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_log_forensic

TheForensicLogdirectiveisusedtologrequeststotheserverforforensicanalysis.EachlogentryisassignedauniqueIDwhichcanbeassociatedwiththerequestusingthenormalCustomLogdirective.mod_log_forensictakestheuniqueIDfrommod_unique_id,soyouneedtoloadthismoduleaswell.(Thisrequirementwillnotbenecessaryinversion2.1andlater,becauseofamorepowerfulAPRversion.)TheIDtokenisattachedtotherequestunderthenameforensic-id,whichcanbeaddedtothetransferlogusingthe%{forensic-id}nformatstring.

Theargument,whichspecifiesthelocationtowhichthelogswillbewritten,cantakeoneofthefollowingtwotypesofvalues:

filenameAfilename,relativetotheServerRoot.

pipeThepipecharacter"|",followedbythepathtoaprogramtoreceivetheloginformationonitsstandardinput.TheprogramnamecanbespecifiedrelativetotheServerRootdirective.

Security:

Ifaprogramisused,thenitwillberunastheuserwhostartedhttpd.Thiswillberootiftheserverwasstartedbyroot;besurethattheprogramissecureorswitchestoa

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

lessprivilegeduser.

Note

Whenenteringafilepathonnon-Unixplatforms,careshouldbetakentomakesurethatonlyforwardslashedareusedeventhoughtheplatformmayallowtheuseofbackslashes.Ingeneralitisagoodideatoalwaysuseforwardslashesthroughouttheconfigurationfiles.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_logio

:: Extension: logio_module: mod_logio.c

mod_log_config

mod_log_config

Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

%...I 0

%...O 0

:

I/O:"%h%l%u%t\"%r\"%>s%b\"%{Referer}i\"

\"%{User-agent}i\"%I%O"

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_mem_cache

: URI: Experimental: mem_cache_module: mod_mem_cache.c

...

mod_cache mod_cache mod_proxy ProxyPass( )

URI

mod_cache

mod_disk_cache

MCacheMaxObjectCount

:: MCacheMaxObjectCountvalue

: MCacheMaxObjectCount1009

:: Experimental: mod_mem_cache

MCacheMaxObjectCount MCacheRemovalAlgorithm

MCacheMaxObjectCount13001

MCacheMaxObjectSize

: (): MCacheMaxObjectSizebytes

: MCacheMaxObjectSize10000

:: Experimental: mod_mem_cache

MCacheMaxObjectSize

MCacheMaxObjectSize6400000

MCacheMaxObjectSize MCacheMinObjectSize

MCacheMaxStreamingBuffer

: : MCacheMaxStreamingBuffersize_in_bytes

: MCacheMaxStreamingBufferof100000

MCacheMaxObjectSize

:: Experimental: mod_mem_cache

MCacheMaxStreamingBuffer Length MCacheMaxStreamingBuffer Content-Length

:

MCacheMaxStreamingBuffer

#Enablecachingofstreamedresponsesupto64KB:

MCacheMaxStreamingBuffer65536

MCacheMinObjectSize

: (): MCacheMinObjectSizebytes

: MCacheMinObjectSize0

:: Experimental: mod_mem_cache

MCacheMinObjectSize

MCacheMinObjectSize10000

MCacheRemovalAlgorithm

:: MCacheRemovalAlgorithmLRU|GDSF

: MCacheRemovalAlgorithmGDSF

:: Experimental: mod_mem_cache

MCacheRemovalAlgorithm

LRU(LeastRecentlyUsed)LRU

GDSF(GreadyDual-Size)GDSF

MCacheRemovalAlgorithmGDSF

MCacheRemovalAlgorithmLRU

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

MCacheSize

:: MCacheSizeKBytes

: MCacheSize100

:: Experimental: mod_mem_cache

MCacheSize (1024)MCacheRemovalAlgorithm

MCacheSize700000

MCacheSize MCacheMaxObjectSize

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_mime

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: ()(MIME)

: Base: mime_module: mod_mime.c

AddCharset AddEncoding AddHandlerAddLanguage AddType content-encoding,content-language,MIME(content-type)TypesConfig MIME

mod_mime AddHandler

AddInputFilter mod_negotiationMultiviews

mod_mime core (,<Location> SetOutputFilter mod_mime

Last-Modified 'touch' ()

MimeMagicFile

AddDefaultCharset

ForceType

DefaultType

SetHandler

SetInputFilter

SetOutputFilter

welcome.html.fr text/htmlwelcome.fr.html

image/gif .htmlMIME text/htmlwelcome.gif.html MIME text/html

en,de Content-Type:text/html

MIME .htmlMIME text/html world.imap.html

imap-file text/htmlMIMEmod_imap

MIME UUencoding

HTTP/1.1RFC14.11

Content-Encoding Content-Encoding

( )

MicrosoftWord pkzip.zip pkzip

Apache

Content-encoding:pkzip

mime (MIME AddType ( MimeMagicFile

AddInputFilter,AddOutputFilter

CharsetApache Content-Language

Content-Language:en,fr

Content-Type:text/plain;charset=ISO-8859-1

charset

AddCharset

:: AddCharsetcharsetextension[extension]...

: ,,,.htaccess: FileInfo: Base: mod_mime

AddCharset charsetMIMEcharset

AddLanguageja.ja

AddCharsetEUC-JP.euc

AddCharsetISO-2022-JP.jis

AddCharsetSHIFT_JIS.sjis

xxxx.ja.jischarset ISO-2022-JP(xxxx.jis.ja) AddCharsetcharset

extension

mod_negotiation

AddDefaultCharset

AddEncoding

: : AddEncodingMIME-encextension[extension]

...

: ,,,.htaccess: FileInfo: Base: mod_mime

AddEncoding extension

AddEncodingx-gzip.gz

AddEncodingx-compress.Z

.gz x-gzip

x-zip x-compress x-Apache compress deflate

extension

AddHandler

:: AddHandlerhandler-nameextension[extension]

...

: ,,,.htaccess: FileInfo: Base: mod_mime

extension handler-name ".cgi"CGI

AddHandlercgi-script.cgi

httpd.conf ".cgi"CGI

extension

SetHandler

AddInputFilter

: : AddInputFilterfilter[;filter...]extension

[extension]...

: ,,,.htaccess: FileInfo: Base: mod_mime: 2.0.26

AddInputFilter extensionPOSTSetInputFilter

RemoveInputFilter

SetInputFilter

AddLanguage

:: AddLanguageMIME-langextension[extension]

...

: ,,,.htaccess: FileInfo: Base: mod_mime

AddLanguage contentlanguageextensionMIME

AddEncodingx-compress.Z

AddLanguageen.en

AddLanguagefr.fr

xxxx.en.Zcompress (language

AddLanguageen.en

AddLanguageen-gb.en

AddLanguageen-us.en

.en en-us

extension

mod_negotiation

AddOutputFilter

: : AddOutputFilterfilter[;filter...]extension

[extension]...

: ,,,.htaccess: FileInfo: Base: mod_mime: 2.0.26

AddOutputFilter extension AddOutputFilterByType

.shtmlSSI mod_deflate

AddOutputFilterINCLUDES;DEFLATEshtml

RemoveOutputFilter

SetOutputFilter

AddType

:: AddTypeMIME-typeextension[extension]...

: ,,,.htaccess: FileInfo: Base: mod_mime

AddType extension MIME(

AddTypeimage/gif.gif

MIME TypesConfig AddType

extension

DefaultType

ForceType

DefaultLanguage

: : DefaultLanguageMIME-lang

: ,,,.htaccess: FileInfo: Base: mod_mime

DefaultLanguageApache ((AddLanguage .fr .de) MIME-lang DefaultLanguage

DefaultLanguage AddLanguage

DefaultLanguageen

mod_negotiation

ModMimeUsePathInfo

: path_infomod_mime: ModMimeUsePathInfoOn|Off

: ModMimeUsePathInfoOff

:: Base: mod_mime: Apache2.0.41

ModMimeUsePathInfo mod_mimeURL Off path_info

ModMimeUsePathInfoOn

/bar(foo.shtml) ModMimeUsePathInfo On

/bar/foo.shtml mod_mimeAddOutputFileterINCLUDES.shtml INCLUDES

ModMimeUsePathInfo INCLUDES

AcceptPathInfo

MultiviewsMatch

: MultiViews: MultiviewsMatch

Any|NegotiatedOnly|Filters|Handlers

[Handlers|Filters]

: MultiviewsMatchNegotiatedOnly

: ,,,.htaccess: FileInfo: Base: mod_mime: 2.0.26

MultiviewsMatch mod_negotiation Multiviews3Multiviews( index.html)index.html.fr index.html.gz)

NegotiatedOnly

MultiviewsMatch

500 index.html.cgi1000 index.html.pl.cgi .asis .asis

mod_mime Any

.bak

Multiviews

MultiviewsMatchHandlersFilters

Options

mod_negotiation

RemoveCharset

: : RemoveCharsetextension[extension]...

: ,,.htaccess: FileInfo: Base: mod_mime: 2.0.24

RemoveCharset

extension

RemoveCharset.html.shtml

RemoveEncoding

: : RemoveEncodingextension[extension]...

: ,,.htaccess: FileInfo: Base: mod_mime

RemoveEncoding

/foo/.htaccess:AddEncodingx-gzip.gz

AddTypetext/plain.asc

<Files*.gz.asc>

RemoveEncoding.gz

</Files>

foo.gzgzip foo.gz.asc

RemoveEncoding AddEncoding

extension

RemoveHandler

: : RemoveHandlerextension[extension]...

: ,,.htaccess: FileInfo: Base: mod_mime

RemoveHandler

/foo/.htaccess:AddHandlerserver-parsed.html

/foo/bar/.htaccess:RemoveHandler.html

/foo/bar .htmlSSI( mod_include)

extension

RemoveInputFilter

:: RemoveInputFilterextension[extension]...

: ,,.htaccess: FileInfo: Base: mod_mime: 2.0.26

RemoveInputFilter

extension

AddInputFilter

SetInputFilter

RemoveLanguage

:: RemoveLanguageextension[extension]...

: ,,.htaccess: FileInfo: Base: mod_mime: 2.0.24

RemoveLanguage

extension

RemoveOutputFilter

:: RemoveOutputFilterextension[extension]...

: ,,.htaccess: FileInfo: Base: mod_mime: 2.0.26

RemoveOutputFilter

extension

RemoveOutputFiltershtml

AddOutputFilter

RemoveType

: : RemoveTypeextension[extension]...

: ,,.htaccess: FileInfo: Base: mod_mime

RemoveType MIME

/foo/.htaccess:RemoveType.cgi

/foo/ .cgi DefaultType

RemoveType AddType

extension

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

TypesConfig

: mime.types: TypesConfigfile-path

: TypesConfigconf/mime.types

:: Base: mod_mime

TypesConfigMIME IANAhttp://www.isi.edu/in-notes/iana/assignments/media-types/media-types mime.types

AddType

MIME-type[extension]...

(`#')

(1)IANA(2) ServerProject category/x-subtype

mod_mime_magic

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_mime_magic

Description: DeterminestheMIMEtypeofafilebylookingatafewbytesofitscontents

Status: ExtensionModuleIdentifier: mime_magic_moduleSourceFile: mod_mime_magic.c

SummaryThismoduledeterminestheMIMEtypeoffilesinthesamewaytheUnixfile(1)commandworks:itlooksatthefirstfewbytesofthefile.Itisintendedasa"secondlineofdefense"forcasesthatmod_mimecan'tresolve.

Thismoduleisderivedfromafreeversionofthefile(1)commandforUnix,whichuses"magicnumbers"andotherhintsfromafile'scontentstofigureoutwhatthecontentsare.ThismoduleisactiveonlyifthemagicfileisspecifiedbytheMimeMagicFiledirective.

FormatoftheMagicFile

ThecontentsofthefileareplainASCIItextin4-5columns.Blanklinesareallowedbutignored.Commentedlinesuseahashmark(#).Theremaininglinesareparsedforthefollowingcolumns:

Column Description1 bytenumbertobegincheckingfrom

">"indicatesadependencyuponthepreviousnon-">"line

2 typeofdatatomatch

byte singlecharactershort machine-order16-bitintegerlong machine-order32-bitintegerstring arbitrary-lengthstringdate longintegerdate(secondssinceUnix

epoch/1970)beshort big-endian16-bitintegerbelong big-endian32-bitintegerbedate big-endian32-bitintegerdateleshort little-endian16-bitintegerlelong little-endian32-bitintegerledate little-endian32-bitintegerdate

3 contentsofdatatomatch4 MIMEtypeifmatched5 MIMEencodingifmatched(optional)

Forexample,thefollowingmagicfilelineswouldrecognizesomeaudioformats:

#Sun/NeXTaudiodata

0string.snd

>12belong1audio/basic

>12belong2audio/basic

>12belong3audio/basic

>12belong4audio/basic

>12belong5audio/basic

>12belong6audio/basic

>12belong7audio/basic

>12belong23audio/x-adpcm

Orthesewouldrecognizethedifferencebetween*.docfilescontainingMicrosoftWordorFrameMakerdocuments.(Theseareincompatiblefileformatswhichusethesamefilesuffix.)

#Frame

0string\<MakerFileapplication/x-frame

0string\<MIFFileapplication/x-frame

0string\<MakerDictionaryapplication/x-frame

0string\<MakerScreenFonapplication/x-frame

0string\<MMLapplication/x-frame

0string\<Bookapplication/x-frame

0string\<Makerapplication/x-frame

#MS-Word

0string\376\067\0\043application/msword

0string\320\317\021\340\241\261application/msword

0string\333\245-\0\0\0application/msword

AnoptionalMIMEencodingcanbeincludedasafifthcolumn.Forexample,thiscanrecognizegzippedfilesandsettheencodingforthem.

#gzip(GNUzip,nottobeconfusedwith

#[Info-ZIP/PKWARE]ziparchiver)

0string\037\213application/octet-streamx-gzip

PerformanceIssues

Thismoduleisnotforeverysystem.Ifyoursystemisbarelykeepingupwithitsloadorifyou'reperformingawebserverbenchmark,youmaynotwanttoenablethisbecausetheprocessingisnotfree.

However,aneffortwasmadetoimprovetheperformanceoftheoriginalfile(1)codetomakeitfitinabusywebserver.Itwasdesignedforaserverwheretherearethousandsofuserswhopublishtheirowndocuments.Thisisprobablyverycommononintranets.Manytimes,it'shelpfuliftheservercanmakemoreintelligentdecisionsaboutafile'scontentsthanthefilenameallows...evenifjusttoreducethe"whydoesn'tmypagework"callswhenusersimproperlynametheirownfiles.Youhavetodecideiftheextraworksuitsyourenvironment.

Notes

Thefollowingnotesapplytothemod_mime_magicmoduleandareincludedhereforcompliancewithcontributors'copyrightrestrictionsthatrequiretheiracknowledgment.

mod_mime_magic:MIMEtypelookupviafilemagicnumbersCopyright(c)1996-1997CiscoSystems,Inc.

ThissoftwarewassubmittedbyCiscoSystemstotheApacheGroupinJuly1997.FuturerevisionsandderivativesofthissourcecodemustacknowledgeCiscoSystemsastheoriginalcontributorofthismodule.AllotherlicensingandusageconditionsarethoseoftheApacheGroup.

Someofthiscodeisderivedfromthefreeversionofthefilecommandoriginallypostedtocomp.sources.unix.Copyrightinfoforthatprogramisincludedbelowasrequired.

-Copyright(c)IanF.Darwin,1987.WrittenbyIanF.Darwin.

ThissoftwareisnotsubjecttoanylicenseoftheAmericanTelephoneandTelegraphCompanyoroftheRegentsoftheUniversityofCalifornia.

Permissionisgrantedtoanyonetousethissoftwareforanypurposeonanycomputersystem,andtoalteritandredistributeitfreely,subjecttothefollowingrestrictions:

1. Theauthorisnotresponsiblefortheconsequencesofuseofthissoftware,nomatterhowawful,eveniftheyarisefromflawsinit.

2. Theoriginofthissoftwaremustnotbemisrepresented,eitherbyexplicitclaimorbyomission.Sincefewuserseverreadsources,creditsmustappearinthedocumentation.

3. Alteredversionsmustbeplainlymarkedassuch,andmust

notbemisrepresentedasbeingtheoriginalsoftware.Sincefewuserseverreadsources,creditsmustappearinthedocumentation.

4. Thisnoticemaynotberemovedoraltered.

ForcompliancewithMrDarwin'sterms:thishasbeenverysignificantlymodifiedfromthefree"file"command.

all-in-onefileforcompilationconveniencewhenmovingfromoneversionofApachetothenext.MemoryallocationisdonethroughtheApacheAPI'spoolstructure.AllfunctionshavehadnecessaryApacheAPIrequestorserverstructurespassedtothemwherenecessarytocallotherApacheAPIroutines.(i.e.,usuallyforlogging,files,ormemoryallocationinitselforacalledfunction.)structmagichasbeenconvertedfromanarraytoasingle-endedlinkedlistbecauseitonlygrowsonerecordatatime,it'sonlyaccessedsequentially,andtheApacheAPIhasnoequivalentofrealloc().Functionshavebeenchangedtogettheirparametersfromtheserverconfigurationinsteadofglobals.(Itshouldbereentrantnowbuthasnotbeentestedinathreadedenvironment.)Placeswhereitusedtoprintresultstostdoutnowsavestheminalistwherethey'reusedtosettheMIMEtypeintheApacherequestrecord.Command-lineflagshavebeenremovedsincetheywillneverbeusedhere.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

MimeMagicFileDirective

Description: EnableMIME-typedeterminationbasedonfilecontentsusingthespecifiedmagicfile

Syntax: MimeMagicFilefile-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_mime_magic

TheMimeMagicFiledirectivecanbeusedtoenablethismodule,thedefaultfileisdistributedatconf/magic.Non-rootedpathsarerelativetotheServerRoot.Virtualhostswillusethesamefileasthemainserverunlessamorespecificsettingisused,inwhichcasethemorespecificsettingoverridesthemainserver'sfile.

ExampleMimeMagicFileconf/magic

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_negotiation

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: : Base: negotiation_module: mod_negotiation.c

( type-map)variantsMultiViews( MultiViewsOption)

Options

mod_mime

RFC822 :

Content-Encoding:

Apache AddEncoding compresscompressgzip x-gzip

Content-Language:

(RFC1766)

Content-Length:

()

Content-Type:

MIME

level

text/html2

qs

variant 0.01.0 ASCIIASCII

Content-Type:image/jpeg;qs=0.8

URI:

()variant uri.

Body:

Apache2.0Body

Example:Body:----xyz----

<html>

<body>

<p>Contentofthepage.</p>

</body>

</html>

----xyz----

MultiViews

MultiViews MultiviewsOptions/some/dir/foo

CacheNegotiatedDocs

: : CacheNegotiatedDocsOn|Off

: CacheNegotiatedDocsOff

: ,: Base: mod_negotiation: 2.0

HTTP/1.0 HTTP/1.1

2.0 CacheNegotiatedDocs on

ForceLanguagePriority

:: ForceLanguagePriorityNone|Prefer|Fallback

[Prefer|Fallback]

: ForceLanguagePriorityPrefer

: ,,,.htaccess: FileInfo: Base: mod_negotiation: 2.0.30

ForceLanguagePriority

ForceLanguagePriorityPrefer HTTP300(MULTIPLECHOICES) LanguagePriorityAccept-Language en de .500()

LanguagePriorityenfrde

ForceLanguagePriorityPrefer

ForceLanguagePriorityFallbackHTTP406 (NOTACCEPTABLE) LanguagePriorityLanguage esvariantvariant

LanguagePriorityenfrde

ForceLanguagePriorityFallback

Prefer Fallback variant variantvaiant

AddLanguage

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

LanguagePriority

: variant: LanguagePriorityMIME-lang[MIME-lang]...

: ,,,.htaccess: FileInfo: Base: mod_negotiation

LanguagePriorityMultiViews

Example:LanguagePriorityenfrde

foo.html foo.html.fr foo.html.defoo.html.fr

ForceLanguagePriority

AddLanguage

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_nw_ssl

Description: EnableSSLencryptionforNetWareStatus: BaseModuleIdentifier: nwssl_moduleSourceFile: mod_nw_ssl.cCompatibility: NetWareonly

SummaryThismoduleenablesSSLencryptionforaspecifiedport.IttakesadvantageoftheSSLencryptionfunctionalitythatisbuiltintotheNetWareoperatingsystem.

NWSSLTrustedCertsDirective

Description: ListofadditionalclientcertificatesSyntax: NWSSLTrustedCertsfilename[filename]

...

Context: serverconfigStatus: BaseModule: mod_nw_ssl

Specifiesalistofclientcertificatefiles(DERformat)thatareusedwhencreatingaproxiedSSLconnection.Eachclientcertificateusedbyaservermustbelistedseparatelyinitsown.derfile.

NWSSLUpgradeableDirective

Description: AllowsaconnectiontobeupgradedtoanSSLconnectionuponrequest

Syntax: NWSSLUpgradeable[IP-

address:]portnumber

Context: serverconfigStatus: BaseModule: mod_nw_ssl

Allowaconnectionthatwascreatedonthespecifiedaddressand/orporttobeupgradedtoanSSLconnectionuponrequestfromtheclient.Theaddressand/orportmusthavealreadybedefinedpreviouslywithaListendirective.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

SecureListenDirective

Description: EnablesSSLencryptionforthespecifiedportSyntax: SecureListen[IP-address:]portnumber

Certificate-Name[MUTUAL]

Context: serverconfigStatus: BaseModule: mod_nw_ssl

SpecifiestheportandtheeDirectorybasedcertificatenamethatwillbeusedtoenableSSLencryption.Anoptionalthirdparameteralsoenablesmutualauthentication.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_proxy

Description: HTTP/1.1proxy/gatewayserverStatus: ExtensionModuleIdentifier: proxy_moduleSourceFile: mod_proxy.c

Summary

Warning

DonotenableproxyingwithProxyRequestsuntilyouhavesecuredyourserver.OpenproxyserversaredangerousbothtoyournetworkandtotheInternetatlarge.

Thismoduleimplementsaproxy/gatewayforApache.ItimplementsproxyingcapabilityforFTP,CONNECT(forSSL),HTTP/0.9,HTTP/1.0,andHTTP/1.1.Themodulecanbeconfiguredtoconnecttootherproxymodulesfortheseandotherprotocols.

Apache'sproxyfeaturesaredividedintoseveralmodulesinadditiontomod_proxy:mod_proxy_http,mod_proxy_ftpandmod_proxy_connect.Thus,ifyouwanttouseoneormoreoftheparticularproxyfunctions,loadmod_proxyandtheappropriatemodule(s)intotheserver(eitherstaticallyatcompile-timeordynamicallyviatheLoadModuledirective).

Inaddition,extendedfeaturesareprovidedbyothermodules.Cachingisprovidedbymod_cacheandrelatedmodules.TheabilitytocontactremoteserversusingtheSSL/TLSprotocolisprovidedbytheSSLProxy*directivesofmod_ssl.Theseadditionalmoduleswillneedtobeloadedandconfiguredtotakeadvantageofthesefeatures.

Seealsomod_cache

mod_proxy_http

mod_proxy_ftp

mod_proxy_connect

mod_ssl

ForwardandReverseProxies

Apachecanbeconfiguredinbothaforwardandreverseproxymode.

Anordinaryforwardproxyisanintermediateserverthatsitsbetweentheclientandtheoriginserver.Inordertogetcontentfromtheoriginserver,theclientsendsarequesttotheproxynamingtheoriginserverasthetargetandtheproxythenrequeststhecontentfromtheoriginserverandreturnsittotheclient.Theclientmustbespeciallyconfiguredtousetheforwardproxytoaccessothersites.

AtypicalusageofaforwardproxyistoprovideInternetaccesstointernalclientsthatareotherwiserestrictedbyafirewall.Theforwardproxycanalsousecaching(asprovidedbymod_cache)toreducenetworkusage.

TheforwardproxyisactivatedusingtheProxyRequestsdirective.Becauseforwardproxysallowclientstoaccessarbitrarysitesthroughyourserverandtohidetheirtrueorigin,itisessentialthatyousecureyourserversothatonlyauthorizedclientscanaccesstheproxybeforeactivatingaforwardproxy.

Areverseproxy,bycontrast,appearstotheclientjustlikeanordinarywebserver.Nospecialconfigurationontheclientisnecessary.Theclientmakesordinaryrequestsforcontentinthename-spaceofthereverseproxy.Thereverseproxythendecideswheretosendthoserequests,andreturnsthecontentasifitwasitselftheorigin.

AtypicalusageofareverseproxyistoprovideInternetusersaccesstoaserverthatisbehindafirewall.Reverseproxiescanalsobeusedtobalanceloadamongseveralback-endservers,ortoprovidecachingforaslowerback-endserver.Inaddition,reverseproxiescanbeusedsimplytobringseveralserversinto

thesameURLspace.

AreverseproxyisactivatedusingtheProxyPassdirectiveorthe[P]flagtotheRewriteRuledirective.ItisnotnecessarytoturnProxyRequestsoninordertoconfigureareverseproxy.

BasicExamples

Theexamplesbelowareonlyaverybasicideatohelpyougetstarted.Pleasereadthedocumentationontheindividualdirectives.

Inaddition,ifyouwishtohavecachingenabled,consultthedocumentationfrommod_cache.

ForwardProxyProxyRequestsOn

ProxyViaOn

<Proxy*>

Orderdeny,allow

Denyfromall

Allowfrominternal.example.com

</Proxy>

ReverseProxyProxyRequestsOff

<Proxy*>

Orderdeny,allow

Allowfromall

</Proxy>

ProxyPass/foohttp://foo.example.com/bar

ProxyPassReverse/foohttp://foo.example.com/bar

Controllingaccesstoyourproxy

Youcancontrolwhocanaccessyourproxyviathe<Proxy>controlblockasinthefollowingexample:

<Proxy*>

OrderDeny,Allow

Denyfromall

Allowfrom192.168.0

</Proxy>

Formoreinformationonaccesscontroldirectives,seemod_access.

Strictlylimitingaccessisessentialifyouareusingaforwardproxy(usingtheProxyRequestsdirective).Otherwise,yourservercanbeusedbyanyclienttoaccessarbitraryhostswhilehidinghisorhertrueidentity.ThisisdangerousbothforyournetworkandfortheInternetatlarge.Whenusingareverseproxy(usingtheProxyPassdirectivewithProxyRequestsOff),accesscontrolislesscriticalbecauseclientscanonlycontactthehoststhatyouhavespecificallyconfigured.

FTPProxy

Whydoesn'tfiletypexxxdownloadviaFTP?Youprobablydon'thavethatparticularfiletypedefinedasapplication/octet-streaminyourproxy'smime.typesconfigurationfile.Ausefullinecanbe

application/octet-streambindmslhalzhexeclasstgztaz

HowcanIforceanFTPASCIIdownloadofFilexxx?IntheraresituationwhereyoumustdownloadaspecificfileusingtheFTPASCIItransfermethod(whilethedefaulttransferisinbinarymode),youcanoverridemod_proxy'sdefaultbysuffixingtherequestwith;type=atoforceanASCIItransfer.(FTPDirectorylistingsarealwaysexecutedinASCIImode,however.)

HowcanIaccessFTPfilesoutsideofmyhomedirectory?AnFTPURIisinterpretedrelativetothehomedirectoryoftheuserwhoisloggingin.Alas,toreachhigherdirectorylevelsyoucannotuse/../,asthedotsareinterpretedbythebrowserandnotactuallysenttotheFTPserver.Toaddressthisproblem,thesocalledSquid%2fhackwasimplementedintheApacheFTPproxy;itisasolutionwhichisalsousedbyotherpopularproxyserversliketheSquidProxyCache.Byprepending/%2ftothepathofyourrequest,youcanmakesuchaproxychangetheFTPstartingdirectoryto/(insteadofthehomedirectory).Forexample,toretrievethefile/etc/motd,youwouldusetheURL:

ftp://user@host/%2f/etc/motd

HowcanIhidetheFTPcleartextpasswordinmybrowser'sURLline?TologintoanFTPserverbyusernameandpassword,Apacheusesdifferentstrategies.InabsenseofausernameandpasswordintheURLaltogether,ApachesendsananonymouslogintotheFTPserver,i.e.,

user:anonymous

password:apache_proxy@

ThisworksforallpopularFTPserverswhichareconfiguredforanonymousaccess.

Forapersonalloginwithaspecificusername,youcanembedtheusernameintotheURL,likein:

ftp://username@host/myfile

IftheFTPserverasksforapasswordwhengiventhisusername(whichitshould),thenApachewillreplywitha401(Authorizationrequired)response,whichcausestheBrowsertopopuptheusername/passworddialog.Uponenteringthepassword,theconnectionattemptisretried,andifsuccessful,therequestedresourceispresented.Theadvantageofthisprocedureisthatyourbrowserdoesnotdisplaythepasswordincleartext(whichitwouldifyouhadused

ftp://username:password@host/myfile

inthefirstplace).

Note

Thepasswordwhichistransmittedinsuchawayisnotencryptedonitsway.Ittravelsbetweenyourbrowserandthe

Apacheproxyserverinabase64-encodedcleartextstring,andbetweentheApacheproxyandtheFTPserverasplaintext.YoushouldthereforethinktwicebeforeaccessingyourFTPserverviaHTTP(orbeforeaccessingyourpersonalfilesviaFTPatall!)Whenusingunsecurechannels,aneavesdroppermightinterceptyourpasswordonitsway.

SlowStartup

Ifyou'reusingtheProxyBlockdirective,hostnames'IPaddressesarelookedupandcachedduringstartupforlatermatchtest.Thismaytakeafewseconds(ormore)dependingonthespeedwithwhichthehostnamelookupsoccur.

IntranetProxy

AnApacheproxyserversituatedinanintranetneedstoforwardexternalrequeststhroughthecompany'sfirewall(forthis,configuretheProxyRemotedirectivetoforwardtherespectiveschemetothefirewallproxy).However,whenithastoaccessresourceswithintheintranet,itcanbypassthefirewallwhenaccessinghosts.TheNoProxydirectiveisusefulforspecifyingwhichhostsbelongtotheintranetandshouldbeaccesseddirectly.

UserswithinanintranettendtoomitthelocaldomainnamefromtheirWWWrequests,thusrequesting"http://somehost/"insteadofhttp://somehost.example.com/.Somecommercialproxyserversletthemgetawaywiththisandsimplyservetherequest,implyingaconfiguredlocaldomain.WhentheProxyDomaindirectiveisusedandtheserverisconfiguredforproxyservice,Apachecanreturnaredirectresponseandsendtheclienttothecorrect,fullyqualified,serveraddress.Thisisthepreferredmethodsincetheuser'sbookmarkfileswillthencontainfullyqualifiedhosts.

ProtocolAdjustments

Forcircumstanceswhereyouhaveaapplicationserverwhichdoesn'timplementkeepalivesorHTTP/1.1properly,thereare2environmentvariableswhichwhensetsendaHTTP/1.0withnokeepalive.ThesearesetviatheSetEnvdirective.

Thesearetheforce-proxy-request-1.0andproxy-nokeepalivenotes.

<Location/buggyappserver/>

ProxyPasshttp://buggyappserver:7001/foo/

SetEnvforce-proxy-request-1.01

SetEnvproxy-nokeepalive1

</Location>

AllowCONNECTDirective

Description: PortsthatareallowedtoCONNECTthroughtheproxy

Syntax: AllowCONNECTport[port]...

Default: AllowCONNECT443563

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

TheAllowCONNECTdirectivespecifiesalistofportnumberstowhichtheproxyCONNECTmethodmayconnect.Today'sbrowsersusethismethodwhenahttpsconnectionisrequestedandproxytunnelingoverHTTPisineffect.

Bydefault,onlythedefaulthttpsport(443)andthedefaultsnewsport(563)areenabled.UsetheAllowCONNECTdirectivetooverridethisdefaultandallowconnectionstothelistedportsonly.

Notethatyou'llneedtohavemod_proxy_connectpresentintheserverinordertogetthesupportfortheCONNECTatall.

NoProxyDirective

Description: Hosts,domains,ornetworksthatwillbeconnectedtodirectly

Syntax: NoProxyhost[host]...

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

ThisdirectiveisonlyusefulforApacheproxyserverswithinintranets.TheNoProxydirectivespecifiesalistofsubnets,IPaddresses,hostsand/ordomains,separatedbyspaces.Arequesttoahostwhichmatchesoneormoreoftheseisalwaysserveddirectly,withoutforwardingtotheconfiguredProxyRemoteproxyserver(s).

ExampleProxyRemote*http://firewall.example.com:81

NoProxy.example.com192.168.112.0/21

ThehostargumentstotheNoProxydirectiveareoneofthefollowingtypelist:

DomainADomainisapartiallyqualifiedDNSdomainname,precededbyaperiod.ItrepresentsalistofhostswhichlogicallybelongtothesameDNSdomainorzone(i.e.,thesuffixesofthehostnamesareallendinginDomain).

Examples.com.apache.org.

TodistinguishDomainsfromHostnames(bothsyntacticallyandsemantically;aDNSdomaincanhaveaDNSArecord,

too!),Domainsarealwayswrittenwithaleadingperiod.

Note

Domainnamecomparisonsaredonewithoutregardtothecase,andDomainsarealwaysassumedtobeanchoredintherootoftheDNStree,thereforetwodomains.MyDomain.comand.mydomain.com.(notethetrailingperiod)areconsideredequal.SinceadomaincomparisondoesnotinvolveaDNSlookup,itismuchmoreefficientthansubnetcomparison.

SubNetASubNetisapartiallyqualifiedinternetaddressinnumeric(dottedquad)form,optionallyfollowedbyaslashandthenetmask,specifiedasthenumberofsignificantbitsintheSubNet.Itisusedtorepresentasubnetofhostswhichcanbereachedoveracommonnetworkinterface.Intheabsenceoftheexplicitnetmaskitisassumedthatomitted(orzerovalued)trailingdigitsspecifythemask.(Inthiscase,thenetmaskcanonlybemultiplesof8bitswide.)Examples:

192.168or192.168.0.0thesubnet192.168.0.0withanimpliednetmaskof16validbits(sometimesusedinthenetmaskform255.255.0.0)

192.168.112.0/21

thesubnet192.168.112.0/21withanetmaskof21validbits(alsousedintheform255.255.248.0)

Asadegeneratecase,aSubNetwith32validbitsistheequivalenttoanIPAddr,whileaSubNetwithzerovalidbits(e.g.,0.0.0.0/0)isthesameastheconstant_Default_,matchinganyIPaddress.

IPAddrAIPAddrrepresentsafullyqualifiedinternetaddressinnumeric(dottedquad)form.Usually,thisaddressrepresentsahost,butthereneednotnecessarilybeaDNSdomainnameconnectedwiththeaddress.

Example192.168.123.7

Note

AnIPAddrdoesnotneedtoberesolvedbytheDNSsystem,soitcanresultinmoreeffectiveapacheperformance.

HostnameAHostnameisafullyqualifiedDNSdomainnamewhichcanberesolvedtooneormoreIPAddrsviatheDNSdomainnameservice.Itrepresentsalogicalhost(incontrasttoDomains,seeabove)andmustberesolvabletoatleastoneIPAddr(oroftentoalistofhostswithdifferentIPAddrs).

Examplesprep.ai.mit.edu

www.apache.org

Note

Inmanysituations,itismoreeffectivetospecifyanIPAddrinplaceofaHostnamesinceaDNSlookupcanbeavoided.NameresolutioninApachecantakearemarkabledealoftimewhentheconnectiontothenameserverusesaslowPPPlink.

Hostnamecomparisonsaredonewithoutregardtothe

case,andHostnamesarealwaysassumedtobeanchoredintherootoftheDNStree,thereforetwohostsWWW.MyDomain.comandwww.mydomain.com.(notethetrailingperiod)areconsideredequal.

SeealsoDNSIssues

<Proxy>Directive

Description: Containerfordirectivesappliedtoproxiedresources

Syntax: <Proxywildcard-url>...</Proxy>

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

Directivesplacedin<Proxy>sectionsapplyonlytomatchingproxiedcontent.Shell-stylewildcardsareallowed.

Forexample,thefollowingwillallowonlyhostsinyournetwork.example.comtoaccesscontentviayourproxyserver:

<Proxy*>

OrderDeny,Allow

Denyfromall

Allowfromyournetwork.example.com

</Proxy>

Thefollowingexamplewillprocessallfilesinthefoodirectoryofexample.comthroughtheINCLUDESfilterwhentheyaresentthroughtheproxyserver:

<Proxyhttp://example.com/foo/*>

SetOutputFilterINCLUDES

</Proxy>

ProxyBadHeaderDirective

Description: Determineshowtohandlebadheaderlinesinaresponse

Syntax: ProxyBadHeader

IsError|Ignore|StartBody

Default: ProxyBadHeaderIsError

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxyCompatibility: AvailableinApache2.0.44andlater

TheProxyBadHeaderdirectivedeterminesthebehaviourofmod_proxyifitreceivessyntacticallyinvalidheaderlines(i.e.containingnocolon).Thefollowingargumentsarepossible:

IsError

Aborttherequestandendupwitha502(BadGateway)response.Thisisthedefaultbehaviour.

Ignore

Treatbadheaderlinesasiftheyweren'tsent.

StartBody

Whenreceivingthefirstbadheaderline,finishreadingtheheadersandtreattheremainderasbody.Thishelpstoworkaroundbuggybackendserverswhichforgettoinsertanemptylinebetweentheheadersandthebody.

ProxyBlockDirective

Description: Words,hosts,ordomainsthatarebannedfrombeingproxied

Syntax: ProxyBlock*|word|host|domain

[word|host|domain]...

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

TheProxyBlockdirectivespecifiesalistofwords,hostsand/ordomains,separatedbyspaces.HTTP,HTTPS,andFTPdocumentrequeststositeswhosenamescontainmatchedwords,hostsordomainsareblockedbytheproxyserver.TheproxymodulewillalsoattempttodetermineIPaddressesoflistitemswhichmaybehostnamesduringstartup,andcachethemformatchtestaswell.Thatmayslowdownthestartuptimeoftheserver.

ExampleProxyBlockjoes-garage.comsome-host.co.uk

rocky.wotsamattau.edu

rocky.wotsamattau.eduwouldalsobematchedifreferencedbyIPaddress.

Notethatwotsamattauwouldalsobesufficienttomatchwotsamattau.edu.

Notealsothat

ProxyBlock*

blocksconnectionstoallsites.

ProxyDomainDirective

Description: DefaultdomainnameforproxiedrequestsSyntax: ProxyDomainDomain

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

ThisdirectiveisonlyusefulforApacheproxyserverswithinintranets.TheProxyDomaindirectivespecifiesthedefaultdomainwhichtheapacheproxyserverwillbelongto.Ifarequesttoahostwithoutadomainnameisencountered,aredirectionresponsetothesamehostwiththeconfiguredDomainappendedwillbegenerated.

ExampleProxyRemote*http://firewall.example.com:81

NoProxy.example.com192.168.112.0/21

ProxyDomain.example.com

ProxyErrorOverrideDirective

Description: OverrideerrorpagesforproxiedcontentSyntax: ProxyErrorOverrideOn|Off

Default: ProxyErrorOverrideOff

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxyCompatibility: Availableinversion2.0andlater

Thisdirectiveisusefulforreverse-proxysetups,whereyouwanttohaveacommonlookandfeelontheerrorpagesseenbytheenduser.Thisalsoallowsforincludedfiles(viamod_include'sSSI)togettheerrorcodeandactaccordingly(defaultbehaviorwoulddisplaytheerrorpageoftheproxiedserver,turningthisonshowstheSSIErrormessage).

ProxyFtpDirCharsetDirective

Description: DefinethecharactersetforproxiedFTPlistingsSyntax: ProxyFtpDirCharsetcharacterset

Default: ProxyFtpDirCharsetISO-8859-1

Context: serverconfig,virtualhost,directoryStatus: ExtensionModule: mod_proxyCompatibility: AvailableinApache2.0.62andlater

TheProxyFtpDirCharsetdirectivedefinesthecharactersettobesetforFTPdirectorylistingsinHTMLgeneratedbymod_proxy_ftp.

ProxyIOBufferSizeDirective

Description: DeterminesizeofinternaldatathroughputbufferSyntax: ProxyIOBufferSizebytes

Default: ProxyIOBufferSize8192

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

TheProxyIOBufferSizedirectiveadjuststhesizeoftheinternalbuffer,whichisusedasascratchpadforthedatabetweeninputandoutput.Thesizemustbelessorequal8192.

Inalmosteverycasethere'snoreasontochangethatvalue.

<ProxyMatch>Directive

Description: Containerfordirectivesappliedtoregular-expression-matchedproxiedresources

Syntax: <ProxyMatchregex>...</ProxyMatch>

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

The<ProxyMatch>directiveisidenticaltothe<Proxy>directive,exceptitmatchesURLsusingregularexpressions.

ProxyMaxForwardsDirective

Description: Maximiumnumberofproxiesthatarequestcanbeforwardedthrough

Syntax: ProxyMaxForwardsnumber

Default: ProxyMaxForwards10

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxyCompatibility: AvailableinApache2.0andlater

TheProxyMaxForwardsdirectivespecifiesthemaximumnumberofproxiesthroughwhicharequestmaypass,ifthere'snoMax-Forwardsheadersuppliedwiththerequest.Thisissettopreventinfiniteproxyloops,oraDoSattack.

ExampleProxyMaxForwards15

ProxyPassDirective

Description: MapsremoteserversintothelocalserverURL-space

Syntax: ProxyPass[path]!|url

Context: serverconfig,virtualhost,directoryStatus: ExtensionModule: mod_proxy

Thisdirectiveallowsremoteserverstobemappedintothespaceofthelocalserver;thelocalserverdoesnotactasaproxyintheconventionalsense,butappearstobeamirroroftheremoteserver.pathisthenameofalocalvirtualpath;urlisapartialURLfortheremoteserverandcannotincludeaquerystring.

Supposethelocalserverhasaddresshttp://example.com/;then

ProxyPass/mirror/foo/http://backend.example.com/

willcausealocalrequestforhttp://example.com/mirror/foo/bartobeinternallyconvertedintoaproxyrequesttohttp://backend.example.com/bar.

The!directiveisusefulinsituationswhereyoudon'twanttoreverse-proxyasubdirectory,e.g.

ProxyPass/mirror/foo/i!

ProxyPass/mirror/foohttp://backend.example.com

willproxyallrequeststo/mirror/footobackend.example.comexceptrequestsmadeto/mirror/foo/i.

Note

Orderisimportant.youneedtoputtheexclusionsbeforethegeneralproxypassdirective.

Whenusedinsidea<Location>section,thefirstargumentisomittedandthelocaldirectoryisobtainedfromthe<Location>.

TheProxyRequestsdirectiveshouldusuallybesetoffwhenusingProxyPass.

Ifyourequireamoreflexiblereverse-proxyconfiguration,seetheRewriteRuledirectivewiththe[P]flag.

ProxyPassReverseDirective

Description: AdjuststheURLinHTTPresponseheaderssentfromareverseproxiedserver

Syntax: ProxyPassReverse[path]url

Context: serverconfig,virtualhost,directoryStatus: ExtensionModule: mod_proxy

ThisdirectiveletsApacheadjusttheURLintheLocation,Content-LocationandURIheadersonHTTPredirectresponses.ThisisessentialwhenApacheisusedasareverseproxytoavoidby-passingthereverseproxybecauseofHTTPredirectsonthebackendserverswhichstaybehindthereverseproxy.

OnlytheHTTPresponseheadersspecificallymentionedabovewillberewritten.Apachewillnotrewriteotherresponseheaders,norwillitrewriteURLreferencesinsideHTMLpages.ThismeansthatiftheproxiedcontentcontainsabsoluteURLreferences,theywillby-passtheproxy.Athird-partymodulethatwilllookinsidetheHTMLandrewriteURLreferencesisNickKew'smod_proxy_html.

pathisthenameofalocalvirtualpath.urlisapartialURLfortheremoteserver-thesamewaytheyareusedfortheProxyPassdirective.

Forexample,supposethelocalserverhasaddresshttp://example.com/;then

ProxyPass/mirror/foo/http://backend.example.com/

ProxyPassReverse/mirror/foo/http://backend.example.com/

willnotonlycausealocalrequestforthehttp://example.com/mirror/foo/bartobeinternally

convertedintoaproxyrequesttohttp://backend.example.com/bar(thefunctionalityProxyPassprovideshere).Italsotakescareofredirectstheserverbackend.example.comsends:whenhttp://backend.example.com/barisredirectedbyhimtohttp://backend.example.com/quuxApacheadjuststhistohttp://example.com/mirror/foo/quuxbeforeforwardingtheHTTPredirectresponsetotheclient.NotethatthehostnameusedforconstructingtheURLischoseninrespecttothesettingoftheUseCanonicalNamedirective.

NotethatthisProxyPassReversedirectivecanalsobeusedinconjunctionwiththeproxypass-throughfeature(RewriteRule...[P])frommod_rewritebecauseitsdoesn'tdependonacorrespondingProxyPassdirective.

Whenusedinsidea<Location>section,thefirstargumentisomittedandthelocaldirectoryisobtainedfromthe<Location>.

ProxyPreserveHostDirective

Description: UseincomingHostHTTPrequestheaderforproxyrequest

Syntax: ProxyPreserveHostOn|Off

Default: ProxyPreserveHostOff

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxyCompatibility: AvailableinApache2.0.31andlater.

Whenenabled,thisoptionwillpasstheHost:linefromtheincomingrequesttotheproxiedhost,insteadofthehostnamespecifiedintheproxypassline.

ThisoptionshouldnormallybeturnedOff.Itismostlyusefulinspecialconfigurationslikeproxiedmassname-basedvirtualhosting,wheretheoriginalHostheaderneedstobeevaluatedbythebackendserver.

ProxyReceiveBufferSizeDirective

Description: NetworkbuffersizeforproxiedHTTPandFTPconnections

Syntax: ProxyReceiveBufferSizebytes

Default: ProxyReceiveBufferSize0

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

TheProxyReceiveBufferSizedirectivespecifiesanexplicit(TCP/IP)networkbuffersizeforproxiedHTTPandFTPconnections,forincreasedthroughput.Ithastobegreaterthan512orsetto0toindicatethatthesystem'sdefaultbuffersizeshouldbeused.

ExampleProxyReceiveBufferSize2048

ProxyRemoteDirective

Description: RemoteproxyusedtohandlecertainrequestsSyntax: ProxyRemotematchremote-server

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

Thisdefinesremoteproxiestothisproxy.matchiseitherthenameofaURL-schemethattheremoteserversupports,orapartialURLforwhichtheremoteservershouldbeused,or*toindicatetheservershouldbecontactedforallrequests.remote-serverisapartialURLfortheremoteserver.Syntax:

remote-server=scheme://hostname[:port]

schemeiseffectivelytheprotocolthatshouldbeusedtocommunicatewiththeremoteserver;onlyhttpissupportedbythismodule.

ExampleProxyRemotehttp://goodguys.com/http://mirrorguys.com:8000

ProxyRemote*http://cleversite.com

ProxyRemoteftphttp://ftpproxy.mydomain.com:8080

Inthelastexample,theproxywillforwardFTPrequests,encapsulatedasyetanotherHTTPproxyrequest,toanotherproxywhichcanhandlethem.

Thisoptionalsosupportsreverseproxyconfiguration-abackendwebservercanbeembeddedwithinavirtualhostURLspaceevenifthatserverishiddenbyanotherforwardproxy.

ProxyRemoteMatchDirective

Description: Remoteproxyusedtohandlerequestsmatchedbyregularexpressions

Syntax: ProxyRemoteMatchregexremote-server

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

TheProxyRemoteMatchisidenticaltotheProxyRemotedirective,exceptthefirstargumentisaregularexpressionmatchagainsttherequestedURL.

ProxyRequestsDirective

Description: Enablesforward(standard)proxyrequestsSyntax: ProxyRequestsOn|Off

Default: ProxyRequestsOff

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

ThisallowsorpreventsApachefromfunctioningasaforwardproxyserver.(SettingProxyRequeststoOffdoesnotdisableuseoftheProxyPassdirective.)

Inatypicalreverseproxyconfiguration,thisoptionshouldbesettoOff.

InordertogetthefunctionalityofproxyingHTTPorFTPsites,youneedalsomod_proxy_httpormod_proxy_ftp(orboth)presentintheserver.

Warning

DonotenableproxyingwithProxyRequestsuntilyouhavesecuredyourserver.OpenproxyserversaredangerousbothtoyournetworkandtotheInternetatlarge.

ProxyTimeoutDirective

Description: NetworktimeoutforproxiedrequestsSyntax: ProxyTimeoutseconds

Default: ProxyTimeout300

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxyCompatibility: AvailableinApache2.0.31andlater

Thisdirectiveallowsausertospecifiyatimeoutonproxyrequests.Thisisusefulwhenyouhaveaslow/buggyappserverwhichhangs,andyouwouldratherjustreturnatimeoutandfailgracefullyinsteadofwaitinghoweverlongittakestheservertoreturn.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ProxyViaDirective

Description: InformationprovidedintheViaHTTPresponseheaderforproxiedrequests

Syntax: ProxyViaOn|Off|Full|Block

Default: ProxyViaOff

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_proxy

ThisdirectivecontrolstheuseoftheVia:HTTPheaderbytheproxy.Itsintendeduseistocontroltheflowofofproxyrequestsalongachainofproxyservers.SeeRFC2616(HTTP/1.1),section14.45foranexplanationofVia:headerlines.

IfsettoOff,whichisthedefault,nospecialprocessingisperformed.IfarequestorreplycontainsaVia:header,itispassedthroughunchanged.IfsettoOn,eachrequestandreplywillgetaVia:headerlineaddedforthecurrenthost.IfsettoFull,eachgeneratedVia:headerlinewilladditionallyhavetheApacheserverversionshownasaVia:commentfield.IfsettoBlock,everyproxyrequestwillhaveallitsVia:headerlinesremoved.NonewVia:headerwillbegenerated.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheModulemod_proxy_connect

Description: mod_proxyextensionforCONNECTrequesthandling

Status: ExtensionModuleIdentifier: proxy_connect_moduleSourceFile: proxy_connect.c

SummaryThismodulerequirestheserviceofmod_proxy.ItprovidessupportfortheCONNECTHTTPmethod.ThismethodismainlyusedtotunnelSSLrequeststhroughproxyservers.

Thus,inordertogettheabilityofhandlingCONNECTrequests,mod_proxyandmod_proxy_connecthavetobepresentintheserver.

Warning

Donotenableproxyinguntilyouhavesecuredyourserver.OpenproxyserversaredangerousbothtoyournetworkandtotheInternetatlarge.

SeealsoAllowCONNECT

mod_proxy

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheModulemod_proxy_ftp

Description: FTPsupportmoduleformod_proxyStatus: ExtensionModuleIdentifier: proxy_ftp_moduleSourceFile: proxy_ftp.c

SummaryThismodulerequirestheserviceofmod_proxy.ItprovidessupportfortheproxyingFTPsites.

Thus,inordertogettheabilityofhandlingFTPproxyrequests,mod_proxyandmod_proxy_ftphavetobepresentintheserver.

Warning

Donotenableproxyinguntilyouhavesecuredyourserver.OpenproxyserversaredangerousbothtoyournetworkandtotheInternetatlarge.

Seealsomod_proxy

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheModulemod_proxy_http

Description: HTTPsupportmoduleformod_proxyStatus: ExtensionModuleIdentifier: proxy_http_moduleSourceFile: proxy_http.c

SummaryThismodulerequirestheserviceofmod_proxy.ItprovidesthefeaturesusedforproxyingHTTPrequests.mod_proxy_httpsupportsHTTP/0.9,HTTP/1.0andHTTP/1.1.Itdoesnotprovideanycachingabilities.Ifyouwanttosetupacachingproxy,youmightwanttousetheadditionalserviceofthemod_cachemodule.

Thus,inordertogettheabilityofhandlingHTTPproxyrequests,mod_proxyandmod_proxy_httphavetobepresentintheserver.

Warning

Donotenableproxyinguntilyouhavesecuredyourserver.OpenproxyserversaredangerousbothtoyournetworkandtotheInternetatlarge.

Seealsomod_proxy

mod_proxy_connect

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_rewrite

Description: Providesarule-basedrewritingenginetorewriterequestedURLsonthefly

Status: ExtensionModuleIdentifier: rewrite_moduleSourceFile: mod_rewrite.cCompatibility: AvailableinApache1.3andlater

SummaryThismoduleusesarule-basedrewritingengine(basedonaregular-expressionparser)torewriterequestedURLsonthefly.Itsupportsanunlimitednumberofrulesandanunlimitednumberofattachedruleconditionsforeachrule,toprovideareallyflexibleandpowerfulURLmanipulationmechanism.TheURLmanipulationscandependonvarioustests,ofservervariables,environmentvariables,HTTPheaders,ortimestamps.EvenexternaldatabaselookupsinvariousformatscanbeusedtoachievehighlygranularURLmatching.

ThismoduleoperatesonthefullURLs(includingthepath-infopart)bothinper-servercontext(httpd.conf)andper-directorycontext(.htaccess)andcangeneratequery-stringpartsonresult.Therewrittenresultcanleadtointernalsub-processing,externalrequestredirectionoreventoaninternalproxythroughput.

Furtherdetails,discussion,andexamples,areprovidedinthedetailedmod_rewritedocumentation.

SeealsoRewriteFlags

APIPhases

ApacheprocessesaHTTPrequestinseveralphases.AhookforeachofthesephasesisprovidedbytheApacheAPI.mod_rewriteusestwoofthesehooks:theURL-to-filenametranslationhook(usedaftertheHTTPrequesthasbeenread,butbeforeanyauthorizationstarts)andtheFixuphook(triggeredaftertheauthorizationphases,andaftertheper-directoryconfigfiles(.htaccess)havebeenread,butbeforethecontenthandlerisactivated).

Oncearequestcomesin,andApachehasdeterminedtheappropriateserver(orvirtualserver),therewriteenginestartstheURL-to-filenametranslation,processingthemod_rewritedirectivesfromtheper-serverconfiguration.Afewstepslater,whenthefinaldatadirectoriesarefound,theper-directoryconfigurationdirectivesofmod_rewritearetriggeredintheFixupphase.

RulesetProcessing

Whenmod_rewriteistriggeredduringthesetwoAPIphases,itreadstherelevantrulesetsfromitsconfigurationstructure(whichwaseithercreatedonstartup,forper-servercontext,orduringthedirectorytraversalforper-directorycontext).TheURLrewritingengineisstartedwiththeappropriateruleset(oneormorerulestogetherwiththeirconditions),anditsoperationisexactlythesameforbothconfigurationcontexts.Onlythefinalresultprocessingisdifferent.

Theorderofrulesintherulesetisimportantbecausetherewriteengineprocessestheminaparticular(notalwaysobvious)order,asfollows:Therewriteengineloopsthroughtherulesets(eachrulesetbeingmadeupofRewriteRuledirectives,withorwithoutRewriteConds),rulebyrule.Whenaparticularruleismatched,mod_rewritealsochecksthecorrespondingconditions(RewriteConddirectives).Forhistoricalreasonstheconditionsaregivenfirst,makingthecontrolflowalittlebitlong-winded.SeeFigure1formoredetails.

Figure1:Thecontrolflowoftherewriteenginethrougharewriteruleset

Asabove,firsttheURLismatchedagainstthePatternofarule.Ifitdoesnotmatch,mod_rewriteimmediatelystopsprocessingthatrule,andgoesontothenextrule.IfthePatternmatches,mod_rewritechecksforruleconditions.Ifnonearepresent,theURLwillbereplacedwithanewstring,constructedfromtheSubstitutionstring,andmod_rewritegoesontothenextrule.

IfRewriteCondsexist,aninnerloopisstarted,processingthemintheorderthattheyarelisted.ConditionsarenotmatchedagainstthecurrentURLdirectly.ATestStringisconstructedbyexpandingvariables,back-references,maplookups,etc.,againstwhichtheCondPatternismatched.Ifthepatternfailstomatchoneoftheconditions,thecompletesetofruleandassociatedconditionsfails.Ifthepatternmatchesagivencondition,thenmatchingcontinuestothenextcondition,untilnomoreconditionsareavailable.Ifallconditionsmatch,processingiscontinuedwith

thesubstitutionoftheSubstitutionstringfortheURL.

RegexBack-ReferenceAvailability

UsingparenthesesinPatternorinoneoftheCondPatternscausesback-referencestobeinternallycreated.Thesecanlaterbereferencedusingthestrings$Nand%N(seebelow),forcreatingtheSubstitutionandTestStringstrings.Figure2attemptstoshowhowtheback-referencesaretransferredthroughtheprocessforlaterexpansion.

Figure2:Theback-referenceflowthrougharule.

QuotingSpecialCharacters

AsofApache1.3.20,specialcharactersinTestStringandSubstitutionstringscanbeescaped(thatis,treatedasnormalcharacterswithouttheirusualspecialmeaning)byprefixingthemwithabackslash('\')character.Inotherwords,youcanincludeanactualdollar-signcharacterinaSubstitutionstringbyusing'\$';thiskeepsmod_rewritefromtryingtotreatitasabackreference.

EnvironmentVariables

Thismodulekeepstrackoftwoadditional(non-standard)CGI/SSIenvironmentvariablesnamedSCRIPT_URLandSCRIPT_URI.ThesecontainthelogicalWeb-viewtothecurrentresource,whilethestandardCGI/SSIvariablesSCRIPT_NAMEandSCRIPT_FILENAMEcontainthephysicalSystem-view.

Notice:ThesevariablesholdtheURI/URLastheywereinitiallyrequested,thatis,beforeanyrewriting.ThisisimportanttonotebecausetherewritingprocessisprimarilyusedtorewritelogicalURLstophysicalpathnames.

ExampleSCRIPT_NAME=/sw/lib/w3s/tree/global/u/rse/.www/index.html

SCRIPT_FILENAME=/u/rse/.www/index.html

SCRIPT_URL=/u/rse/

SCRIPT_URI=http://en1.engelschall.com/u/rse/

PracticalSolutions

Fornumerousexamplesofcommon,andnot-so-common,usesformod_rewrite,seetheRewriteGuide,andtheAdvancedRewriteGuidedocuments.

RewriteBaseDirective

Description: SetsthebaseURLforper-directoryrewritesSyntax: RewriteBaseURL-path

Default: Seeusageforinformation.

Context: directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_rewrite

TheRewriteBasedirectiveexplicitlysetsthebaseURLforper-directoryrewrites.Asyouwillseebelow,RewriteRulecanbeusedinper-directoryconfigfiles(.htaccess).Insuchacase,itwillactlocally,strippingthelocaldirectoryprefixbeforeprocessing,andapplyingrewriterulesonlytotheremainder.Whenprocessingiscomplete,theprefixisautomaticallyaddedbacktothepath.Thedefaultsettingis;RewriteBasephysical-directory-path

WhenasubstitutionoccursforanewURL,thismodulehastore-injecttheURLintotheserverprocessing.TobeabletodothisitneedstoknowwhatthecorrespondingURL-prefixorURL-baseis.Bydefaultthisprefixisthecorrespondingfilepathitself.However,formostwebsites,URLsareNOTdirectlyrelatedtophysicalfilenamepaths,sothisassumptionwilloftenbewrong!Therefore,youcanusetheRewriteBasedirectivetospecifythecorrectURL-prefix.

Ifyourwebserver'sURLsarenotdirectlyrelatedtophysicalfilepaths,youwillneedtouseRewriteBaseinevery.htaccessfilewhereyouwanttouseRewriteRuledirectives.

Forexample,assumethefollowingper-directoryconfigfile:

#

#/abc/def/.htaccess--per-dirconfigfilefordirectory/abc/def

#Remember:/abc/defisthephysicalpathof/xyz,i.e.,theserver

#hasa'Alias/xyz/abc/def'directivee.g.

#

RewriteEngineOn

#lettheserverknowthatwewerereachedvia/xyzandnot

#viathephysicalpathprefix/abc/def

RewriteBase/xyz

#nowtherewritingrules

RewriteRule^oldstuff\.html$newstuff.html

Intheaboveexample,arequestto/xyz/oldstuff.htmlgetscorrectlyrewrittentothephysicalfile/abc/def/newstuff.html.

ForApacheHackers

Thefollowinglistgivesdetailedinformationabouttheinternalprocessingsteps:

Request:

/xyz/oldstuff.html

InternalProcessing:

/xyz/oldstuff.html->/abc/def/oldstuff.html(per-serverAlias)

/abc/def/oldstuff.html->/abc/def/newstuff.html(per-dirRewriteRule)

/abc/def/newstuff.html->/xyz/newstuff.html(per-dirRewriteBase)

/xyz/newstuff.html->/abc/def/newstuff.html(per-serverAlias)

Result:

/abc/def/newstuff.html

Thisseemsverycomplicated,butisinfactcorrectApacheinternalprocessing.Becausetheper-directoryrewritingcomeslateintheprocess,therewrittenrequesthastobere-injectedintotheApachekernel,asifitwereanewrequest.(Seemod_rewritetechnicaldetails.)Thisisnottheseriousoverheaditmayseemtobe-thisre-injectioniscompletelyinternaltotheApacheserver(andthesameprocedureisusedbymanyother

operationswithinApache).

RewriteCondDirective

Description: Definesaconditionunderwhichrewritingwilltakeplace

Syntax: RewriteCondTestStringCondPattern

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_rewrite

TheRewriteConddirectivedefinesarulecondition.OneormoreRewriteCondcanprecedeaRewriteRuledirective.ThefollowingruleisthenonlyusedifboththecurrentstateoftheURImatchesitspattern,andiftheseconditionsaremet.

TestStringisastringwhichcancontainthefollowingexpandedconstructsinadditiontoplaintext:

RewriteRulebackreferences:Thesearebackreferencesoftheform$N(0<=N<=9),whichprovideaccesstothegroupedparts(inparentheses)ofthepattern,fromtheRewriteRulewhichissubjecttothecurrentsetofRewriteCondconditions..RewriteCondbackreferences:Thesearebackreferencesoftheform%N(1<=N<=9),whichprovideaccesstothegroupedparts(again,inparentheses)ofthepattern,fromthelastmatchedRewriteCondinthecurrentsetofconditions.RewriteMapexpansions:Theseareexpansionsoftheform${mapname:key|default}.SeethedocumentationforRewriteMapformoredetails.Server-Variables:Thesearevariablesoftheform%{NAME_OF_VARIABLE}whereNAME_OF_VARIABLEcanbeastringtakenfromthefollowinglist:

HTTPheaders: connection&

request:HTTP_USER_AGENTHTTP_REFERERHTTP_COOKIEHTTP_FORWARDEDHTTP_HOSTHTTP_PROXY_CONNECTIONHTTP_ACCEPT

REMOTE_ADDRREMOTE_HOSTREMOTE_PORTREMOTE_USERREMOTE_IDENTREQUEST_METHODSCRIPT_FILENAMEPATH_INFOQUERY_STRINGAUTH_TYPE

serverinternals: systemstuff: specials:DOCUMENT_ROOTSERVER_ADMINSERVER_NAMESERVER_ADDRSERVER_PORTSERVER_PROTOCOLSERVER_SOFTWARE

TIME_YEARTIME_MONTIME_DAYTIME_HOURTIME_MINTIME_SECTIME_WDAYTIME

API_VERSIONTHE_REQUESTREQUEST_URIREQUEST_FILENAMEIS_SUBREQHTTPS

ThesevariablesallcorrespondtothesimilarlynamedHTTPMIME-headers,CvariablesoftheApacheserverorstructtmfieldsoftheUnixsystem.MostaredocumentedelsewhereintheManualorintheCGIspecification.Thosethatarespecialtomod_rewriteincludethosebelow.

IS_SUBREQ

Willcontainthetext"true"iftherequestcurrentlybeingprocessedisasub-request,"false"otherwise.Sub-requestsmaybegeneratedbymodulesthatneedtoresolveadditionalfilesorURIsinordertocompletetheirtasks.

API_VERSION

ThisistheversionoftheApachemoduleAPI(theinternalinterfacebetweenserverandmodule)inthecurrenthttpdbuild,asdefinedininclude/ap_mmn.h.ThemoduleAPIversioncorrespondstotheversionofApacheinuse(inthereleaseversionofApache1.3.14,forinstance,itis19990320:10),butismainlyofinteresttomoduleauthors.

THE_REQUEST

ThefullHTTPrequestlinesentbythebrowsertotheserver(e.g.,"GET/index.htmlHTTP/1.1").Thisdoesnotincludeanyadditionalheaderssentbythebrowser.

REQUEST_URI

TheresourcerequestedintheHTTPrequestline.(Intheexampleabove,thiswouldbe"/index.html".)

REQUEST_FILENAME

Thefulllocalfilesystempathtothefileorscriptmatchingtherequest.

HTTPS

Willcontainthetext"on"iftheconnectionisusingSSL/TLS,or"off"otherwise.(Thisvariablecanbesafelyusedregardlessofwhetherornotmod_sslisloaded).

Otherthingsyoushouldbeawareof:

1. ThevariablesSCRIPT_FILENAMEandREQUEST_FILENAMEcontainthesamevalue-thevalueofthefilenamefieldoftheinternalrequest_recstructureoftheApacheserver.ThefirstnameisthecommonlyknownCGIvariablenamewhilethesecondistheappropriate

counterpartofREQUEST_URI(whichcontainsthevalueoftheurifieldofrequest_rec).

2. %{ENV:variable},wherevariablecanbeanyenvironmentvariable,isalsoavailable.Thisislooked-upviainternalApachestructuresand(ifnotfoundthere)viagetenv()fromtheApacheserverprocess.

3. %{SSL:variable},wherevariableisthenameofanSSLenvironmentvariable,canbeusedwhetherornotmod_sslisloaded,butwillalwaysexpandtotheemptystringifitisnot.Example:%{SSL:SSL_CIPHER_USEKEYSIZE}mayexpandto128.

4. %{HTTP:header},whereheadercanbeanyHTTPMIME-headername,canalwaysbeusedtoobtainthevalueofaheadersentintheHTTPrequest.Example:%{HTTP:Proxy-Connection}isthevalueoftheHTTPheader``Proxy-Connection:''.

5. %{LA-U:variable}canbeusedforlook-aheadswhichperformaninternal(URL-based)sub-requesttodeterminethefinalvalueofvariable.Thiscanbeusedtoaccessvariableforrewritingwhichisnotavailableatthecurrentstage,butwillbesetinalaterphase.Forinstance,torewriteaccordingtotheREMOTE_USERvariablefromwithintheper-servercontext(httpd.conffile)youmustuse%{LA-U:REMOTE_USER}-thisvariableissetbytheauthorizationphases,whichcomeaftertheURLtranslationphase(duringwhichmod_rewriteoperates).

Ontheotherhand,becausemod_rewriteimplementsitsper-directorycontext(.htaccessfile)viatheFixupphaseoftheAPIandbecausetheauthorizationphasescomebeforethisphase,youjustcanuse%{REMOTE_USER}inthatcontext.

6. %{LA-F:variable}canbeusedtoperformaninternal(filename-based)sub-request,todeterminethefinalvalueofvariable.Mostofthetime,thisisthesameasLA-Uabove.

CondPatternistheconditionpattern,aregularexpressionwhichisappliedtothecurrentinstanceoftheTestString.TestStringisfirstevaluated,beforebeingmatchedagainstCondPattern.

Remember:CondPatternisaperlcompatibleregularexpressionwithsomeadditions:

1. Youcanprefixthepatternstringwitha'!'character(exclamationmark)tospecifyanon-matchingpattern.

2. TherearesomespecialvariantsofCondPatterns.Insteadofrealregularexpressionstringsyoucanalsouseoneofthefollowing:

'<CondPattern'(lexicographicallyprecedes)TreatstheCondPatternasaplainstringandcomparesitlexicographicallytoTestString.TrueifTestStringlexicographicallyprecedesCondPattern.

'>CondPattern'(lexicographicallyfollows)TreatstheCondPatternasaplainstringandcomparesitlexicographicallytoTestString.TrueifTestStringlexicographicallyfollowsCondPattern.

'=CondPattern'(lexicographicallyequal)TreatstheCondPatternasaplainstringandcomparesitlexicographicallytoTestString.TrueifTestStringislexicographicallyequaltoCondPattern(thetwostringsareexactlyequal,characterforcharacter).IfCondPatternis""(twoquotationmarks)thiscomparesTestStringtotheemptystring.

'-d'(isdirectory)TreatstheTestStringasapathnameandtestswhetheror

notitexists,andisadirectory.

'-f'(isregularfile)TreatstheTestStringasapathnameandtestswhetherornotitexists,andisaregularfile.

'-s'(isregularfile,withsize)TreatstheTestStringasapathnameandtestswhetherornotitexists,andisaregularfilewithsizegreaterthanzero.

'-l'(issymboliclink)TreatstheTestStringasapathnameandtestswhetherornotitexists,andisasymboliclink.

'-F'(isexistingfile,viasubrequest)CheckswhetherornotTestStringisavalidfile,accessibleviaalltheserver'scurrently-configuredaccesscontrolsforthatpath.Thisusesaninternalsubrequesttodothecheck,souseitwithcare-itcanimpactyourserver'sperformance!

'-U'(isexistingURL,viasubrequest)CheckswhetherornotTestStringisavalidURL,accessibleviaalltheserver'scurrently-configuredaccesscontrolsforthatpath.Thisusesaninternalsubrequesttodothecheck,souseitwithcare-itcanimpactyourserver'sperformance!

Note

Allofthesetestscanalsobeprefixedbyanexclamationmark('!')tonegatetheirmeaning.

3. YoucanalsosetspecialflagsforCondPatternbyappending[flags]asthethirdargumenttotheRewriteConddirective,whereflagsisacomma-separatedlistofanyofthefollowing

flags:

'nocase|NC'(nocase)Thismakesthetestcase-insensitive-differencesbetween'A-Z'and'a-z'areignored,bothintheexpandedTestStringandtheCondPattern.ThisflagiseffectiveonlyforcomparisonsbetweenTestStringandCondPattern.Ithasnoeffectonfilesystemandsubrequestchecks.

'ornext|OR'(ornextcondition)UsethistocombineruleconditionswithalocalORinsteadoftheimplicitAND.Typicalexample:

RewriteCond%{REMOTE_HOST}=host1[OR]

RewriteCond%{REMOTE_HOST}=host2[OR]

RewriteCond%{REMOTE_HOST}=host3

RewriteRule...somespecialstuffforanyofthesehosts...

Withoutthisflagyouwouldhavetowritethecondition/rulepairthreetimes.

Example:

TorewritetheHomepageofasiteaccordingtothe``User-Agent:''headeroftherequest,youcanusethefollowing:

RewriteCond%{HTTP_USER_AGENT}^Mozilla

RewriteRule^/$/homepage.max.html[L]

RewriteCond%{HTTP_USER_AGENT}^Lynx

RewriteRule^/$/homepage.min.html[L]

RewriteRule^/$/homepage.std.html[L]

Explanation:Ifyouuseabrowserwhichidentifiesitselfas'Mozilla'(includingNetscapeNavigator,Mozillaetc),thenyougetthemaxhomepage(whichcouldincludeframes,orotherspecialfeatures).

IfyouusetheLynxbrowser(whichisterminal-based),thenyougettheminhomepage(whichcouldbeaversiondesignedforeasy,text-onlybrowsing).Ifneitheroftheseconditionsapply(youuseanyotherbrowser,oryourbrowseridentifiesitselfassomethingnon-standard),yougetthestd(standard)homepage.

RewriteEngineDirective

Description: EnablesordisablesruntimerewritingengineSyntax: RewriteEngineon|off

Default: RewriteEngineoff

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_rewrite

TheRewriteEnginedirectiveenablesordisablestheruntimerewritingengine.Ifitissettooffthismoduledoesnoruntimeprocessingatall.ItdoesnotevenupdatetheSCRIPT_URxenvironmentvariables.

UsethisdirectivetodisablethemoduleinsteadofcommentingoutalltheRewriteRuledirectives!

Notethat,bydefault,rewriteconfigurationsarenotinherited.ThismeansthatyouneedtohaveaRewriteEngineondirectiveforeachvirtualhostinwhichyouwishtouseit.

RewriteMapdirectivesofthetypeprgarenotstartedduringserverinitializationifthey'redefinedinacontextthatdoesnothaveRewriteEnginesettoon

RewriteLockDirective

Description: SetsthenameofthelockfileusedforRewriteMapsynchronization

Syntax: RewriteLockfile-path

Context: serverconfigStatus: ExtensionModule: mod_rewrite

Thisdirectivesetsthefilenameforasynchronizationlockfilewhichmod_rewriteneedstocommunicatewithRewriteMapprograms.Setthislockfiletoalocalpath(notonaNFS-mounteddevice)whenyouwanttousearewritingmap-program.Itisnotrequiredforothertypesofrewritingmaps.

RewriteLogDirective

Description: Setsthenameofthefileusedforloggingrewriteengineprocessing

Syntax: RewriteLogfile-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_rewrite

TheRewriteLogdirectivesetsthenameofthefiletowhichtheserverlogsanyrewritingactionsitperforms.Ifthenamedoesnotbeginwithaslash('/')thenitisassumedtoberelativetotheServerRoot.Thedirectiveshouldoccuronlyonceperserverconfig.

TodisabletheloggingofrewritingactionsitisnotrecommendedtosetFilenameto/dev/null,becausealthoughtherewritingenginedoesnotthenoutputtoalogfileitstillcreatesthelogfileoutputinternally.Thiswillslowdowntheserverwithnoadvantagetotheadministrator!TodisableloggingeitherremoveorcommentouttheRewriteLogdirectiveoruseRewriteLogLevel0!

SecuritySeetheApacheSecurityTipsdocumentfordetailsonhowyoursecuritycouldbecompromisedifthedirectorywherelogfilesarestorediswritablebyanyoneotherthantheuserthatstartstheserver.

ExampleRewriteLog"/usr/local/var/apache/logs/rewrite.log"

RewriteLogLevelDirective

Description: Setstheverbosityofthelogfileusedbytherewriteengine

Syntax: RewriteLogLevelLevel

Default: RewriteLogLevel0

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_rewrite

TheRewriteLogLeveldirectivesetstheverbosityleveloftherewritinglogfile.Thedefaultlevel0meansnologging,while9ormoremeansthatpracticallyallactionsarelogged.

TodisabletheloggingofrewritingactionssimplysetLevelto0.Thisdisablesallrewriteactionlogs.

UsingahighvalueforLevelwillslowdownyourApacheserverdramatically!UsetherewritinglogfileataLevelgreaterthan2onlyfordebugging!

ExampleRewriteLogLevel3

RewriteMapDirective

Description: Definesamappingfunctionforkey-lookupSyntax: RewriteMapMapNameMapType:MapSource

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_rewriteCompatibility: Thechoiceofdifferentdbmtypesisavailablein

Apache2.0.41andlater

TheRewriteMapdirectivedefinesaRewritingMapwhichcanbeusedinsiderulesubstitutionstringsbythemapping-functionstoinsert/substitutefieldsthroughakeylookup.Thesourceofthislookupcanbeofvarioustypes.

TheMapNameisthenameofthemapandwillbeusedtospecifyamapping-functionforthesubstitutionstringsofarewritingruleviaoneofthefollowingconstructs:

${MapName:LookupKey}${MapName:LookupKey|DefaultValue}

Whensuchaconstructoccurs,themapMapNameisconsultedandthekeyLookupKeyislooked-up.Ifthekeyisfound,themap-functionconstructissubstitutedbySubstValue.IfthekeyisnotfoundthenitissubstitutedbyDefaultValueorbytheemptystringifnoDefaultValuewasspecified.

Forexample,youmightdefineaRewriteMapas:

RewriteMapexamplemaptxt:/path/to/file/map.txt

YouwouldthenbeabletousethismapinaRewriteRuleasfollows:

RewriteRule^/ex/(.*)${examplemap:$1}

ThefollowingcombinationsforMapTypeandMapSourcecanbeused:

StandardPlainTextMapType:txt,MapSource:UnixfilesystempathtovalidregularfileThisisthestandardrewritingmapfeaturewheretheMapSourceisaplainASCIIfilecontainingeitherblanklines,commentlines(startingwitha'#'character)orpairslikethefollowing-oneperline.

MatchingKeySubstValue

Example##

##map.txt--rewritingmap

##

Ralf.S.Engelschallrse#BastardOperatorFromHell

Mr.Joe.Averagejoe#Mr.Average

RewriteMapreal-to-usertxt:/path/to/file/map.txt

RandomizedPlainTextMapType:rnd,MapSource:UnixfilesystempathtovalidregularfileThisisidenticaltotheStandardPlainTextvariantabovebutwithaspecialpost-processingfeature:Afterlookingupavalueitisparsedaccordingtocontained``|''characterswhichhavethemeaningof``or''.Inotherwordstheyindicateasetofalternativesfromwhichtheactualreturnedvalueis

chosenrandomly.Forexample,youmightusethefollowingmapfileanddirectivestoprovidearandomloadbalancingbetweenseveralback-endserver,viaareverse-proxy.Imagesaresenttooneoftheserversinthe'static'pool,whileeverythingelseissenttooneofthe'dynamic'pool.

Example:

Rewritemapfile##

##map.txt--rewritingmap

##

staticwww1|www2|www3|www4

dynamicwww5|www6

ConfigurationdirectivesRewriteMapserversrnd:/path/to/file/map.txt

RewriteRule^/(.*\.(png|gif|jpg))

http://${servers:static}/$1[NC,P,L]

RewriteRule^/(.*)http://${servers:dynamic}/$1[P,L]

HashFileMapType:dbm[=type],MapSource:UnixfilesystempathtovalidregularfileHerethesourceisabinaryformatDBMfilecontainingthesamecontentsasaPlainTextformatfile,butinaspecialrepresentationwhichisoptimizedforreallyfastlookups.Thetypecanbesdbm,gdbm,ndbm,ordbdependingoncompile-timesettings.Ifthetypeisommitted,thecompile-timedefaultwillbechosen.YoucancreatesuchafilewithanyDBMtoolorwiththefollowingPerlscript.BesuretoadjustittocreatetheappropriatetypeofDBM.TheexamplecreatesanNDBM

file.

#!/path/to/bin/perl

##

##txt2dbm--converttxtmaptodbmformat

##

useNDBM_File;

useFcntl;

($txtmap,$dbmmap)=@ARGV;

open(TXT,"<$txtmap")ordie"Couldn'topen$txtmap!\n";

tie(%DB,'NDBM_File',$dbmmap,O_RDWR|O_TRUNC|O_CREAT,0644)

ordie"Couldn'tcreate$dbmmap!\n";

while(<TXT>){

nextif(/^\s*#/or/^\s*$/);

$DB{$1}=$2if(/^\s*(\S+)\s+(\S+)/);

}

untie%DB;

close(TXT);

$txt2dbmmap.txtmap.db

InternalFunctionMapType:int,MapSource:InternalApachefunctionHere,thesourceisaninternalApachefunction.Currentlyyoucannotcreateyourown,butthefollowingfunctionsalreadyexist:

toupper:Convertsthekeytoalluppercase.

tolower:Convertsthekeytoalllowercase.escape:Translatesspecialcharactersinthekeytohex-encodings.unescape:Translateshex-encodingsinthekeybacktospecialcharacters.

ExternalRewritingProgramMapType:prg,MapSource:UnixfilesystempathtovalidregularfileHerethesourceisaprogram,notamapfile.Tocreateityoucanusealanguageofyourchoice,buttheresulthastobeanexecutableprogram(eitherobject-codeorascriptwiththemagiccookietrick'#!/path/to/interpreter'asthefirstline).

Thisprogramisstartedonce,whentheApacheserverisstarted,andthencommunicateswiththerewritingengineviaitsstdinandstdoutfile-handles.Foreachmap-functionlookupitwillreceivethekeytolookupasanewline-terminatedstringonstdin.Itthenhastogivebackthelooked-upvalueasanewline-terminatedstringonstdoutorthefour-characterstring``NULL''ifitfails(i.e.,thereisnocorrespondingvalueforthegivenkey).Atrivialprogramwhichwillimplementa1:1map(i.e.,key==value)couldbe:

Externalrewritingprogramsarenotstartedifthey'redefinedinacontextthatdoesnothaveRewriteEnginesettoon

.

#!/usr/bin/perl

$|=1;

while(<STDIN>){

#...puthereanytransformationsorlookups...

print$_;

}

Butbeverycareful:

1. ``Keepitsimple,stupid''(KISS).Ifthisprogramhangs,itwillcauseApachetohangwhentryingtousetherelevantrewriterule.

2. AcommonmistakeistousebufferedI/Oonstdout.Avoidthis,asitwillcauseadeadloop!``$|=1''isusedabove,topreventthis.

3. TheRewriteLockdirectivecanbeusedtodefinealockfilewhichmod_rewritecanusetosynchronizecommunicationwiththemappingprogram.Bydefaultnosuchsynchronizationtakesplace.

TheRewriteMapdirectivecanoccurmorethanonce.Foreachmapping-functionuseoneRewriteMapdirectivetodeclareitsrewritingmapfile.Whileyoucannotdeclareamapinper-directorycontextitisofcoursepossibletousethismapinper-directorycontext.

NoteForplaintextandDBMformatfilesthelooked-upkeysarecachedin-coreuntilthemtimeofthemapfilechangesortheserverdoesarestart.Thiswayyoucanhavemap-functionsinruleswhichareusedforeveryrequest.Thisisnoproblem,becausetheexternallookuponlyhappensonce!

RewriteOptionsDirective

Description: SetssomespecialoptionsfortherewriteengineSyntax: RewriteOptionsOptions

Default: RewriteOptionsMaxRedirects=10

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_rewriteCompatibility: MaxRedirectsisavailableinApache2.0.45

andlater

TheRewriteOptionsdirectivesetssomespecialoptionsforthecurrentper-serverorper-directoryconfiguration.TheOptionstringscanbeoneofthefollowing:

inherit

Thisforcesthecurrentconfigurationtoinherittheconfigurationoftheparent.Inper-virtual-servercontextthismeansthatthemaps,conditionsandrulesofthemainserverareinherited.Inper-directorycontextthismeansthatconditionsandrulesoftheparentdirectory's.htaccessconfigurationareinherited.

MaxRedirects=number

Inordertopreventendlessloopsofinternalredirectsissuedbyper-directoryRewriteRules,mod_rewriteabortstherequestafterreachingamaximumnumberofsuchredirectsandrespondswithan500InternalServerError.Ifyoureallyneedmoreinternalredirectsthan10perrequest,youmayincreasethedefaulttothedesiredvalue.

AllowAnyURI

WhenRewriteRuleisusedinVirtualHostorservercontextwithversion2.0.65orlaterofhttpd,mod_rewrite

willonlyprocesstherewriterulesiftherequestURIisaURL-path.Thisavoidssomesecurityissueswhereparticularrulescouldallow"surprising"patternexpansions(seeCVE-2011-3368andCVE-2011-4317).TolifttherestrictiononmatchingaURL-path,theAllowAnyURIoptioncanbeenabled,andmod_rewritewillapplytherulesettoanyrequestURIstring,regardlessofwhetherthatstringmatchestheURL-pathgrammarrequiredbytheHTTPspecification.

SecurityWarning

Enablingthisoptionwillmaketheservervulnerabletosecurityissuesifusedwithrewriteruleswhicharenotcarefullyauthored.Itisstronglyrecommendedthatthisoptionisnotused.Inparticular,bewareofinputstringscontainingthe'@'characterwhichcouldchangetheinterpretationofthetransformedURI,aspertheaboveCVEnames.

MergeBase

Withthisoption,thevalueofRewriteBaseiscopiedfromwhereit'sexplicitlydefinedintoanysub-directoryorsub-locationthatdoesn'tdefineitsownRewriteBase.ThisflagisavailableforApacheHTTPServer2.0.65andlater.

RewriteRuleDirective

Description: DefinesrulesfortherewritingengineSyntax: RewriteRulePatternSubstitution

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_rewriteCompatibility: Thecookie-flagisavailableinApache2.0.40and

later.

TheRewriteRuledirectiveistherealrewritingworkhorse.Thedirectivecanoccurmorethanonce,witheachinstancedefiningasinglerewriterule.Theorderinwhichtheserulesaredefinedisimportant-thisistheorderinwhichtheywillbeappliedatrun-time.

Patternisaperlcompatibleregularexpression,whichisappliedtothecurrentURL.``Current''meansthevalueoftheURLwhenthisruleisapplied.ThismaynotbetheoriginallyrequestedURL,whichmayalreadyhavematchedapreviousrule,andhavebeenaltered.

Somehintsonthesyntaxofregularexpressions:

Text:

.Anysinglecharacter

[chars]Characterclass:Anycharacteroftheclass``chars''

[^chars]Characterclass:Notacharacteroftheclass``chars''

text1|text2Alternative:text1ortext2

Quantifiers:

?0or1occurrencesoftheprecedingtext

*0orNoccurrencesoftheprecedingtext(N>0)

+1orNoccurrencesoftheprecedingtext(N>1)

Grouping:

(text)Groupingoftext

(usedeithertosetthebordersofanalternativeasabove,or

tomakebackreferences,wheretheNthgroupcan

bereferredtoontheRHSofaRewriteRuleas$N)

Anchors:

^Start-of-lineanchor

$End-of-lineanchor

Escaping:

\charescapethegivenchar

(forinstance,tospecifythechars".[]()"etc.)

Formoreinformationaboutregularexpressions,havealookattheperlregularexpressionmanpage("perldocperlre").Ifyouareinterestedinmoredetailedinformationaboutregularexpressionsandtheirvariants(POSIXregexetc.)thefollowingbookisdedicatedtothistopic:

MasteringRegularExpressions,2ndEditionJeffreyE.F.FriedlO'Reilly&Associates,Inc.2002ISBN0-596-00289-0

Inmod_rewrite,theNOTcharacter('!')isalsoavailableasapossiblepatternprefix.Thisenablesyoutonegateapattern;tosay,forinstance:``ifthecurrentURLdoesNOTmatchthispattern''.Thiscanbeusedforexceptionalcases,whereitiseasiertomatchthenegativepattern,orasalastdefaultrule.

NoteWhenusingtheNOTcharactertonegateapattern,youcannotincludegroupedwildcardpartsinthatpattern.Thisisbecause,whenthepatterndoesNOTmatch(ie,thenegationmatches),therearenocontentsforthegroups.Thus,ifnegatedpatternsareused,youcannotuse$Ninthesubstitutionstring!

Thesubstitutionofarewriteruleisthestringwhichissubstituted

for(orreplaces)theoriginalURLwhichPatternmatched.Inadditiontoplaintext,itcaninclude

1. back-references($N)totheRewriteRulepattern

2. back-references(%N)tothelastmatchedRewriteCondpattern

3. server-variablesasinruleconditiontest-strings(%{VARNAME})

4. mapping-functioncalls(${mapname:key|default})

Back-referencesareidentifiersoftheform$N(N=0..9),whichwillbereplacedbythecontentsoftheNthgroupofthematchedPattern.Theserver-variablesarethesameasfortheTestStringofaRewriteConddirective.Themapping-functionscomefromtheRewriteMapdirectiveandareexplainedthere.Thesethreetypesofvariablesareexpandedintheorderabove.

Asalreadymentioned,allrewriterulesareappliedtotheSubstitution(intheorderinwhichtheyaredefinedintheconfigfile).TheURLiscompletelyreplacedbytheSubstitutionandtherewritingprocesscontinuesuntilallruleshavebeenapplied,oritisexplicitlyterminatedbyaLflag-seebelow.

Thereisaspecialsubstitutionstringnamed'-'whichmeans:NOsubstitution!ThisisusefulinprovidingrewritingruleswhichonlymatchURLsbutdonotsubstituteanythingforthem.ItiscommonlyusedinconjunctionwiththeC(chain)flag,inordertoapplymorethanonepatternbeforesubstitutionoccurs.

AdditionallyyoucansetspecialflagsforSubstitutionbyappending[flags]asthethirdargumenttotheRewriteRuledirective.Flagsisacomma-separatedlistofanyofthefollowingflags:

'chain|C'(chainedwithnextrule)

Thisflagchainsthecurrentrulewiththenextrule(whichitselfcanbechainedwiththefollowingrule,andsoon).Thishasthefollowingeffect:ifarulematches,thenprocessingcontinuesasusual-theflaghasnoeffect.Iftheruledoesnotmatch,thenallfollowingchainedrulesareskipped.Forinstance,itcanbeusedtoremovethe``.www''part,insideaper-directoryruleset,whenyouletanexternalredirecthappen(wherethe``.www''partshouldnotoccur!).'cookie|CO=NAME:VAL:domain[:lifetime[:path]]'(setcookie)Thissetsacookieintheclient'sbrowser.Thecookie'snameisspecifiedbyNAMEandthevalueisVAL.Thedomainfieldisthedomainofthecookie,suchas'.apache.org',theoptionallifetimeisthelifetimeofthecookieinminutes,andtheoptionalpathisthepathofthecookie'env|E=VAR:VAL'(setenvironmentvariable)ThisforcesanenvironmentvariablenamedVARtobesettothevalueVAL,whereVALcancontainregexpbackreferences($Nand%N)whichwillbeexpanded.Youcanusethisflagmorethanonce,tosetmorethanonevariable.Thevariablescanlaterbedereferencedinmanysituations,mostcommonlyfromwithinXSSI(via<!--#echovar="VAR"-->)orCGI($ENV{'VAR'}).YoucanalsodereferencethevariableinalaterRewriteCondpattern,using%{ENV:VAR}.UsethistostripinformationfromURLs,whilemaintainingarecordofthatinformation.'forbidden|F'(forceURLtobeforbidden)ThisforcesthecurrentURLtobeforbidden-itimmediatelysendsbackaHTTPresponseof403(FORBIDDEN).UsethisflaginconjunctionwithappropriateRewriteCondstoconditionallyblocksomeURLs.'gone|G'(forceURLtobegone)ThisforcesthecurrentURLtobegone-itimmediatelysendsbackaHTTPresponseof410(GONE).Usethisflagtomark

pageswhichnolongerexistasgone.'last|L'(lastrule)Stoptherewritingprocesshereanddon'tapplyanymorerewriterules.ThiscorrespondstothePerllastcommandorthebreakcommandinC.UsethisflagtopreventthecurrentlyrewrittenURLfrombeingrewrittenfurtherbyfollowingrules.Forexample,useittorewritetheroot-pathURL('/')toarealone,e.g.,'/e/www/'.'next|N'(nextround)Re-runtherewritingprocess(startingagainwiththefirstrewritingrule).Thistime,theURLtomatchisnolongertheoriginalURL,butrathertheURLreturnedbythelastrewritingrule.ThiscorrespondstothePerlnextcommandorthecontinuecommandinC.Usethisflagtorestarttherewritingprocess-toimmediatelygotothetopoftheloop.Becarefulnottocreateaninfiniteloop!'nocase|NC'(nocase)ThismakesthePatterncase-insensitive,ignoringdifferencebetween'A-Z'and'a-z'whenPatternismatchedagainstthecurrentURL.'noescape|NE'(noURIescapingofoutput)Thisflagpreventsmod_rewritefromapplyingtheusualURIescapingrulestotheresultofarewrite.Ordinarily,specialcharacters(suchas'%','$',';',andsoon)willbeescapedintotheirhexcodeequivalents('%25','%24',and'%3B',respectively);thisflagpreventsthisfromhappening.Thisallowspercentsymbolstoappearintheoutput,asin

RewriteRule/foo/(.*)/bar?arg=P1\%3d$1[R,NE]

whichwouldturn'/foo/zed'intoasaferequestfor'/bar?arg=P1=zed'.'nosubreq|NS'(notforinternalsub-requests)

Thisflagforcestherewriteenginetoskiparewriteruleifthecurrentrequestisaninternalsub-request.Forinstance,sub-requestsoccurinternallyinApachewhenmod_includetriestofindoutinformationaboutpossibledirectorydefaultfiles(index.xxx).Onsub-requestsitisnotalwaysuseful,andcanevencauseerrors,ifthecompletesetofrulesareapplied.Usethisflagtoexcludesomerules.Todecidewhetherornottousethisrule:ifyouprefixURLswithCGI-scripts,toforcethemtobeprocessedbytheCGI-script,it'slikelythatyouwillrunintoproblems(orsignificantoverhead)onsub-requests.Inthesecases,usethisflag.'proxy|P'(forceproxy)Thisflagforcesthesubstitutionparttobeinternallysentasaproxyrequestandimmediately(rewriteprocessingstopshere)putthroughtheproxymodule.YoumustmakesurethatthesubstitutionstringisavalidURI(typicallystartingwithhttp://hostname)whichcanbehandledbytheApacheproxymodule.Ifnot,youwillgetanerrorfromtheproxymodule.UsethisflagtoachieveamorepowerfulimplementationoftheProxyPassdirective,tomapremotecontentintothenamespaceofthelocalserver.Note:mod_proxymustbeenabledinordertousethisflag.

'passthrough|PT'(passthroughtonexthandler)Thisflagforcestherewriteenginetosettheurifieldoftheinternalrequest_recstructuretothevalueofthefilenamefield.Thisflagisjustahacktoenablepost-processingoftheoutputofRewriteRuledirectives,usingAlias,ScriptAlias,Redirect,andotherdirectivesfromvariousURI-to-filenametranslators.Forexample,torewrite/abcto/defusingmod_rewrite,andthen/defto/ghiusingmod_alias:

RewriteRule^/abc(.*)/def$1[PT]

Alias/def/ghi

IfyouomitthePTflag,mod_rewritewillrewriteuri=/abc/...tofilename=/def/...asafullAPI-compliantURI-to-filenametranslatorshoulddo.Thenmod_aliaswilltrytodoaURI-to-filenametransition,whichwillfail.Note:YoumustusethisflagifyouwanttomixdirectivesfromdifferentmoduleswhichallowURL-to-filenametranslators.Thetypicalexampleistheuseofmod_aliasandmod_rewrite.

'qsappend|QSA'(querystringappend)Thisflagforcestherewriteenginetoappendaquerystringpartofthesubstitutionstringtotheexistingstring,insteadofreplacingit.Usethiswhenyouwanttoaddmoredatatothequerystringviaarewriterule.'redirect|R[=code]'(forceredirect)PrefixSubstitutionwithhttp://thishost[:thisport]/(whichmakesthenewURLaURI)toforceaexternalredirection.Ifnocodeisgiven,aHTTPresponseof302(MOVEDTEMPORARILY)willbereturned.Ifyouwanttouseotherresponsecodesintherange300-400,simplyspecifytheappropriatenumberoruseoneofthefollowingsymbolicnames:temp(default),permanent,seeother.UsethisforrulestocanonicalizetheURLandreturnittotheclient-totranslate``/~''into``/u/'',ortoalwaysappendaslashto/u/user,etc.Note:Whenyouusethisflag,makesurethatthesubstitutionfieldisavalidURL!Otherwise,youwillberedirectingtoaninvalidlocation.Rememberthatthisflagonitsownwillonlyprependhttp://thishost[:thisport]/totheURL,andrewritingwillcontinue.Usually,youwillwanttostoprewritingatthispoint,andredirectimmediately.Tostoprewriting,you

shouldaddthe'L'flag.'skip|S=num'(skipnextrule(s))Thisflagforcestherewritingenginetoskipthenextnumrulesinsequence,ifthecurrentrulematches.Usethistomakepseudoif-then-elseconstructs:Thelastruleofthethen-clausebecomesskip=N,whereNisthenumberofrulesintheelse-clause.(Thisisnotthesameasthe'chain|C'flag!)'type|T=MIME-type'(forceMIMEtype)ForcetheMIME-typeofthetargetfiletobeMIME-type.Thiscanbeusedtosetupthecontent-typebasedonsomeconditions.Forexample,thefollowingsnippetallows.phpfilestobedisplayedbymod_phpiftheyarecalledwiththe.phpsextension:

RewriteRule^(.+\.php)s$$1[T=application/x-httpd-php-

source]

Homedirectoryexpansion

Whenthesubstitutionstringbeginswithastringresembling"/~user"(viaexplicittextorbackreferences),mod_rewriteperformshomedirectoryexpansionindependentofthepresenceorconfigurationofmod_userdir.

ThisexpansiondoesnotoccurwhenthePTflagisusedontheRewriteRuledirective.

Note:Enablingrewritesinper-directorycontextToenabletherewritingengineforper-directoryconfigurationfiles,youneedtoset``RewriteEngineOn''inthesefilesand``OptionsFollowSymLinks''mustbeenabled.IfyouradministratorhasdisabledoverrideofFollowSymLinksforauser'sdirectory,thenyoucannotusetherewritingengine.Thisrestrictionisneededforsecurityreasons.

Note:Patternmatchinginper-directorycontextNeverforgetthatPatternisappliedtoacompleteURLinper-serverconfigurationfiles.However,inper-directoryconfigurationfiles,theper-directoryprefix(whichalwaysisthesameforaspecificdirectory)isautomaticallyremovedforthepatternmatchingandautomaticallyaddedafterthesubstitutionhasbeendone.Thisfeatureisessentialformanysortsofrewriting-withoutthis,youwouldalwayshavetomatchtheparentdirectorywhichisnotalwayspossible.

Thereisoneexception:Ifasubstitutionstringstartswith``http://'',thenthedirectoryprefixwillnotbeadded,andanexternalredirectorproxythroughput(ifflagPisused)isforced!

Note:SubstitutionofAbsoluteURLs

Whenyouprefixasubstitutionfieldwithhttp://thishost[:thisport],mod_rewritewillautomaticallystripthatout.Thisauto-reductiononURLswithanimplicitexternalredirectismostusefulincombinationwithamapping-functionwhichgeneratesthehostnamepart.

Remember:Anunconditionalexternalredirecttoyourownserverwillnotworkwiththeprefixhttp://thishostbecauseofthisfeature.Toachievesuchaself-redirect,youhavetousetheR-flag.

Note:QueryString

ThePatternwillnotbematchedagainstthequerystring.Instead,youmustuseaRewriteCondwiththe%{QUERY_STRING}variable.Youcan,however,createURLsinthesubstitutionstring,containingaquerystringpart.Simplyuseaquestionmarkinsidethesubstitutionstring,toindicatethatthefollowingtextshouldbere-injectedintothequerystring.When

youwanttoeraseanexistingquerystring,endthesubstitutionstringwithjustaquestionmark.Tocombineanewquerystringwithanoldone,usethe[QSA]flag.

Hereareallpossiblesubstitutioncombinationsandtheirmeanings:

Insideper-serverconfiguration(httpd.conf)forrequest``GET/somepath/pathinfo'':

GivenRuleResultingSubstitution

--------------------------------------------------------------------------------

^/somepath(.*)otherpath$1invalid,notsupported

^/somepath(.*)otherpath$1[R]invalid,notsupported

^/somepath(.*)otherpath$1[P]invalid,notsupported

--------------------------------------------------------------------------------

^/somepath(.*)/otherpath$1/otherpath/pathinfo

^/somepath(.*)/otherpath$1[R]http://thishost/otherpath/pathinfo

viaexternalredirection

^/somepath(.*)/otherpath$1[P]doesn'tmakesense,notsupported

--------------------------------------------------------------------------------

^/somepath(.*)http://thishost/otherpath$1/otherpath/pathinfo

^/somepath(.*)http://thishost/otherpath$1[R]http://thishost/otherpath/pathinfo

viaexternalredirection

^/somepath(.*)http://thishost/otherpath$1[P]doesn'tmakesense,notsupported

--------------------------------------------------------------------------------

^/somepath(.*)http://otherhost/otherpath$1http://otherhost/otherpath/pathinfo

viaexternalredirection

^/somepath(.*)http://otherhost/otherpath$1[R]http://otherhost/otherpath/pathinfo

viaexternalredirection

(the[R]flagisredundant)

^/somepath(.*)http://otherhost/otherpath$1[P]http://otherhost/otherpath/pathinfo

viainternalproxy

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Insideper-directoryconfigurationfor/somepath(/physical/path/to/somepath/.htacccess,withRewriteBase/somepath)forrequest``GET/somepath/localpath/pathinfo'':

GivenRuleResultingSubstitution

--------------------------------------------------------------------------------

^localpath(.*)otherpath$1/somepath/otherpath/pathinfo

^localpath(.*)otherpath$1[R]http://thishost/somepath/otherpath/pathinfo

viaexternalredirection

^localpath(.*)otherpath$1[P]doesn'tmakesense,notsupported

--------------------------------------------------------------------------------

^localpath(.*)/otherpath$1/otherpath/pathinfo

^localpath(.*)/otherpath$1[R]http://thishost/otherpath/pathinfo

viaexternalredirection

^localpath(.*)/otherpath$1[P]doesn'tmakesense,notsupported

--------------------------------------------------------------------------------

^localpath(.*)http://thishost/otherpath$1/otherpath/pathinfo

^localpath(.*)http://thishost/otherpath$1[R]http://thishost/otherpath/pathinfo

viaexternalredirection

^localpath(.*)http://thishost/otherpath$1[P]doesn'tmakesense,notsupported

--------------------------------------------------------------------------------

^localpath(.*)http://otherhost/otherpath$1http://otherhost/otherpath/pathinfo

viaexternalredirection

^localpath(.*)http://otherhost/otherpath$1[R]http://otherhost/otherpath/pathinfo

viaexternalredirection

(the[R]flagisredundant)

^localpath(.*)http://otherhost/otherpath$1[P]http://otherhost/otherpath/pathinfo

viainternalproxy

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_setenvif

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

:: Base: setenvif_module: mod_setenvif.c

mod_setenvif

BrowserMatch^Mozillanetscape

BrowserMatchMSIE!netscape

Apache

BrowserMatch

: HTTPUser-Agent: BrowserMatchregex[!]env-variable[=value]

[[!]env-variable[=value]]...

: ,,,.htaccess: FileInfo: Base: mod_setenvif

BrowserMatch SetEnvIf User-AgentHTTP:

BrowserMatchNoCaseRobotis_a_robot

SetEnvIfNoCaseUser-AgentRobotis_a_robot

:

BrowserMatch^Mozillaformsjpeg=yesbrowser=netscape

BrowserMatch"^Mozilla/[2-3]"tablesagifframesjavascript

BrowserMatchMSIE!javascript

BrowserMatchNoCase

: HTTPUser-Agent: BrowserMatchNoCaseregex[!]env-

variable[=value][[!]env-variable[=value]]

...

: ,,,.htaccess: FileInfo: Base: mod_setenvif: Apache1.2 (Apache1.2

BrowserMatchNoCase BrowserMatch

BrowserMatchNoCasemacplatform=macintosh

BrowserMatchNoCasewinplatform=windows

BrowserMatch BrowserMatchNoCaseSetEnvIfNoCase 2:

BrowserMatchNoCaseRobotis_a_robot

SetEnvIfNoCaseUser-AgentRobotis_a_robot

SetEnvIf

:: SetEnvIfattributeregex[!]env-

variable[=value][[!]env-variable[=value]]

...

: ,,,.htaccess: FileInfo: Base: mod_setenvif

SetEnvIf

1. HTTP( RFC2616 ) Host,User-AgentReferer,Accept-Language

2. :

Remote_Host-()

Remote_Addr-IP

Server_Addr-IP (2.0.43)

Request_Method-( GET,POST)

Request_Protocol-

Request_URI-URL

3. SetEnvIf SetEnvIf[NoCase]()

( regex) PerlPOSIX.2egrep regexattribute

1. varname

2. !varname

3. varname=value

"1" regex

:SetEnvIfRequest_URI"\.gif$"object_is_image=gif

SetEnvIfRequest_URI"\.jpg$"object_is_image=jpg

SetEnvIfRequest_URI"\.xbm$"object_is_image=xbm

:

SetEnvIfRefererwww\.mydomain\.comintra_site_referral

:

SetEnvIfobject_is_imagexbmXBIT_PROCESSING=1

:

SetEnvIf^TS*^[a-z].*HAVE_TS

object_is_imageintra_site_referral

"TS"[a-z]

Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

SetEnvIfNoCase

:: SetEnvIfNoCaseattributeregex[!]env-

variable[=value][[!]env-variable[=value]]

...

: ,,,.htaccess: FileInfo: Base: mod_setenvif: Apache1.3

SetEnvIfNoCase SetEnvIf

SetEnvIfNoCaseHostApache\.Orgsite=apache

HTTP Host: Apache.Org apache.orgsite" apache"

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_so

:: Extension: so_module: mod_so.c: Window()

Base

Unix ( .so)

Apache1.3Apache2.0 ―Apache2.0

Windows

Apache1.3.152.0Windows ―mod_foo.so

mod_soApacheModuleFoo.dll

ApacheAPIUNIXWindows WindowsWindowsUnix

UnixConfigure ApacheCore

DLL DLLApache

DLL AP_MODULE_DECLARE_DATA(Apache)

modulefoo_module;

moduleAP_MODULE_DECLARE_DATAfoo_module;

Unix Windows

DLL libhttpd.lib modules .dsp

DLL modules

LoadFile

:: LoadFilefilename[filename]...

:: Extension: mod_so

LoadFile

:

LoadFilelibexec/libxmlparse.so

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

LoadModule

: : LoadModulemodulefilename

:: Extension: mod_so

LoadModule filename:

LoadModulestatus_modulemodules/mod_status.so

ServerRootmodules

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_speling

: URL: Extension: speling_module: mod_speling.c

Apache

Apache

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

CheckSpelling

: spelling: CheckSpellingon|off

: CheckSpellingOff

: ,,,.htaccess: Options: Extension: mod_speling: CheckSpellingApache1.1Apache1.3

ApacheApache1.3.2 CheckSpelling

(http://my.host/~apahce/) <Location/status>

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_ssl

Description: StrongcryptographyusingtheSecureSocketsLayer(SSL)andTransportLayerSecurity(TLS)protocols

Status: ExtensionModuleIdentifier: ssl_moduleSourceFile: mod_ssl.c

SummaryThismoduleprovidesSSLv2/v3andTLSv1supportfortheApacheHTTPServer.ItwascontributedbyRalfS.Engeschallbasedonhismod_sslprojectandoriginallyderivedfromworkbyBenLaurie.

ThismodulereliesonOpenSSLtoprovidethecryptographyengine.

Furtherdetails,discussion,andexamplesareprovidedintheSSLdocumentation.

EnvironmentVariables

ThismoduleprovidesalotofSSLinformationasadditionalenvironmentvariablestotheSSIandCGInamespace.Thegeneratedvariablesarelistedinthetablebelow.Forbackwardcompatibilitytheinformationcanbemadeavailableunderdifferentnames,too.LookintheCompatibilitychapterfordetailsonthecompatibilityvariables.

VariableName: ValueType:

Description:

HTTPS flag HTTPSisbeingused.SSL_PROTOCOL string TheSSLprotocolversion

(SSLv2,SSLv3,TLSv1)SSL_SESSION_ID string Thehex-encodedSSL

sessionidSSL_CIPHER string Thecipherspecification

nameSSL_CIPHER_EXPORT string trueifcipherisan

exportcipherSSL_CIPHER_USEKEYSIZE number Numberofcipherbits

(actuallyused)SSL_CIPHER_ALGKEYSIZE number Numberofcipherbits

(possible)SSL_VERSION_INTERFACE string Themod_sslprogram

versionSSL_VERSION_LIBRARY string TheOpenSSLprogram

versionSSL_CLIENT_M_VERSION string Theversionoftheclient

certificateSSL_CLIENT_M_SERIAL string Theserialoftheclient

certificateSSL_CLIENT_S_DN string SubjectDNinclient's

certificateSSL_CLIENT_S_DN_x509 string Componentofclient's

SubjectDNSSL_CLIENT_I_DN string IssuerDNofclient's

certificateSSL_CLIENT_I_DN_x509 string Componentofclient's

IssuerDNSSL_CLIENT_V_START string Validityofclient's

certificate(starttime)SSL_CLIENT_V_END string Validityofclient's

certificate(endtime)SSL_CLIENT_A_SIG string Algorithmusedforthe

signatureofclient'scertificate

SSL_CLIENT_A_KEY string Algorithmusedforthepublickeyofclient'scertificate

SSL_CLIENT_CERT string PEM-encodedclientcertificate

SSL_CLIENT_CERT_CHAINn string PEM-encodedcertificatesinclientcertificatechain

SSL_CLIENT_VERIFY string NONE,SUCCESS,GENEROUSorFAILED:reason

SSL_SERVER_M_VERSION string Theversionoftheservercertificate

SSL_SERVER_M_SERIAL string Theserialoftheservercertificate

SSL_SERVER_S_DN string SubjectDNinserver'scertificate

SSL_SERVER_S_DN_x509 string Componentofserver's

SubjectDNSSL_SERVER_I_DN string IssuerDNofserver's

certificateSSL_SERVER_I_DN_x509 string Componentofserver's

IssuerDNSSL_SERVER_V_START string Validityofserver's

certificate(starttime)SSL_SERVER_V_END string Validityofserver's

certificate(endtime)SSL_SERVER_A_SIG string Algorithmusedforthe

signatureofserver'scertificate

SSL_SERVER_A_KEY string Algorithmusedforthepublickeyofserver'scertificate

SSL_SERVER_CERT string PEM-encodedservercertificate

[wherex509isacomponentofaX.509DN:C,ST,L,O,OU,CN,T,I,G,S,D,UID,Email]

CustomLogFormats

Whenmod_sslisbuiltintoApacheoratleastloaded(underDSOsituation)additionalfunctionsexistfortheCustomLogFormatofmod_log_config.Firstthereisanadditional``%{varname}x''eXtensionformatfunctionwhichcanbeusedtoexpandanyvariablesprovidedbyanymodule,especiallythoseprovidedbymod_sslwhichcanyoufindintheabovetable.

Forbackwardcompatibilitythereisadditionallyaspecial``%{name}c''cryptographyformatfunctionprovided.InformationaboutthisfunctionisprovidedintheCompatibilitychapter.

Example:

CustomLoglogs/ssl_request_log\"%t%h%{SSL_PROTOCOL}x%

{SSL_CIPHER}x\"%r\"%b"

SSLCACertificateFileDirective

Description: FileofconcatenatedPEM-encodedCACertificatesforClientAuth

Syntax: SSLCACertificateFilefile-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoucanassembletheCertificatesofCertificationAuthorities(CA)whoseclientsyoudealwith.TheseareusedforClientAuthentication.SuchafileissimplytheconcatenationofthevariousPEM-encodedCertificatefiles,inorderofpreference.Thiscanbeusedalternativelyand/oradditionallytoSSLCACertificatePath.

ExampleSSLCACertificateFile/usr/local/apache2/conf/ssl.crt/ca-bundle-

client.crt

SSLCACertificatePathDirective

Description: DirectoryofPEM-encodedCACertificatesforClientAuth

Syntax: SSLCACertificatePathdirectory-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

ThisdirectivesetsthedirectorywhereyoukeeptheCertificatesofCertificationAuthorities(CAs)whoseclientsyoudealwith.TheseareusedtoverifytheclientcertificateonClientAuthentication.

ThefilesinthisdirectoryhavetobePEM-encodedandareaccessedthroughhashfilenames.Sousuallyyoucan'tjustplacetheCertificatefilesthere:youalsohavetocreatesymboliclinksnamedhash-value.N.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.

ExampleSSLCACertificatePath/usr/local/apache2/conf/ssl.crt/

SSLCARevocationFileDirective

Description: FileofconcatenatedPEM-encodedCACRLsforClientAuth

Syntax: SSLCARevocationFilefile-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoucanassembletheCertificateRevocationLists(CRL)ofCertificationAuthorities(CA)whoseclientsyoudealwith.TheseareusedforClientAuthentication.SuchafileissimplytheconcatenationofthevariousPEM-encodedCRLfiles,inorderofpreference.Thiscanbeusedalternativelyand/oradditionallytoSSLCARevocationPath.

ExampleSSLCARevocationFile/usr/local/apache2/conf/ssl.crl/ca-bundle-

client.crl

SSLCARevocationPathDirective

Description: DirectoryofPEM-encodedCACRLsforClientAuthSyntax: SSLCARevocationPathdirectory-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

ThisdirectivesetsthedirectorywhereyoukeeptheCertificateRevocationLists(CRL)ofCertificationAuthorities(CAs)whoseclientsyoudealwith.TheseareusedtorevoketheclientcertificateonClientAuthentication.

ThefilesinthisdirectoryhavetobePEM-encodedandareaccessedthroughhashfilenames.SousuallyyouhavenotonlytoplacetheCRLfilesthere.Additionallyyouhavetocreatesymboliclinksnamedhash-value.rN.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.

ExampleSSLCARevocationPath/usr/local/apache2/conf/ssl.crl/

SSLCertificateChainFileDirective

Description: FileofPEM-encodedServerCACertificatesSyntax: SSLCertificateChainFilefile-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

Thisdirectivesetstheoptionalall-in-onefilewhereyoucanassemblethecertificatesofCertificationAuthorities(CA)whichformthecertificatechainoftheservercertificate.ThisstartswiththeissuingCAcertificateofoftheservercertificateandcanrangeuptotherootCAcertificate.SuchafileissimplytheconcatenationofthevariousPEM-encodedCACertificatefiles,usuallyincertificatechainorder.

Thisshouldbeusedalternativelyand/oradditionallytoSSLCACertificatePathforexplicitlyconstructingtheservercertificatechainwhichissenttothebrowserinadditiontotheservercertificate.ItisespeciallyusefultoavoidconflictswithCAcertificateswhenusingclientauthentication.BecausealthoughplacingaCAcertificateoftheservercertificatechainintoSSLCACertificatePathhasthesameeffectforthecertificatechainconstruction,ithastheside-effectthatclientcertificatesissuedbythissameCAcertificatearealsoacceptedonclientauthentication.That'susuallynotoneexpect.

Butbecareful:Providingthecertificatechainworksonlyifyouareusingasingle(eitherRSAorDSA)basedservercertificate.IfyouareusingacoupledRSA+DSAcertificatepair,thiswillworkonlyifactuallybothcertificatesusethesamecertificatechain.Elsethebrowserswillbeconfusedinthissituation.

ExampleSSLCertificateChainFile/usr/local/apache2/conf/ssl.crt/ca.crt

SSLCertificateFileDirective

Description: ServerPEM-encodedX.509CertificatefileSyntax: SSLCertificateFilefile-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

ThisdirectivepointstothePEM-encodedCertificatefilefortheserverandoptionallyalsotothecorrespondingRSAorDSAPrivateKeyfileforit(containedinthesamefile).IfthecontainedPrivateKeyisencryptedthePassPhrasedialogisforcedatstartuptime.Thisdirectivecanbeuseduptotwotimes(referencingdifferentfilenames)whenbothaRSAandaDSAbasedservercertificateisusedinparallel.

ExampleSSLCertificateFile/usr/local/apache2/conf/ssl.crt/server.crt

SSLCertificateKeyFileDirective

Description: ServerPEM-encodedPrivateKeyfileSyntax: SSLCertificateKeyFilefile-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

ThisdirectivepointstothePEM-encodedPrivateKeyfilefortheserver.IfthePrivateKeyisnotcombinedwiththeCertificateintheSSLCertificateFile,usethisadditionaldirectivetopointtothefilewiththestand-alonePrivateKey.WhenSSLCertificateFileisusedandthefilecontainsboththeCertificateandthePrivateKeythisdirectiveneednotbeused.Butwestronglydiscouragethispractice.InsteadwerecommendyoutoseparatetheCertificateandthePrivateKey.IfthecontainedPrivateKeyisencrypted,thePassPhrasedialogisforcedatstartuptime.Thisdirectivecanbeuseduptotwotimes(referencingdifferentfilenames)whenbothaRSAandaDSAbasedprivatekeyisusedinparallel.

ExampleSSLCertificateKeyFile

/usr/local/apache2/conf/ssl.key/server.key

SSLCipherSuiteDirective

Description: CipherSuiteavailablefornegotiationinSSLhandshakeSyntax: SSLCipherSuitecipher-spec

Default: SSLCipherSuite

ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP

Context: serverconfig,virtualhost,directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_ssl

Thiscomplexdirectiveusesacolon-separatedcipher-specstringconsistingofOpenSSLcipherspecificationstoconfiguretheCipherSuitetheclientispermittedtonegotiateintheSSLhandshakephase.Noticethatthisdirectivecanbeusedbothinper-serverandper-directorycontext.Inper-servercontextitappliestothestandardSSLhandshakewhenaconnectionisestablished.Inper-directorycontextitforcesaSSLrenegotationwiththereconfiguredCipherSuiteaftertheHTTPrequestwasreadbutbeforetheHTTPresponseissent.

AnSSLcipherspecificationincipher-speciscomposedof4majorattributesplusafewextraminorones:

KeyExchangeAlgorithm:RSAorDiffie-Hellmanvariants.AuthenticationAlgorithm:RSA,Diffie-Hellman,DSSornone.Cipher/EncryptionAlgorithm:DES,Triple-DES,RC4,RC2,IDEAornone.MACDigestAlgorithm:MD5,SHAorSHA1.

AnSSLciphercanalsobeanexportcipherandiseitheraSSLv2orSSLv3/TLSv1cipher(hereTLSv1isequivalenttoSSLv3).To

specifywhichcipherstouse,onecaneitherspecifyalltheCiphers,oneatatime,orusealiasestospecifythepreferenceandorderfortheciphers(seeTable1).

Tag DescriptionKeyExchangeAlgorithm:kRSA RSAkeyexchangekDHr Diffie-HellmankeyexchangewithRSAkeykDHd Diffie-HellmankeyexchangewithDSAkeykEDH Ephemeral(temp.key)Diffie-Hellmankeyexchange

(nocert)AuthenticationAlgorithm:aNULL NoauthenticationaRSA RSAauthenticationaDSS DSSauthenticationaDH Diffie-HellmanauthenticationCipherEncodingAlgorithm:eNULL NoencodingDES DESencoding3DES Triple-DESencodingRC4 RC4encodingRC2 RC2encodingIDEA IDEAencodingMACDigestAlgorithm:MD5 MD5hashfunctionSHA1 SHA1hashfunctionSHA SHAhashfunctionAliases:SSLv2 allSSLversion2.0ciphersSSLv3 allSSLversion3.0ciphers

TLSv1 allTLSversion1.0ciphersEXP allexportciphersEXPORT40 all40-bitexportciphersonlyEXPORT56 all56-bitexportciphersonlyLOW alllowstrengthciphers(noexport,singleDES)MEDIUM allcipherswith128bitencryptionHIGH allciphersusingTriple-DESRSA allciphersusingRSAkeyexchangeDH allciphersusingDiffie-HellmankeyexchangeEDH allciphersusingEphemeralDiffie-Hellmankey

exchangeADH allciphersusingAnonymousDiffie-Hellmankey

exchangeDSS allciphersusingDSSauthenticationNULL allciphersusingnoencryption

Nowwherethisbecomesinterestingisthatthesecanbeputtogethertospecifytheorderandciphersyouwishtouse.Tospeedthisuptherearealsoaliases(SSLv2,SSLv3,TLSv1,EXP,LOW,MEDIUM,HIGH)forcertaingroupsofciphers.Thesetagscanbejoinedtogetherwithprefixestoformthecipher-spec.Availableprefixesare:

none:addciphertolist+:movematchingcipherstothecurrentlocationinlist-:removecipherfromlist(canbeaddedlateragain)!:killcipherfromlistcompletely(cannotbeaddedlateragain)

Asimplerwaytolookatallofthisistousethe``opensslciphers-v''commandwhichprovidesanicewaytosuccessivelycreatethecorrectcipher-specstring.Thedefault

cipher-specstringis``ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP''whichmeansthefollowing:first,removefromconsiderationanyciphersthatdonotauthenticate,i.e.forSSLonlytheAnonymousDiffie-Hellmanciphers.Next,useciphersusingRC4andRSA.Nextincludethehigh,mediumandthenthelowsecurityciphers.FinallypullallSSLv2andexportcipherstotheendofthelist.

$opensslciphers-v'ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP'

NULL-SHASSLv3Kx=RSAAu=RSAEnc=NoneMac=SHA1

NULL-MD5SSLv3Kx=RSAAu=RSAEnc=NoneMac=MD5

EDH-RSA-DES-CBC3-SHASSLv3Kx=DHAu=RSAEnc=3DES(168)Mac=SHA1

...............

EXP-RC4-MD5SSLv3Kx=RSA(512)Au=RSAEnc=RC4(40)Mac=MD5export

EXP-RC2-CBC-MD5SSLv2Kx=RSA(512)Au=RSAEnc=RC2(40)Mac=MD5export

EXP-RC4-MD5SSLv2Kx=RSA(512)Au=RSAEnc=RC4(40)Mac=MD5export

ThecompletelistofparticularRSA&DHciphersforSSLisgiveninTable2.

ExampleSSLCipherSuiteRSA:!EXP:!NULL:+HIGH:+MEDIUM:-LOW

Cipher-Tag

Protocol KeyEx. Auth. Enc. MAC Type

RSACiphers:DES-

CBC3-SHA

SSLv3 RSA RSA 3DES(168) SHA1

DES-

CBC3-MD5

SSLv2 RSA RSA 3DES(168) MD5

IDEA-

CBC-SHA

SSLv3 RSA RSA IDEA(128) SHA1

RC4-SHA SSLv3 RSA RSA RC4(128) SHA1

RC4-MD5 SSLv3 RSA RSA RC4(128) MD5

IDEA-

CBC-MD5

SSLv2 RSA RSA IDEA(128) MD5

RC2-CBC-

MD5

SSLv2 RSA RSA RC2(128) MD5

RC4-MD5 SSLv2 RSA RSA RC4(128) MD5DES-CBC-

SHA

SSLv3 RSA RSA DES(56) SHA1

RC4-64-

MD5

SSLv2 RSA RSA RC4(64) MD5

DES-CBC-

MD5

SSLv2 RSA RSA DES(56) MD5

EXP-DES-

CBC-SHA

SSLv3 RSA(512) RSA DES(40) SHA1 export

EXP-RC2-

CBC-MD5

SSLv3 RSA(512) RSA RC2(40) MD5 export

EXP-RC4-

MD5

SSLv3 RSA(512) RSA RC4(40) MD5 export

EXP-RC2-

CBC-MD5

SSLv2 RSA(512) RSA RC2(40) MD5 export

EXP-RC4-

MD5

SSLv2 RSA(512) RSA RC4(40) MD5 export

NULL-SHA SSLv3 RSA RSA None SHA1NULL-MD5 SSLv3 RSA RSA None MD5Diffie-HellmanCiphers:ADH-DES-

CBC3-SHA

SSLv3 DH None 3DES(168) SHA1

ADH-DES-

CBC-SHA

SSLv3 DH None DES(56) SHA1

ADH-RC4-

MD5

SSLv3 DH None RC4(128) MD5

EDH-RSA-

DES-

CBC3-SHA

SSLv3 DH RSA 3DES(168) SHA1

EDH-DSS-

DES-

CBC3-SHA

SSLv3 DH DSS 3DES(168) SHA1

EDH-RSA-

DES-CBC-

SHA

SSLv3 DH RSA DES(56) SHA1

EDH-DSS-

DES-CBC-

SHA

SSLv3 DH DSS DES(56) SHA1

EXP-EDH-

RSA-DES-

CBC-SHA

SSLv3 DH(512) RSA DES(40) SHA1 export

EXP-EDH-

DSS-DES-

CBC-SHA

SSLv3 DH(512) DSS DES(40) SHA1 export

EXP-ADH-

DES-CBC-

SHA

SSLv3 DH(512) None DES(40) SHA1 export

EXP-ADH-

RC4-MD5

SSLv3 DH(512) None RC4(40) MD5 export

SSLEngineDirective

Description: SSLEngineOperationSwitchSyntax: SSLEngineon|off

Default: SSLEngineoff

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

ThisdirectivetogglestheusageoftheSSL/TLSProtocolEngine.Thisisusuallyusedinsidea<VirtualHost>sectiontoenableSSL/TLSforaparticularvirtualhost.BydefaulttheSSL/TLSProtocolEngineisdisabledforboththemainserverandallconfiguredvirtualhosts.

Example<VirtualHost_default_:443>

SSLEngineon

...

</VirtualHost>

SSLHonorCipherOrderDirective

Description: Optiontoprefertheserver'scipherpreferenceorder

Syntax: SSLHonorCipherOrderflag

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_sslCompatibility: AvailableinApache2.0.65andlater,ifusing

OpenSSL0.9.7orlater

WhenchoosingacipherduringanSSLv3orTLSv1handshake,normallytheclient'spreferenceisused.Ifthisdirectiveisenabled,theserver'spreferencewillbeusedinstead.

ExampleSSLHonorCipherOrderon

SSLInsecureRenegotiationDirective

Description: Optiontoenablesupportforinsecurerenegotiation

Syntax: SSLInsecureRenegotiationflag

Default: SSLInsecureRenegotiationoff

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_sslCompatibility: Availableinhttpd2.0.64andlater,ifusing

OpenSSL0.9.8morlater

Asoriginallyspecified,allversionsoftheSSLandTLSprotocols(uptoandincludingTLS/1.2)werevulnerabletoaMan-in-the-Middleattack(CVE-2009-3555)duringarenegotiation.Thisvulnerabilityallowedanattackerto"prefix"achosenplaintexttotheHTTPrequestasseenbythewebserver.Aprotocolextensionwasdevelopedwhichfixedthisvulnerabilityifsupportedbybothclientandserver.

Ifmod_sslislinkedagainstOpenSSLversion0.9.8morlater,bydefaultrenegotiationisonlysupportedwithclientssupportingthenewprotocolextension.Ifthisdirectiveisenabled,renegotiationwillbeallowedwithold(unpatched)clients,albeitinsecurely.

Securitywarning

Ifthisdirectiveisenabled,SSLconnectionswillbevulnerabletotheMan-in-the-MiddleprefixattackasdescribedinCVE-2009-3555.

ExampleSSLInsecureRenegotiationon

TheSSL_SECURE_RENEGenvironmentvariablecanbeusedfromanSSIorCGIscripttodeterminewhethersecurerenegotiationissupportedforagivenSSLconnection.

SSLMutexDirective

Description: Semaphoreforinternalmutualexclusionofoperations

Syntax: SSLMutextype

Default: SSLMutexnone

Context: serverconfigStatus: ExtensionModule: mod_ssl

ThisconfigurestheSSLengine'ssemaphore(aka.lock)whichisusedformutualexclusionofoperationswhichhavetobedoneinasynchronizedwaybetweenthepre-forkedApacheserverprocesses.Thisdirectivecanonlybeusedintheglobalservercontextbecauseit'sonlyusefultohaveoneglobalmutex.ThisdirectiveisdesignedtocloselymatchtheAcceptMutexdirective

ThefollowingMutextypesareavailable:

none|no

ThisisthedefaultwherenoMutexisusedatall.Useitatyourownrisk.ButbecausecurrentlytheMutexismainlyusedforsynchronizingwriteaccesstotheSSLSessionCacheyoucanlivewithoutitaslongasyouacceptasometimesgarbledSessionCache.Soit'snotrecommendedtoleavethisthedefault.InsteadconfigurearealMutex.

posixsem

ThisisanelegantMutexvariantwhereaPosixSemaphoreisusedwhenpossible.ItisonlyavailablewhentheunderlyingplatformandAPRsupportsit.

sysvsem

ThisisasomewhatelegantMutexvariantwhereaSystemVIPCSemaphoreisusedwhenpossible.Itispossibleto"leak"

SysVsemaphoresifprocessescrashbeforethesemaphoreisremoved.ItisonlyavailablewhentheunderlyingplatformandAPRsupportsit.

sem

ThisdirectivetellstheSSLModuletopickthe"best"semaphoreimplementationavailabletoit,choosingbetweenPosixandSystemVIPC,inthatorder.ItisonlyavailablewhentheunderlyingplatformandAPRsupportsatleastoneofthe2.

pthread

ThisdirectivetellstheSSLModuletousePosixthreadmutexes.ItisonlyavailableiftheunderlyingplatformandAPRsupportsit.

fcntl:/path/to/mutex

ThisisaportableMutexvariantwhereaphysical(lock-)fileandthefcntl()fucntionareusedastheMutex.Alwaysusealocaldiskfilesystemfor/path/to/mutexandneverafileresidingonaNFS-orAFS-filesystem.ItisonlyavailablewhentheunderlyingplatformandAPRsupportsit.Note:Internally,theProcessID(PID)oftheApacheparentprocessisautomaticallyappendedto/path/to/mutextomakeitunique,soyoudon'thavetoworryaboutconflictsyourself.NoticethatthistypeofmutexisnotavailableundertheWin32environment.Thereyouhavetousethesemaphoremutex.

flock:/path/to/mutex

Thisissimilartothefcntl:/path/to/mutexmethodwiththeexceptionthattheflock()functionisusedtoprovidefilelocking.ItisonlyavailablewhentheunderlyingplatformandAPRsupportsit.

file:/path/to/mutex

ThisdirectivetellstheSSLModuletopickthe"best"filelockingimplementationavailabletoit,choosingbetweenfcntlandflock,inthatorder.ItisonlyavailablewhentheunderlyingplatformandAPRsupportsatleastoneofthe2.

default|yes

ThisdirectivetellstheSSLModuletopickthedefaultlockingimplementationasdeterminedbytheplatformandAPR.

ExampleSSLMutexfile:/usr/local/apache/logs/ssl_mutex

SSLOptionsDirective

Description: ConfigurevariousSSLenginerun-timeoptionsSyntax: SSLOptions[+|-]option...

Context: serverconfig,virtualhost,directory,.htaccessOverride: OptionsStatus: ExtensionModule: mod_ssl

Thisdirectivecanbeusedtocontrolvariousrun-timeoptionsonaper-directorybasis.Normally,ifmultipleSSLOptionscouldapplytoadirectory,thenthemostspecificoneistakencompletely;theoptionsarenotmerged.HoweverifalltheoptionsontheSSLOptionsdirectiveareprecededbyaplus(+)orminus(-)symbol,theoptionsaremerged.Anyoptionsprecededbya+areaddedtotheoptionscurrentlyinforce,andanyoptionsprecededbya-areremovedfromtheoptionscurrentlyinforce.

Theavailableoptionsare:

StdEnvVars

Whenthisoptionisenabled,thestandardsetofSSLrelatedCGI/SSIenvironmentvariablesarecreated.Thisperdefaultisdisabledforperformancereasons,becausetheinformationextractionstepisaratherexpensiveoperation.SooneusuallyenablesthisoptionforCGIandSSIrequestsonly.

CompatEnvVars

Whenthisoptionisenabled,additionalCGI/SSIenvironmentvariablesarecreatedforbackwardcompatibilitytootherApacheSSLsolutions.LookintheCompatibilitychapterfordetailsontheparticularvariablesgenerated.

ExportCertData

Whenthisoptionisenabled,additionalCGI/SSIenvironment

variablesarecreated:SSL_SERVER_CERT,SSL_CLIENT_CERTandSSL_CLIENT_CERT_CHAINn(withn=0,1,2,..).ThesecontainthePEM-encodedX.509CertificatesofserverandclientforthecurrentHTTPSconnectionandcanbeusedbyCGIscriptsfordeeperCertificatechecking.Additionallyallothercertificatesoftheclientcertificatechainareprovided,too.Thisbloatsuptheenvironmentalittlebitwhichiswhyyouhavetousethisoptiontoenableitondemand.

FakeBasicAuth

Whenthisoptionisenabled,theSubjectDistinguishedName(DN)oftheClientX509CertificateistranslatedintoaHTTPBasicAuthorizationusername.ThismeansthatthestandardApacheauthenticationmethodscanbeusedforaccesscontrol.TheusernameisjusttheSubjectoftheClient'sX509Certificate(canbedeterminedbyrunningOpenSSL'sopensslx509command:opensslx509-noout-subject-incertificate.crt).Notethatnopasswordisobtainedfromtheuser.Everyentryintheuserfileneedsthispassword:``xxj31ZMTZzkVA'',whichistheDES-encryptedversionoftheword`password''.ThosewholiveunderMD5-basedencryption(forinstanceunderFreeBSDorBSD/OS,etc.)shouldusethefollowingMD5hashofthesameword:``$1$OXLyS...$Owx8s2/m9/gfkcRVXzgoE/''.

StrictRequire

ThisforcesforbiddenaccesswhenSSLRequireSSLorSSLRequiresuccessfullydecidedthataccessshouldbeforbidden.Usuallythedefaultisthatinthecasewherea``Satisfyany''directiveisused,andotheraccessrestrictionsarepassed,denialofaccessduetoSSLRequireSSLorSSLRequireisoverridden(becausethat'showtheApacheSatisfymechanismshouldwork.)

ButforstrictaccessrestrictionyoucanuseSSLRequireSSLand/orSSLRequireincombinationwithan``SSLOptions+StrictRequire''.Thenanadditional``SatisfyAny''hasnochanceoncemod_sslhasdecidedtodenyaccess.

OptRenegotiate

ThisenablesoptimizedSSLconnectionrenegotiationhandlingwhenSSLdirectivesareusedinper-directorycontext.Bydefaultastrictschemeisenabledwhereeveryper-directoryreconfigurationofSSLparameterscausesafullSSLrenegotiationhandshake.Whenthisoptionisusedmod_ssltriestoavoidunnecessaryhandshakesbydoingmoregranular(butstillsafe)parameterchecks.Neverthelessthesegranularcheckssometimesmaybenotwhattheuserexpects,soenablethisonaper-directorybasisonly,please.

ExampleSSLOptions+FakeBasicAuth-StrictRequire

<Files~"\.(cgi|shtml)$">

SSLOptions+StdEnvVars+CompatEnvVars-ExportCertData

<Files>

SSLPassPhraseDialogDirective

Description: Typeofpassphrasedialogforencryptedprivatekeys

Syntax: SSLPassPhraseDialogtype

Default: SSLPassPhraseDialogbuiltin

Context: serverconfigStatus: ExtensionModule: mod_ssl

WhenApachestartsupithastoreadthevariousCertificate(seeSSLCertificateFile)andPrivateKey(seeSSLCertificateKeyFile)filesoftheSSL-enabledvirtualservers.BecauseforsecurityreasonsthePrivateKeyfilesareusuallyencrypted,mod_sslneedstoquerytheadministratorforaPassPhraseinordertodecryptthosefiles.Thisquerycanbedoneintwowayswhichcanbeconfiguredbytype:

builtin

ThisisthedefaultwhereaninteractiveterminaldialogoccursatstartuptimejustbeforeApachedetachesfromtheterminal.HeretheadministratorhastomanuallyenterthePassPhraseforeachencryptedPrivateKeyfile.BecausealotofSSL-enabledvirtualhostscanbeconfigured,thefollowingreuse-schemeisusedtominimizethedialog:WhenaPrivateKeyfileisencrypted,allknownPassPhrases(atthebeginningtherearenone,ofcourse)aretried.IfoneofthoseknownPassPhrasessucceedsnodialogpopsupforthisparticularPrivateKeyfile.Ifnonesucceeded,anotherPassPhraseisqueriedontheterminalandrememberedforthenextround(whereitperhapscanbereused).

Thisschemeallowsmod_ssltobemaximallyflexible(becauseforNencryptedPrivateKeyfilesyoucanuseNdifferentPassPhrases-butthenyouhavetoenterallof

them,ofcourse)whileminimizingtheterminaldialog(i.e.whenyouuseasinglePassPhraseforallNPrivateKeyfilesthisPassPhraseisqueriedonlyonce).

exec:/path/to/program

HereanexternalprogramisconfiguredwhichiscalledatstartupforeachencryptedPrivateKeyfile.Itiscalledwithtwoarguments(thefirstisoftheform``servername:portnumber'',thesecondiseither``RSA''or``DSA''),whichindicateforwhichserverandalgorithmithastoprintthecorrespondingPassPhrasetostdout.Theintentisthatthisexternalprogramfirstrunssecuritycheckstomakesurethatthesystemisnotcompromisedbyanattacker,andonlywhenthesecheckswerepassedsuccessfullyitprovidesthePassPhrase.

Boththesesecuritychecks,andthewaythePassPhraseisdetermined,canbeascomplexasyoulike.Mod_ssljustdefinestheinterface:anexecutableprogramwhichprovidesthePassPhraseonstdout.Nothingmoreorless!So,ifyou'rereallyparanoidaboutsecurity,hereisyourinterface.Anythingelsehastobeleftasanexercisetotheadministrator,becauselocalsecurityrequirementsaresodifferent.

Thereuse-algorithmaboveisusedhere,too.Inotherwords:TheexternalprogramiscalledonlyonceperuniquePassPhrase.

Example:

SSLPassPhraseDialogexec:/usr/local/apache/sbin/pp-filter

SSLProtocolDirective

Description: ConfigureusableSSLprotocolflavorsSyntax: SSLProtocol[+|-]protocol...

Default: SSLProtocolall

Context: serverconfig,virtualhostOverride: OptionsStatus: ExtensionModule: mod_ssl

ThisdirectivecanbeusedtocontroltheSSLprotocolflavorsmod_sslshouldusewhenestablishingitsserverenvironment.Clientsthencanonlyconnectwithoneoftheprovidedprotocols.

Theavailable(case-insensitive)protocolsare:

SSLv2

ThisistheSecureSocketsLayer(SSL)protocol,version2.0.ItistheoriginalSSLprotocolasdesignedbyNetscapeCorporation.

SSLv3

ThisistheSecureSocketsLayer(SSL)protocol,version3.0.ItisthesuccessortoSSLv2andthecurrently(asofFebruary1999)de-factostandardizedSSLprotocolfromNetscapeCorporation.It'ssupportedbyalmostallpopularbrowsers.

TLSv1

ThisistheTransportLayerSecurity(TLS)protocol,version1.0.ItisthesuccessortoSSLv3andcurrently(asofFebruary1999)stillunderconstructionbytheInternetEngineeringTaskForce(IETF).It'sstillnotsupportedbyanypopularbrowsers.

All

Thisisashortcutfor``+SSLv2+SSLv3+TLSv1''anda

convinientwayforenablingallprotocolsexceptonewhenusedincombinationwiththeminussignonaprotocolastheexampleaboveshows.

Example#enableSSLv3andTLSv1,butnotSSLv2

SSLProtocolall-SSLv2

SSLProxyCACertificateFileDirective

Description: FileofconcatenatedPEM-encodedCACertificatesforRemoteServerAuth

Syntax: SSLProxyCACertificateFilefile-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoucanassembletheCertificatesofCertificationAuthorities(CA)whoseremoteserversyoudealwith.TheseareusedforRemoteServerAuthentication.SuchafileissimplytheconcatenationofthevariousPEM-encodedCertificatefiles,inorderofpreference.Thiscanbeusedalternativelyand/oradditionallytoSSLProxyCACertificatePath.

ExampleSSLProxyCACertificateFile/usr/local/apache2/conf/ssl.crt/ca-

bundle-remote-server.crt

SSLProxyCACertificatePathDirective

Description: DirectoryofPEM-encodedCACertificatesforRemoteServerAuth

Syntax: SSLProxyCACertificatePathdirectory-

path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

ThisdirectivesetsthedirectorywhereyoukeeptheCertificatesofCertificationAuthorities(CAs)whoseremoteserversyoudealwith.TheseareusedtoverifytheremoteservercertificateonRemoteServerAuthentication.

ThefilesinthisdirectoryhavetobePEM-encodedandareaccessedthroughhashfilenames.Sousuallyyoucan'tjustplacetheCertificatefilesthere:youalsohavetocreatesymboliclinksnamedhash-value.N.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.UsetheMakefilewhichcomeswithmod_ssltoaccomplishthistask.

ExampleSSLProxyCACertificatePath/usr/local/apache2/conf/ssl.crt/

SSLProxyCARevocationFileDirective

Description: FileofconcatenatedPEM-encodedCACRLsforRemoteServerAuth

Syntax: SSLProxyCARevocationFilefile-path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoucanassembletheCertificateRevocationLists(CRL)ofCertificationAuthorities(CA)whoseremoteserversyoudealwith.TheseareusedforRemoteServerAuthentication.SuchafileissimplytheconcatenationofthevariousPEM-encodedCRLfiles,inorderofpreference.Thiscanbeusedalternativelyand/oradditionallytoSSLProxyCARevocationPath.

ExampleSSLProxyCARevocationFile/usr/local/apache2/conf/ssl.crl/ca-

bundle-remote-server.crl

SSLProxyCARevocationPathDirective

Description: DirectoryofPEM-encodedCACRLsforRemoteServerAuth

Syntax: SSLProxyCARevocationPathdirectory-

path

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

ThisdirectivesetsthedirectorywhereyoukeeptheCertificateRevocationLists(CRL)ofCertificationAuthorities(CAs)whoseremoteserversyoudealwith.TheseareusedtorevoketheremoteservercertificateonRemoteServerAuthentication.

ThefilesinthisdirectoryhavetobePEM-encodedandareaccessedthroughhashfilenames.SousuallyyouhavenotonlytoplacetheCRLfilesthere.Additionallyyouhavetocreatesymboliclinksnamedhash-value.rN.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.UsetheMakefilewhichcomeswithmod_ssltoaccomplishthistask.

ExampleSSLProxyCARevocationPath/usr/local/apache2/conf/ssl.crl/

SSLProxyCipherSuiteDirective

Description: CipherSuiteavailablefornegotiationinSSLproxyhandshakeSyntax: SSLProxyCipherSuitecipher-spec

Default: SSLProxyCipherSuite

ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP

Context: serverconfig,virtualhost,directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_ssl

EquivalenttoSSLCipherSuite,butfortheproxyconnection.PleaserefertoSSLCipherSuiteforadditionalinformation.

SSLProxyEngineDirective

Description: SSLProxyEngineOperationSwitchSyntax: SSLProxyEngineon|off

Default: SSLProxyEngineoff

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

ThisdirectivetogglestheusageoftheSSL/TLSProtocolEngineforproxy.Thisisusuallyusedinsidea<VirtualHost>sectiontoenableSSL/TLSforproxyusageinaparticularvirtualhost.BydefaulttheSSL/TLSProtocolEngineisdisabledforproxyimagebothforthemainserverandallconfiguredvirtualhosts.

Example<VirtualHost_default_:443>

SSLProxyEngineon

...

</VirtualHost>

SSLProxyMachineCertificateFileDirective

Description: FileofconcatenatedPEM-encodedclientcertificatesandkeystobeusedbytheproxy

Syntax: SSLProxyMachineCertificateFile

filename

Context: serverconfigOverride: NotapplicableStatus: ExtensionModule: mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoukeepthecertificatesandkeysusedforauthenticationoftheproxyservertoremoteservers.

ThisreferencedfileissimplytheconcatenationofthevariousPEM-encodedcertificatefiles,inorderofpreference.UsethisdirectivealternativelyoradditionallytoSSLProxyMachineCertificatePath.

Currentlythereisnosupportforencryptedprivatekeys

Example:

SSLProxyMachineCertificateFile

/usr/local/apache2/conf/ssl.crt/proxy.pem

SSLProxyMachineCertificatePathDirective

Description: DirectoryofPEM-encodedclientcertificatesandkeystobeusedbytheproxy

Syntax: SSLProxyMachineCertificatePath

directory

Context: serverconfigOverride: NotapplicableStatus: ExtensionModule: mod_ssl

Thisdirectivesetsthedirectorywhereyoukeepthecertificatesandkeysusedforauthenticationoftheproxyservertoremoteservers.

ThefilesinthisdirectorymustbePEM-encodedandareaccessedthroughhashfilenames.Additionally,youmustcreatesymboliclinksnamedhash-value.N.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.UsetheMakefilewhichcomeswithmod_ssltoaccomplishthistask.

Currentlythereisnosupportforencryptedprivatekeys

Example:

SSLProxyMachineCertificatePath

/usr/local/apache2/conf/proxy.crt/

SSLProxyProtocolDirective

Description: ConfigureusableSSLprotocolflavorsforproxyusage

Syntax: SSLProxyProtocol[+|-]protocol...

Default: SSLProxyProtocolall

Context: serverconfig,virtualhostOverride: OptionsStatus: ExtensionModule: mod_ssl

ThisdirectivecanbeusedtocontroltheSSLprotocolflavorsmod_sslshouldusewhenestablishingitsserverenvironmentforproxy.Itwillonlyconnecttoserversusingoneoftheprovidedprotocols.

PleaserefertoSSLProtocolforadditionalinformation.

SSLProxyVerifyDirective

Description: TypeofremoteserverCertificateverificationSyntax: SSLProxyVerifylevel

Default: SSLProxyVerifynone

Context: serverconfig,virtualhost,directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_ssl

ThisdirectivesetstheCertificateverificationlevelfortheremoteserverAuthentication.Noticethatthisdirectivecanbeusedbothinper-serverandper-directorycontext.Inper-servercontextitappliestotheremoteserverauthenticationprocessusedinthestandardSSLhandshakewhenaconnectionisestablished.Inper-directorycontextitforcesaSSLrenegotationwiththereconfiguredremoteserververificationlevelaftertheHTTPrequestwasreadbutbeforetheHTTPresponseissent.

Thefollowinglevelsareavailableforlevel:

none:noremoteserverCertificateisrequiredatalloptional:theremoteservermaypresentavalidCertificaterequire:theremoteserverhastopresentavalidCertificateoptional_no_ca:theremoteservermaypresentavalidCertificatebutitneednottobe(successfully)verifiable.

Inpracticeonlylevelsnoneandrequirearereallyinteresting,becauseleveloptionaldoesn'tworkwithallserversandleveloptional_no_caisactuallyagainsttheideaofauthentication(butcanbeusedtoestablishSSLtestpages,etc.)

ExampleSSLProxyVerifyrequire

SSLProxyVerifyDepthDirective

Description: MaximumdepthofCACertificatesinRemoteServerCertificateverification

Syntax: SSLProxyVerifyDepthnumber

Default: SSLProxyVerifyDepth1

Context: serverconfig,virtualhost,directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_ssl

Thisdirectivesetshowdeeplymod_sslshouldverifybeforedecidingthattheremoteserverdoesnothaveavalidcertificate.Noticethatthisdirectivecanbeusedbothinper-serverandper-directorycontext.Inper-servercontextitappliestotheclientauthenticationprocessusedinthestandardSSLhandshakewhenaconnectionisestablished.Inper-directorycontextitforcesaSSLrenegotationwiththereconfiguredremoteserververificationdepthaftertheHTTPrequestwasreadbutbeforetheHTTPresponseissent.

Thedepthactuallyisthemaximumnumberofintermediatecertificateissuers,i.e.thenumberofCAcertificateswhicharemaxallowedtobefollowedwhileverifyingtheremoteservercertificate.Adepthof0meansthatself-signedremoteservercertificatesareacceptedonly,thedefaultdepthof1meanstheremoteservercertificatecanbeself-signedorhastobesignedbyaCAwhichisdirectlyknowntotheserver(i.e.theCA'scertificateisunderSSLProxyCACertificatePath),etc.

ExampleSSLProxyVerifyDepth10

SSLRandomSeedDirective

Description: PseudoRandomNumberGenerator(PRNG)seedingsource

Syntax: SSLRandomSeedcontextsource[bytes]

Context: serverconfigStatus: ExtensionModule: mod_ssl

ThisconfiguresoneormoresourcesforseedingthePseudoRandomNumberGenerator(PRNG)inOpenSSLatstartuptime(contextisstartup)and/orjustbeforeanewSSLconnectionisestablished(contextisconnect).ThisdirectivecanonlybeusedintheglobalservercontextbecausethePRNGisaglobalfacility.

Thefollowingsourcevariantsareavailable:

builtin

Thisisthealwaysavailablebuiltinseedingsource.It'susageconsumesminimumCPUcyclesunderruntimeandhencecanbealwaysusedwithoutdrawbacks.ThesourceusedforseedingthePRNGcontainsofthecurrenttime,thecurrentprocessidand(whenapplicable)arandomlychoosen1KBextractoftheinter-processscoreboardstructureofApache.Thedrawbackisthatthisisnotreallyastrongsourceandatstartuptime(wherethescoreboardisstillnotavailable)thissourcejustproducesafewbytesofentropy.Soyoushouldalways,atleastforthestartup,useanadditionalseedingsource.

file:/path/to/source

Thisvariantusesanexternalfile/path/to/sourceasthesourceforseedingthePRNG.Whenbytesisspecified,onlythefirstbytesnumberofbytesofthefileformtheentropy(andbytesisgivento/path/to/sourceasthefirst

argument).Whenbytesisnotspecifiedthewholefileformstheentropy(and0isgivento/path/to/sourceasthefirstargument).Usethisespeciallyatstartuptime,forinstancewithanavailable/dev/randomand/or/dev/urandomdevices(whichusuallyexistonmodernUnixderivateslikeFreeBSDandLinux).

Butbecareful:Usually/dev/randomprovidesonlyasmuchentropydataasitactuallyhas,i.e.whenyourequest512bytesofentropy,butthedevicecurrentlyhasonly100bytesavailabletwothingscanhappen:Onsomeplatformsyoureceiveonlythe100byteswhileonotherplatformsthereadblocksuntilenoughbytesareavailable(whichcantakealongtime).Hereusinganexisting/dev/urandomisbetter,becauseitneverblocksandactuallygivestheamountofrequesteddata.Thedrawbackisjustthatthequalityofthereceiveddatamaynotbethebest.

OnsomeplatformslikeFreeBSDonecanevencontrolhowtheentropyisactuallygenerated,i.e.bywhichsysteminterrupts.Moredetailsonecanfindunderrndcontrol(8)onthoseplatforms.Alternatively,whenyoursystemlackssucharandomdevice,youcanusetoollikeEGD(EntropyGatheringDaemon)andrunit'sclientprogramwiththeexec:/path/to/program/variant(seebelow)oruseegd:/path/to/egd-socket(seebelow).

exec:/path/to/program

Thisvariantusesanexternalexecutable/path/to/programasthesourceforseedingthePRNG.Whenbytesisspecified,onlythefirstbytesnumberofbytesofitsstdoutcontentsformtheentropy.Whenbytesisnotspecified,theentiretyofthedataproducedonstdoutformtheentropy.Usethisonlyatstartuptimewhenyouneeda

verystrongseedingwiththehelpofanexternalprogram(forinstanceasintheexampleabovewiththetruerandutilityyoucanfindinthemod_ssldistributionwhichisbasedontheAT&Ttruerandlibrary).Usingthisintheconnectioncontextslowsdowntheservertoodramatically,ofcourse.Sousuallyyoushouldavoidusingexternalprogramsinthatcontext.

egd:/path/to/egd-socket(Unixonly)ThisvariantusestheUnixdomainsocketoftheexternalEntropyGatheringDaemon(EGD)(seehttp://www.lothar.com/tech/crypto/)toseedthePRNG.Usethisifnorandomdeviceexistsonyourplatform.

ExampleSSLRandomSeedstartupbuiltin

SSLRandomSeedstartupfile:/dev/random

SSLRandomSeedstartupfile:/dev/urandom1024

SSLRandomSeedstartupexec:/usr/local/bin/truerand16

SSLRandomSeedconnectbuiltin

SSLRandomSeedconnectfile:/dev/random

SSLRandomSeedconnectfile:/dev/urandom1024

SSLRequireDirective

Description: Allowaccessonlywhenanarbitrarilycomplexbooleanexpressionistrue

Syntax: SSLRequireexpression

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_ssl

Thisdirectivespecifiesageneralaccessrequirementwhichhastobefulfilledinordertoallowaccess.It'saverypowerfuldirectivebecausetherequirementspecificationisanarbitrarilycomplexbooleanexpressioncontaininganynumberofaccesschecks.

Theexpressionmustmatchthefollowingsyntax(givenasaBNFgrammarnotation):

expr::="true"|"false"

|"!"expr

|expr"&&"expr

|expr"||"expr

|"("expr")"

|comp

comp::=word"=="word|word"eq"word

|word"!="word|word"ne"word

|word"<"word|word"lt"word

|word"<="word|word"le"word

|word">"word|word"gt"word

|word">="word|word"ge"word

|word"in""{"wordlist"}"

|word"=~"regex

|word"!~"regex

wordlist::=word

|wordlist","word

word::=digit

|cstring

|variable

|function

digit::=[0-9]+

cstring::="..."

variable::="%{"varname"}"

function::=funcname"("funcargs")"

whileforvarnameanyvariablefromTable3canbeused.Finallyforfuncnamethefollowingfunctionsareavailable:

file(filename)Thisfunctiontakesonestringargumentandexpandstothecontentsofthefile.Thisisespeciallyusefulformatchingthiscontentsagainstaregularexpression,etc.

Noticethatexpressionisfirstparsedintoaninternalmachinerepresentationandthenevaluatedinasecondstep.Actually,inGlobalandPer-ServerClasscontextexpressionisparsedatstartuptimeandatruntimeonlythemachinerepresentationisexecuted.ForPer-Directorycontextthisisdifferent:hereexpressionhastobeparsedandimmediatelyexecutedforeveryrequest.

ExampleSSLRequire(%{SSL_CIPHER}!~m/^(EXP|NULL)-/\

and%{SSL_CLIENT_S_DN_O}eq"SnakeOil,Ltd."\

and%{SSL_CLIENT_S_DN_OU}in{"Staff","CA","Dev"}\

and%{TIME_WDAY}>=1and%{TIME_WDAY}<=5\

and%{TIME_HOUR}>=8and%{TIME_HOUR}<=20)\

or%{REMOTE_ADDR}=~m/^192\.76\.162\.[0-9]+$/

StandardCGI/1.0andApachevariables:

HTTP_USER_AGENTPATH_INFOAUTH_TYPE

HTTP_REFERERQUERY_STRINGSERVER_SOFTWARE

HTTP_COOKIEREMOTE_HOSTAPI_VERSION

HTTP_FORWARDEDREMOTE_IDENTTIME_YEAR

HTTP_HOSTIS_SUBREQTIME_MON

HTTP_PROXY_CONNECTIONDOCUMENT_ROOTTIME_DAY

HTTP_ACCEPTSERVER_ADMINTIME_HOUR

HTTP:headernameSERVER_NAMETIME_MIN

THE_REQUESTSERVER_PORTTIME_SEC

REQUEST_METHODSERVER_PROTOCOLTIME_WDAY

REQUEST_SCHEMEREMOTE_ADDRTIME

REQUEST_URIREMOTE_USERENV:variablename

REQUEST_FILENAME

SSL-relatedvariables:

HTTPSSSL_CLIENT_M_VERSIONSSL_SERVER_M_VERSION

SSL_CLIENT_M_SERIALSSL_SERVER_M_SERIAL

SSL_PROTOCOLSSL_CLIENT_V_STARTSSL_SERVER_V_START

SSL_SESSION_IDSSL_CLIENT_V_ENDSSL_SERVER_V_END

SSL_CIPHERSSL_CLIENT_S_DNSSL_SERVER_S_DN

SSL_CIPHER_EXPORTSSL_CLIENT_S_DN_CSSL_SERVER_S_DN_C

SSL_CIPHER_ALGKEYSIZESSL_CLIENT_S_DN_STSSL_SERVER_S_DN_ST

SSL_CIPHER_USEKEYSIZESSL_CLIENT_S_DN_LSSL_SERVER_S_DN_L

SSL_VERSION_LIBRARYSSL_CLIENT_S_DN_OSSL_SERVER_S_DN_O

SSL_VERSION_INTERFACESSL_CLIENT_S_DN_OUSSL_SERVER_S_DN_OU

SSL_CLIENT_S_DN_CNSSL_SERVER_S_DN_CN

SSL_CLIENT_S_DN_TSSL_SERVER_S_DN_T

SSL_CLIENT_S_DN_ISSL_SERVER_S_DN_I

SSL_CLIENT_S_DN_GSSL_SERVER_S_DN_G

SSL_CLIENT_S_DN_SSSL_SERVER_S_DN_S

SSL_CLIENT_S_DN_DSSL_SERVER_S_DN_D

SSL_CLIENT_S_DN_UIDSSL_SERVER_S_DN_UID

SSL_CLIENT_S_DN_EmailSSL_SERVER_S_DN_Email

SSL_CLIENT_I_DNSSL_SERVER_I_DN

SSL_CLIENT_I_DN_CSSL_SERVER_I_DN_C

SSL_CLIENT_I_DN_STSSL_SERVER_I_DN_ST

SSL_CLIENT_I_DN_LSSL_SERVER_I_DN_L

SSL_CLIENT_I_DN_OSSL_SERVER_I_DN_O

SSL_CLIENT_I_DN_OUSSL_SERVER_I_DN_OU

SSL_CLIENT_I_DN_CNSSL_SERVER_I_DN_CN

SSL_CLIENT_I_DN_TSSL_SERVER_I_DN_T

SSL_CLIENT_I_DN_ISSL_SERVER_I_DN_I

SSL_CLIENT_I_DN_GSSL_SERVER_I_DN_G

SSL_CLIENT_I_DN_SSSL_SERVER_I_DN_S

SSL_CLIENT_I_DN_DSSL_SERVER_I_DN_D

SSL_CLIENT_I_DN_UIDSSL_SERVER_I_DN_UID

SSL_CLIENT_I_DN_EmailSSL_SERVER_I_DN_Email

SSL_CLIENT_A_SIGSSL_SERVER_A_SIG

SSL_CLIENT_A_KEYSSL_SERVER_A_KEY

SSL_CLIENT_CERTSSL_SERVER_CERT

SSL_CLIENT_CERT_CHAINn

SSL_CLIENT_VERIFY

SSLRequireSSLDirective

Description: DenyaccesswhenSSLisnotusedfortheHTTPrequest

Syntax: SSLRequireSSL

Context: directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_ssl

ThisdirectiveforbidsaccessunlessHTTPoverSSL(i.e.HTTPS)isenabledforthecurrentconnection.ThisisveryhandyinsidetheSSL-enabledvirtualhostordirectoriesfordefendingagainstconfigurationerrorsthatexposestuffthatshouldbeprotected.WhenthisdirectiveispresentallrequestsaredeniedwhicharenotusingSSL.

ExampleSSLRequireSSL

SSLSessionCacheDirective

Description: Typeoftheglobal/inter-processSSLSessionCache

Syntax: SSLSessionCachetype

Default: SSLSessionCachenone

Context: serverconfigStatus: ExtensionModule: mod_ssl

Thisconfiguresthestoragetypeoftheglobal/inter-processSSLSessionCache.Thiscacheisanoptionalfacilitywhichspeedsupparallelrequestprocessing.Forrequeststothesameserverprocess(viaHTTPkeep-alive),OpenSSLalreadycachestheSSLsessioninformationlocally.Butbecausemodernclientsrequestinlinedimagesandotherdataviaparallelrequests(usuallyuptofourparallelrequestsarecommon)thoserequestsareservedbydifferentpre-forkedserverprocesses.Hereaninter-processcachehelpstoavoidunneccessarysessionhandshakes.

Thefollowingtwostoragetypesarecurrentlysupported:

none

Thisisthedefaultandjustdisablestheglobal/inter-processSessionCache.Thereisnodrawbackinfunctionality,butanoticeablespeedpenaltycanbeobserved.

dbm:/path/to/datafile

ThismakesuseofaDBMhashfileonthelocaldisktosynchronizethelocalOpenSSLmemorycachesoftheserverprocesses.TheslightincreaseinI/Oontheserverresultsinavisiblerequestspeedupforyourclients,sothistypeofstorageisgenerallyrecommended.

shm:/path/to/datafile[(size)]

Thismakesuseofahigh-performancehashtable(approx.sizebytesinsize)insideasharedmemorysegmentinRAM(establishedvia/path/to/datafile)tosynchronizethelocalOpenSSLmemorycachesoftheserverprocesses.Thisstoragetypeisnotavailableonallplatforms.

ExamplesSSLSessionCachedbm:/usr/local/apache/logs/ssl_gcache_data

SSLSessionCache

shm:/usr/local/apache/logs/ssl_gcache_data(512000)

SSLSessionCacheTimeoutDirective

Description: NumberofsecondsbeforeanSSLsessionexpiresintheSessionCache

Syntax: SSLSessionCacheTimeoutseconds

Default: SSLSessionCacheTimeout300

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_ssl

Thisdirectivesetsthetimeoutinsecondsfortheinformationstoredintheglobal/inter-processSSLSessionCacheandtheOpenSSLinternalmemorycache.Itcanbesetaslowas15fortesting,butshouldbesettohighervalueslike300inreallife.

ExampleSSLSessionCacheTimeout600

SSLUserNameDirective

Description: VariablenametodetermineusernameSyntax: SSLUserNamevarname

Context: serverconfig,directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_sslCompatibility: AvailableinApache2.0.51andlater

Thisdirectivesetsthe"user"fieldintheApacherequestobject.Thisisusedbylowermodulestoidentifytheuserwithacharacterstring.Inparticular,thismaycausetheenvironmentvariableREMOTE_USERtobeset.ThevarnamecanbeanyoftheSSLenvironmentvariables.

ExampleSSLUserNameSSL_CLIENT_S_DN_CN

SSLVerifyClientDirective

Description: TypeofClientCertificateverificationSyntax: SSLVerifyClientlevel

Default: SSLVerifyClientnone

Context: serverconfig,virtualhost,directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_ssl

ThisdirectivesetstheCertificateverificationlevelfortheClientAuthentication.Noticethatthisdirectivecanbeusedbothinper-serverandper-directorycontext.Inper-servercontextitappliestotheclientauthenticationprocessusedinthestandardSSLhandshakewhenaconnectionisestablished.Inper-directorycontextitforcesaSSLrenegotationwiththereconfiguredclientverificationlevelaftertheHTTPrequestwasreadbutbeforetheHTTPresponseissent.

Thefollowinglevelsareavailableforlevel:

none:noclientCertificateisrequiredatalloptional:theclientmaypresentavalidCertificaterequire:theclienthastopresentavalidCertificateoptional_no_ca:theclientmaypresentavalidCertificatebutitneednottobe(successfully)verifiable.

Inpracticeonlylevelsnoneandrequirearereallyinteresting,becauseleveloptionaldoesn'tworkwithallbrowsersandleveloptional_no_caisactuallyagainsttheideaofauthentication(butcanbeusedtoestablishSSLtestpages,etc.)

ExampleSSLVerifyClientrequire

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

SSLVerifyDepthDirective

Description: MaximumdepthofCACertificatesinClientCertificateverification

Syntax: SSLVerifyDepthnumber

Default: SSLVerifyDepth1

Context: serverconfig,virtualhost,directory,.htaccessOverride: AuthConfigStatus: ExtensionModule: mod_ssl

Thisdirectivesetshowdeeplymod_sslshouldverifybeforedecidingthattheclientsdon'thaveavalidcertificate.Noticethatthisdirectivecanbeusedbothinper-serverandper-directorycontext.Inper-servercontextitappliestotheclientauthenticationprocessusedinthestandardSSLhandshakewhenaconnectionisestablished.Inper-directorycontextitforcesaSSLrenegotationwiththereconfiguredclientverificationdepthaftertheHTTPrequestwasreadbutbeforetheHTTPresponseissent.

Thedepthactuallyisthemaximumnumberofintermediatecertificateissuers,i.e.thenumberofCAcertificateswhicharemaxallowedtobefollowedwhileverifyingtheclientcertificate.Adepthof0meansthatself-signedclientcertificatesareacceptedonly,thedefaultdepthof1meanstheclientcertificatecanbeself-signedorhastobesignedbyaCAwhichisdirectlyknowntotheserver(i.e.theCA'scertificateisunderSSLCACertificatePath),etc.

ExampleSSLVerifyDepth10

Modules|Directives|FAQ|Glossary|Sitemap

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_status

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

:: Base: status_module: mod_status.c

Status

:

(:) (*)(*)

11 (*)ApacheCPU(*)(*)

"(*)"

Status

foo.com

<Location/server-status>

SetHandlerserver-status

OrderDeny,Allow

Denyfromall

Allowfrom.foo.com

</Location>

http://your.server.name/server-status

Nstatus?refresh=N

http://your.server.name/server-status?auto Apache /support

mod_status

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

ExtendedStatus

:: ExtendedStatusOn|Off

: ExtendedStatusOff

:: Base: mod_status: ExtendedStatusApache1.3.2

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_suexec

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: CGI: Extension: suexec_module: mod_suexec.c: Apache2.0

suexecCGI

SuEXEC

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

SuexecUserGroup

: CGI: SuexecUserGroupUserGroup

: ,: Extension: mod_suexec: SuexecUserGroup2.0

SuexecUserGroupCGI CGI1.3VirtualHosts UserGroup

SuexecUserGroupnobodynogroup

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_unique_id

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

: : Extension: unique_id_module: mod_unique_id.c

ApacheUnix

(NTP)

NTPIP

pid(ID) 32

httpd

Unix(UTC1970 11)16 (ip_addr,pid,time_stamp,counter)httpd 65536pid

httpd (÷10)modulo655360)

pidpid

rand()seed seed

? 500 1.5%

UTCNTP UTC

UNIQUE_ID112(32IP 32pid,3216 [A-Za-z0-9@-]MIMEbase6419base64 [A-Za-z0-9+/] + /URL

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

:IPpid, UNIQUE_ID

UNIQUE_ID

WindowsNT)httpd ()

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_userdir

:: Base: userdir_module: mod_userdir.c

http://example.com/~user/

URLpublic_html

UserDir

:: UserDirdirectory-filename

: UserDirpublic_html

: ,: Base: mod_userdir

UserDir

disabled enabled() disabled enabled

enabled disabled UserDir http://www.foo.com/~bob/one/two.html:

UserDirUserDirpublic_html ~bob/public_html/one/two.htmlUserDir/usr/web /usr/web/bob/one/two.htmlUserDir/home/*/www /home/bob/www/one/two.html

:

UserDirUserDirhttp://www.foo.com/users

http://www.foo.com/users/bob/one/two.html

UserDirhttp://www.foo.com/*/usr

http://www.foo.com/bob/usr/one/two.html

UserDirhttp://www.foo.com/~*/

http://www.foo.com/~bob/one/two.html

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

; "UserDir./" "/~rootdisabledroot"

:

UserDir:

UserDirdisabled

UserDirenableduser1user2user3

UserDir:

UserDirenabled

UserDirdisableduser4user5user6

:

Userdirpublic_html/usr/webhttp://www.foo.com/

http://www.foo.com/~bob/one/two.html~bob/public_html/one/two.html/usr/web/bob/one/two.htmlhttp://www.foo.com/bob/one/two.html

Apache

public_html

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_usertrack

Description: ClickstreamloggingofuseractivityonasiteStatus: ExtensionModuleIdentifier: usertrack_moduleSourceFile: mod_usertrack.c

SummaryPreviousreleasesofApachehaveincludedamodulewhichgeneratesa'clickstream'logofuseractivityonasiteusingcookies.Thiswascalledthe"cookies"module,mod_cookies.InApache1.2andlaterthismodulehasbeenrenamedthe"usertracking"module,mod_usertrack.Thismodulehasbeensimplifiedandnewdirectivesadded.

Logging

Previously,thecookiesmodule(nowtheusertrackingmodule)diditsownlogging,usingtheCookieLogdirective.Inthisrelease,thismoduledoesnologgingatall.Instead,aconfigurablelogformatfileshouldbeusedtologuserclick-streams.Thisispossiblebecausetheloggingmodulenowallowsmultiplelogfiles.Thecookieitselfisloggedbyusingthetext%{cookie}ninthelogfileformat.Forexample:

CustomLoglogs/clickstream"%{cookie}n%r%t"

ForbackwardcompatibilitytheconfigurablelogmoduleimplementstheoldCookieLogdirective,butthisshouldbeupgradedtotheaboveCustomLogdirective.

2-digitor4-digitdatesforcookies?

(thefollowingisfrommessage<022701bda43d$9d32bbb0$1201a8c0@christian.office.sane.com>inthenew-httpdarchives)

From:"ChristianAllen"<christian@sane.com>

Subject:Re:ApacheY2Kbuginmod_usertrack.c

Date:Tue,30Jun199811:41:56-0400

Didsomeworkwithcookiesanddugupsomeinfothatmightbeuseful.

True,NetscapeclaimsthatthecorrectformatNOWisfourdigitdates,and

fourdigitdatesdoinfactwork...forNetscape4.x(Communicator),that

is.However,3.xandbelowdoNOTacceptthem.ItseemsthatNetscape

originallyhada2-digitstandard,andthenwithalloftheY2Khypeand

probablyafewcomplaints,changedtoafourdigitdateforCommunicator.

Fortunately,4.xalsounderstandsthe2-digitformat,andsothebestwayto

ensurethatyourexpirationdateislegibletotheclient'sbrowseristo

use2-digitdates.

However,thisdoesnotlimitexpirationdatestotheyear2000;ifyouuse

anexpirationyearof"13",forexample,itisinterpretedas2013,NOT

1913!Infact,youcanuseanexpirationyearofupto"37",anditwillbe

understoodas"2037"bybothMSIEandNetscapeversions3.xandup(notsure

aboutversionsprevioustothose).NotsurewhyNetscapeusedthat

particularyearasitscut-offpoint,butmyguessisthatitwasinrespect

toUNIX's2038problem.Netscape/MSIE4.xseemtobeabletounderstand

2-digityearsbeyondthat,atleastuntil"50"forsure(Ithinkthey

understandupuntilabout"70",butnotforsure).

Summary:Mozilla3.xandupunderstandstwodigitdatesupuntil"37"

(2037).Mozilla4.xunderstandsupuntilatleast"50"(2050)in2-digit

form,butalsounderstands4-digityears,whichcanprobablyreachupuntil

9999.Yourbestbetforsendingalong-lifecookieistosenditforsome

timelateintheyear"37".

CookieDomainDirective

Description: ThedomaintowhichthetrackingcookieappliesSyntax: CookieDomaindomain

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_usertrack

Thisdirectivecontrolsthesettingofthedomaintowhichthetrackingcookieapplies.Ifnotpresent,nodomainisincludedinthecookieheaderfield.

Thedomainstringmustbeginwithadot,andmustincludeatleastoneembeddeddot.Thatis,.foo.comislegal,butfoo.bar.comand.comarenot.

Mostbrowsersinusetodaywillnotallowcookiestobesetforatwo-parttopleveldomain,suchas.co.uk,althoughsuchadomainostensiblyfulfillstherequirementsabove.Thesedomainsareequivalenttotopleveldomainssuchas.com,andallowingsuchcookiesmaybeasecurityrisk.Thus,ifyouareunderatwo-parttopleveldomain,youshouldstilluseyouractualdomain,asyouwouldwithanyothertopleveldomain(forexample,use.foo.co.uk).

CookieExpiresDirective

Description: ExpirytimeforthetrackingcookieSyntax: CookieExpiresexpiry-period

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_usertrack

Whenused,thisdirectivesetsanexpirytimeonthecookiegeneratedbytheusertrackmodule.Theexpiry-periodcanbegiveneitherasanumberofseconds,orintheformatsuchas"2weeks3days7hours".Validdenominationsare:years,months,weeks,days,hours,minutesandseconds.Iftheexpirytimeisinanyformatotherthanonenumberindicatingthenumberofseconds,itmustbeenclosedbydoublequotes.

Ifthisdirectiveisnotused,cookieslastonlyforthecurrentbrowsersession.

CookieNameDirective

Description: NameofthetrackingcookieSyntax: CookieNametoken

Default: CookieNameApache

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_usertrack

Thisdirectiveallowsyoutochangethenameofthecookiethismoduleusesforitstrackingpurposes.Bydefaultthecookieisnamed"Apache".

Youmustspecifyavalidcookiename;resultsareunpredictableifyouuseanamecontainingunusualcharacters.ValidcharactersincludeA-Z,a-z,0-9,"_",and"-".

CookieStyleDirective

Description: FormatofthecookieheaderfieldSyntax: CookieStyle

Netscape|Cookie|Cookie2|RFC2109|RFC2965

Default: CookieStyleNetscape

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_usertrack

Thisdirectivecontrolstheformatofthecookieheaderfield.Thethreeformatsallowedare:

Netscape,whichistheoriginalbutnowdeprecatedsyntax.Thisisthedefault,andthesyntaxApachehashistoricallyused.CookieorRFC2109,whichisthesyntaxthatsupersededtheNetscapesyntax.Cookie2orRFC2965,whichisthemostcurrentcookiesyntax.

Notallclientscanunderstandalloftheseformats.butyoushouldusethenewestonethatisgenerallyacceptabletoyourusers'browsers.Atthetimeofwriting,mostbrowsersonlyfullysupportCookieStyleNetscape.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

CookieTrackingDirective

Description: EnablestrackingcookieSyntax: CookieTrackingon|off

Default: CookieTrackingoff

Context: serverconfig,virtualhost,directory,.htaccessOverride: FileInfoStatus: ExtensionModule: mod_usertrack

Whenmod_usertrackisloaded,andCookieTrackingonisset,Apachewillsendauser-trackingcookieforallnewrequests.Thisdirectivecanbeusedtoturnthisbehavioronoroffonaper-serverorper-directorybasis.Bydefault,enablingmod_usertrackwillnotactivatecookies.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Apachemod_version

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

:: Extension: version_module: mod_version.c: 2.0.54

httpd

<IfVersion2.1.0>

#currenthttpdversionisexactly2.1.0

</IfVersion>

<IfVersion>=2.2>

#usereallynewfeatures:-)

</IfVersion>

<IfVersion>

:: <IfVersion[[!]operator]version>...

</IfVersion>

: ,,,.htaccess: All: Extension: mod_version

<IfVersion> httpd major[.minor[.patch]] 2.1.0 2.2patch 0

operator= == httpd

> httpd

>= httpd

< httpd

<= httpd

<IfVersion>=2.1>

#thishappensonlyinversionsgreateror

#equal2.1.0.

</IfVersion>

http :

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

operator=or== version

/regex/~ version regex

<IfVersion=/^2.1.[01234]$/>

#e.g.workaroundforbuggyversions

</IfVersion>

( !):

<IfVersion!~^2.1.[01234]$>

#notforthoseversions

</IfVersion>

operator =

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Modules

ApacheModulemod_vhost_alias

Description: Providesfordynamicallyconfiguredmassvirtualhosting

Status: ExtensionModuleIdentifier: vhost_alias_moduleSourceFile: mod_vhost_alias.c

SummaryThismodulecreatesdynamicallyconfiguredvirtualhosts,byallowingtheIPaddressand/ortheHost:headeroftheHTTPrequesttobeusedaspartofthepathnametodeterminewhatfilestoserve.Thisallowsforeasyuseofahugenumberofvirtualhostswithsimilarconfigurations.

Note

Ifmod_aliasormod_userdirareusedfortranslatingURIstofilenames,theywilloverridethedirectivesofmod_vhost_aliasdescribedbelow.Forexample,thefollowingconfigurationwillmap/cgi-bin/script.plto/usr/local/apache2/cgi-bin/script.plinallcases:

ScriptAlias/cgi-bin//usr/local/apache2/cgi-bin/

VirtualScriptAlias/never/found/%0/cgi-bin/

SeealsoUseCanonicalName

Dynamicallyconfiguredmassvirtualhosting

DirectoryNameInterpolation

Allthedirectivesinthismoduleinterpolateastringintoapathname.Theinterpolatedstring(henceforthcalledthe"name")maybeeithertheservername(seetheUseCanonicalNamedirectivefordetailsonhowthisisdetermined)ortheIPaddressofthevirtualhostontheserverindotted-quadformat.Theinterpolationiscontrolledbyspecifiersinspiredbyprintfwhichhaveanumberofformats:

%% inserta%%p inserttheportnumberofthevirtualhost%N.M insert(partof)thename

NandMareusedtospecifysubstringsofthename.Nselectsfromthedot-separatedcomponentsofthename,andMselectscharacterswithinwhateverNhasselected.Misoptionalanddefaultstozeroifitisn'tpresent;thedotmustbepresentifandonlyifMispresent.Theinterpretationisasfollows:

0 thewholename1 thefirstpart2 thesecondpart-1 thelastpart-2 thepenultimatepart2+ thesecondandallsubsequentparts-2+ thepenultimateandallprecedingparts1+and-1+ thesameas0

IfNorMisgreaterthanthenumberofpartsavailableasingleunderscoreisinterpolated.

Examples

Forsimplename-basedvirtualhostsyoumightusethefollowingdirectivesinyourserverconfigurationfile:

UseCanonicalNameOff

VirtualDocumentRoot/usr/local/apache/vhosts/%0

Arequestforhttp://www.example.com/directory/file.htmlwillbesatisfiedbythefile/usr/local/apache/vhosts/www.example.com/directory/file.html

Foraverylargenumberofvirtualhostsitisagoodideatoarrangethefilestoreducethesizeofthevhostsdirectory.Todothisyoumightusethefollowinginyourconfigurationfile:

UseCanonicalNameOff

VirtualDocumentRoot

/usr/local/apache/vhosts/%3+/%2.1/%2.2/%2.3/%2

Arequestforhttp://www.domain.example.com/directory/file.html

willbesatisfiedbythefile/usr/local/apache/vhosts/example.com/d/o/m/domain/directory/file.html

Amoreevenspreadoffilescanbeachievedbyhashingfromtheendofthename,forexample:

VirtualDocumentRoot

/usr/local/apache/vhosts/%3+/%2.-1/%2.-2/%2.-3/%2

Theexamplerequestwouldcomefrom/usr/local/apache/vhosts/example.com/n/i/a/domain/directory/file.html

Alternativelyyoumightuse:

VirtualDocumentRoot

/usr/local/apache/vhosts/%3+/%2.1/%2.2/%2.3/%2.4+

Theexamplerequestwouldcomefrom/usr/local/apache/vhosts/example.com/d/o/m/ain/directory/file.html

ForIP-basedvirtualhostingyoumightusethefollowinginyourconfigurationfile:

UseCanonicalNameDNS

VirtualDocumentRootIP/usr/local/apache/vhosts/%1/%2/%3/%4/docs

VirtualScriptAliasIP/usr/local/apache/vhosts/%1/%2/%3/%4/cgi-

bin

Arequestforhttp://www.domain.example.com/directory/file.html

wouldbesatisfiedbythefile/usr/local/apache/vhosts/10/20/30/40/docs/directory/file.html

iftheIPaddressofwww.domain.example.comwere10.20.30.40.Arequestforhttp://www.domain.example.com/cgi-bin/script.pl

wouldbesatisfiedbyexecutingtheprogram/usr/local/apache/vhosts/10/20/30/40/cgi-

bin/script.pl.

Ifyouwanttoincludethe.characterinaVirtualDocumentRootdirective,butitclasheswitha%directive,youcanworkaroundtheprobleminthefollowingway:

VirtualDocumentRoot/usr/local/apache/vhosts/%2.0.%3.0

Arequestforhttp://www.domain.example.com/directory/file.html

willbesatisfiedbythefile/usr/local/apache/vhosts/domain.example/directory/file.html

TheLogFormatdirectives%Vand%Aareusefulinconjunctionwiththismodule.

VirtualDocumentRootDirective

Description: Dynamicallyconfigurethelocationofthedocumentrootforagivenvirtualhost

Syntax: VirtualDocumentRootinterpolated-

directory|none

Default: VirtualDocumentRootnone

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_vhost_alias

TheVirtualDocumentRootdirectiveallowsyoutodeterminewhereApachewillfindyourdocumentsbasedonthevalueoftheservername.Theresultofexpandinginterpolated-directoryisusedastherootofthedocumenttreeinasimilarmannertotheDocumentRootdirective'sargument.Ifinterpolated-directoryisnonethenVirtualDocumentRootisturnedoff.ThisdirectivecannotbeusedinthesamecontextasVirtualDocumentRootIP.

VirtualDocumentRootIPDirective

Description: Dynamicallyconfigurethelocationofthedocumentrootforagivenvirtualhost

Syntax: VirtualDocumentRootIPinterpolated-

directory|none

Default: VirtualDocumentRootIPnone

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_vhost_alias

TheVirtualDocumentRootIPdirectiveisliketheVirtualDocumentRootdirective,exceptthatitusestheIPaddressoftheserverendoftheconnectionfordirectoryinterpolationinsteadoftheservername.

VirtualScriptAliasDirective

Description: DynamicallyconfigurethelocationoftheCGIdirectoryforagivenvirtualhost

Syntax: VirtualScriptAliasinterpolated-

directory|none

Default: VirtualScriptAliasnone

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_vhost_alias

TheVirtualScriptAliasdirectiveallowsyoutodeterminewhereApachewillfindCGIscriptsinasimilarmannertoVirtualDocumentRootdoesforotherdocuments.ItmatchesrequestsforURIsstarting/cgi-bin/,muchlikeScriptAlias/cgi-bin/would.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

VirtualScriptAliasIPDirective

Description: Dynamicallyconfigurethelocationofthecgidirectoryforagivenvirtualhost

Syntax: VirtualScriptAliasIPinterpolated-

directory|none

Default: VirtualScriptAliasIPnone

Context: serverconfig,virtualhostStatus: ExtensionModule: mod_vhost_alias

TheVirtualScriptAliasIPdirectiveisliketheVirtualScriptAliasdirective,exceptthatitusestheIPaddressoftheserverendoftheconnectionfordirectoryinterpolationinsteadoftheservername.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>DeveloperDocumentation

Apache1.3APInotes

Warning

Thisdocumenthasnotbeenupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

ThesearesomenotesontheApacheAPIandthedatastructuresyouhavetodealwith,etc.Theyarenotyetnearlycomplete,buthopefully,theywillhelpyougetyourbearings.KeepinmindthattheAPIisstillsubjecttochangeaswegainexperiencewithit.(SeetheTODOfileforwhatmightbecoming).However,itwillbeeasytoadaptmodulestoanychangesthataremade.(Wehavemoremodulestoadaptthanyoudo).

Afewnotesongeneralpedagogicalstylehere.Intheinterestofconciseness,allstructuredeclarationshereareincomplete--therealoneshavemoreslotsthatI'mnottellingyouabout.Forthemostpart,thesearereservedtoonecomponentoftheservercoreoranother,andshouldbealteredbymoduleswithcaution.However,insomecases,theyreallyarethingsIjusthaven'tgottenaroundtoyet.Welcometothebleedingedge.

Finally,here'sanoutline,togiveyousomebareideaofwhat'scomingup,andinwhatorder:

Basicconcepts.Handlers,Modules,andRequestsAbrieftourofamodule

HowhandlersworkAbrieftouroftherequest_recWhererequest_recstructurescomefrom

Handlingrequests,declining,andreturningerrorcodesSpecialconsiderationsforresponsehandlersSpecialconsiderationsforauthenticationhandlersSpecialconsiderationsforlogginghandlers

ResourceallocationandresourcepoolsConfiguration,commandsandthelike

Per-directoryconfigurationstructuresCommandhandlingSidenotes---per-serverconfiguration,virtualservers,etc.

Basicconcepts

WebeginwithanoverviewofthebasicconceptsbehindtheAPI,andhowtheyaremanifestedinthecode.

Handlers,Modules,andRequestsApachebreaksdownrequesthandlingintoaseriesofsteps,moreorlessthesamewaytheNetscapeserverAPIdoes(althoughthisAPIhasafewmorestagesthanNetSitedoes,ashooksforstuffIthoughtmightbeusefulinthefuture).Theseare:

URI->FilenametranslationAuthIDchecking[istheuserwhotheysaytheyare?]Authaccesschecking[istheuserauthorizedhere?]AccesscheckingotherthanauthDeterminingMIMEtypeoftheobjectrequested`Fixups'--therearen'tanyoftheseyet,butthephaseisintendedasahookforpossibleextensionslikeSetEnv,whichdon'treallyfitwellelsewhere.Actuallysendingaresponsebacktotheclient.Loggingtherequest

Thesephasesarehandledbylookingateachofasuccessionofmodules,lookingtoseeifeachofthemhasahandlerforthephase,andattemptinginvokingitifso.Thehandlercantypicallydooneofthreethings:

Handletherequest,andindicatethatithasdonesobyreturningthemagicconstantOK.Declinetohandletherequest,byreturningthemagicintegerconstantDECLINED.Inthiscase,theserverbehavesinallrespectsasifthehandlersimplyhadn'tbeenthere.Signalanerror,byreturningoneoftheHTTPerrorcodes.Thisterminatesnormalhandlingoftherequest,althoughanErrorDocumentmaybeinvokedtotrytomopup,anditwillbe

loggedinanycase.

Mostphasesareterminatedbythefirstmodulethathandlesthem;however,forlogging,`fixups',andnon-accessauthenticationchecking,allhandlersalwaysrun(barringanerror).Also,theresponsephaseisuniqueinthatmodulesmaydeclaremultiplehandlersforit,viaadispatchtablekeyedontheMIMEtypeoftherequestedobject.Modulesmaydeclarearesponse-phasehandlerwhichcanhandleanyrequest,bygivingitthekey*/*(i.e.,awildcardMIMEtypespecification).However,wildcardhandlersareonlyinvokediftheserverhasalreadytriedandfailedtofindamorespecificresponsehandlerfortheMIMEtypeoftherequestedobject(eithernoneexisted,ortheyalldeclined).

Thehandlersthemselvesarefunctionsofoneargument(arequest_recstructure.videinfra),whichreturnsaninteger,asabove.

AbrieftourofamoduleAtthispoint,weneedtoexplainthestructureofamodule.Ourcandidatewillbeoneofthemessierones,theCGImodule--thishandlesbothCGIscriptsandtheScriptAliasconfigfilecommand.It'sactuallyagreatdealmorecomplicatedthanmostmodules,butifwe'regoingtohaveonlyoneexample,itmightaswellbetheonewithitsfingersineveryplace.

Let'sbeginwithhandlers.InordertohandletheCGIscripts,themoduledeclaresaresponsehandlerforthem.BecauseofScriptAlias,italsohashandlersforthenametranslationphase(torecognizeScriptAliasedURIs),thetype-checkingphase(anyScriptAliasedrequestistypedasaCGIscript).

Themoduleneedstomaintainsomeper(virtual)serverinformation,namely,theScriptAliasesineffect;themodule

structurethereforecontainspointerstoafunctionswhichbuildsthesestructures,andtoanotherwhichcombinestwoofthem(incasethemainserverandavirtualserverbothhaveScriptAliasesdeclared).

Finally,thismodulecontainscodetohandletheScriptAliascommanditself.Thisparticularmoduleonlydeclaresonecommand,buttherecouldbemore,somoduleshavecommandtableswhichdeclaretheircommands,anddescribewheretheyarepermitted,andhowtheyaretobeinvoked.

Afinalnoteonthedeclaredtypesoftheargumentsofsomeofthesecommands:apoolisapointertoaresourcepoolstructure;theseareusedbytheservertokeeptrackofthememorywhichhasbeenallocated,filesopened,etc.,eithertoserviceaparticularrequest,ortohandletheprocessofconfiguringitself.Thatway,whentherequestisover(or,fortheconfigurationpool,whentheserverisrestarting),thememorycanbefreed,andthefilesclosed,enmasse,withoutanyonehavingtowriteexplicitcodetotrackthemalldownanddisposeofthem.Also,acmd_parmsstructurecontainsvariousinformationabouttheconfigfilebeingread,andotherstatusinformation,whichissometimesofusetothefunctionwhichprocessesaconfig-filecommand(suchasScriptAlias).Withnofurtherado,themoduleitself:

/*Declarationsofhandlers.*/

inttranslate_scriptalias(request_rec*);

inttype_scriptalias(request_rec*);

intcgi_handler(request_rec*);

/*Subsidiarydispatchtableforresponse-phase

*handlers,byMIMEtype*/

handler_reccgi_handlers[]={

{"application/x-httpd-cgi",cgi_handler},

{NULL}

};

/*Declarationsofroutinestomanipulatethe

*module'sconfigurationinfo.Notethattheseare

*returned,andpassedin,asvoid*'s;theserver

*corekeepstrackofthem,butitdoesn't,andcan't,

*knowtheirinternalstructure.

*/

void*make_cgi_server_config(pool*);

void*merge_cgi_server_config(pool*,void*,void*);

/*Declarationsofroutinestohandleconfig-filecommands*/

externchar*script_alias(cmd_parms*,void*per_dir_config,

char*fake,char*real);

command_reccgi_cmds[]={

{"ScriptAlias",script_alias,NULL,RSRC_CONF,TAKE2,

"afakenameandarealname"},

{NULL}

};

modulecgi_module={

STANDARD_MODULE_STUFF,

NULL,/*initializer*/

NULL,/*dirconfigcreator*/

NULL,/*dirmerger*/

make_cgi_server_config,/*serverconfig*/

merge_cgi_server_config,/*mergeserverconfig*/

cgi_cmds,/*commandtable*/

cgi_handlers,/*handlers*/

translate_scriptalias,/*filenametranslation*/

NULL,/*check_user_id*/

NULL,/*checkauth*/

NULL,/*checkaccess*/

type_scriptalias,/*type_checker*/

NULL,/*fixups*/

NULL,/*logger*/

NULL/*headerparser*/

};

Howhandlerswork

Thesoleargumenttohandlersisarequest_recstructure.Thisstructuredescribesaparticularrequestwhichhasbeenmadetotheserver,onbehalfofaclient.Inmostcases,eachconnectiontotheclientgeneratesonlyonerequest_recstructure.

Abrieftouroftherequest_recTherequest_reccontainspointerstoaresourcepoolwhichwillbeclearedwhentheserverisfinishedhandlingtherequest;tostructurescontainingper-serverandper-connectioninformation,andmostimportantly,informationontherequestitself.

Themostimportantsuchinformationisasmallsetofcharacterstringsdescribingattributesoftheobjectbeingrequested,includingitsURI,filename,content-typeandcontent-encoding(thesebeingfilledinbythetranslationandtype-checkhandlerswhichhandletherequest,respectively).

OthercommonlyuseddataitemsaretablesgivingtheMIMEheadersontheclient'soriginalrequest,MIMEheaderstobesentbackwiththeresponse(whichmodulescanaddtoatwill),andenvironmentvariablesforanysubprocesseswhicharespawnedoffinthecourseofservicingtherequest.Thesetablesaremanipulatedusingtheap_table_getandap_table_setroutines.

NotethattheContent-typeheadervaluecannotbesetbymodulecontent-handlersusingtheap_table_*()routines.Rather,itissetbypointingthecontent_typefieldintherequest_recstructuretoanappropriatestring.e.g.,

r->content_type="text/html";

Finally,therearepointerstotwodatastructureswhich,inturn,pointtoper-moduleconfigurationstructures.Specifically,theseholdpointerstothedatastructureswhichthemodulehasbuilttodescribethewayithasbeenconfiguredtooperateinagivendirectory(via.htaccessfilesor<Directory>sections),forprivatedataithasbuiltinthecourseofservicingtherequest(somodules'handlersforonephasecanpass`notes'totheirhandlersforotherphases).Thereisanothersuchconfigurationvectorintheserver_recdatastructurepointedtobytherequest_rec,whichcontainsper(virtual)serverconfigurationdata.

Hereisanabridgeddeclaration,givingthefieldsmostcommonlyused:

structrequest_rec{

pool*pool;

conn_rec*connection;

server_rec*server;

/*Whatobjectisbeingrequested*/

char*uri;

char*filename;

char*path_info;

char*args;/*QUERY_ARGS,ifany*/

structstatfinfo;/*Setbyservercore;

*st_modesettozeroifnosuchfile*/

char*content_type;

char*content_encoding;

/*MIMEheaderenvironments,inandout.Also,

*anarraycontainingenvironmentvariablesto

*bepassedtosubprocesses,sopeoplecanwrite

*modulestoaddtothatenvironment.

*

*Thedifferencebetweenheaders_outand

*err_headers_outisthatthelatterareprinted

*evenonerror,andpersistacrossinternal

*redirects(sotheheadersprintedfor

*ErrorDocumenthandlerswillhavethem).

*/

table*headers_in;table*headers_out;table*err_headers_out;table*subprocess_env;

/*Infoabouttherequestitself...*/

intheader_only;/*HEADrequest,asopposedtoGET*/

char*protocol;/*Protocol,asgiventous,orHTTP/0.9*/

char*method;/*GET,HEAD,POST,etc.*/

intmethod_number;/*M_GET,M_POST,etc.*/

/*Infoforlogging*/

char*the_request;

intbytes_sent;

/*Aflagwhichmodulescanset,toindicatethat

*thedatabeingreturnedisvolatile,andclients

*shouldbetoldnottocacheit.

*/

intno_cache;

/*Variousotherconfiginfowhichmaychange

*with.htaccessfiles

*Theseareconfigvectors,withonevoid*

*pointerforeachmodule(thethingpointed

*tobeingthemodule'sbusiness).

*/

void*per_dir_config;/*Optionssetinconfigfiles,etc.*/

void*request_config;/*Noteson*this*request*/

};

Whererequest_recstructurescomefromMostrequest_recstructuresarebuiltbyreadinganHTTPrequestfromaclient,andfillinginthefields.However,thereareafewexceptions:

Iftherequestistoanimagemap,atypemap(i.e.,a*.varfile),oraCGIscriptwhichreturnedalocal`Location:',thentheresourcewhichtheuserrequestedisgoingtobeultimatelylocatedbysomeURIotherthanwhattheclientoriginallysupplied.Inthiscase,theserverdoesaninternalredirect,constructinganewrequest_recforthenewURI,andprocessingitalmostexactlyasiftheclienthadrequestedthenewURIdirectly.Ifsomehandlersignaledanerror,andanErrorDocumentisinscope,thesameinternalredirectmachinerycomesintoplay.Finally,ahandleroccasionallyneedstoinvestigate`whatwouldhappenif'someotherrequestwererun.Forinstance,thedirectoryindexingmoduleneedstoknowwhatMIMEtypewouldbeassignedtoarequestforeachdirectoryentry,inordertofigureoutwhaticontouse.

Suchhandlerscanconstructasub-request,usingthefunctionsap_sub_req_lookup_file,ap_sub_req_lookup_uri,andap_sub_req_method_uri;theseconstructanewrequest_recstructureandprocessesitasyouwouldexpect,uptobutnotincludingthepointofactuallysendingaresponse.(Thesefunctionsskipovertheaccesschecksifthesub-requestisforafileinthesamedirectoryastheoriginalrequest).

(Server-sideincludesworkbybuildingsub-requestsandthenactuallyinvokingtheresponsehandlerforthem,viathefunctionap_run_sub_req).

Handlingrequests,declining,andreturningerrorcodes

Asdiscussedabove,eachhandler,wheninvokedtohandleaparticularrequest_rec,hastoreturnaninttoindicatewhathappened.Thatcaneitherbe

OK--therequestwashandledsuccessfully.Thismayormaynotterminatethephase.DECLINED--noerroneousconditionexists,butthemoduledeclinestohandlethephase;theservertriestofindanother.anHTTPerrorcode,whichabortshandlingoftherequest.

NotethatiftheerrorcodereturnedisREDIRECT,thenthemoduleshouldputaLocationintherequest'sheaders_out,toindicatewheretheclientshouldberedirectedto.

SpecialconsiderationsforresponsehandlersHandlersformostphasesdotheirworkbysimplysettingafewfieldsintherequest_recstructure(or,inthecaseofaccesscheckers,simplybyreturningthecorrecterrorcode).However,responsehandlershavetoactuallysendarequestbacktotheclient.

TheyshouldbeginbysendinganHTTPresponseheader,usingthefunctionap_send_http_header.(Youdon'thavetodoanythingspecialtoskipsendingtheheaderforHTTP/0.9requests;thefunctionfiguresoutonitsownthatitshouldn'tdoanything).Iftherequestismarkedheader_only,that'salltheyshoulddo;theyshouldreturnafterthat,withoutattemptinganyfurtheroutput.

Otherwise,theyshouldproducearequestbodywhichrespondstotheclientasappropriate.Theprimitivesforthisareap_rputcandap_rprintf,forinternallygeneratedoutput,andap_send_fd,tocopythecontentsofsomeFILE*straighttotheclient.

Atthispoint,youshouldmoreorlessunderstandthefollowingpieceofcode,whichisthehandlerwhichhandlesGETrequestswhichhavenomorespecifichandler;italsoshowshowconditionalGETscanbehandled,ifit'sdesirabletodosoinaparticularresponsehandler--ap_set_last_modifiedchecksagainsttheIf-modified-sincevaluesuppliedbytheclient,ifany,andreturnsanappropriatecode(whichwill,ifnonzero,beUSE_LOCAL_COPY).Nosimilarconsiderationsapplyforap_set_content_length,butitreturnsanerrorcodeforsymmetry.

intdefault_handler(request_rec*r)

{

interrstatus;

FILE*f;

if(r->method_number!=M_GET)returnDECLINED;

if(r->finfo.st_mode==0)returnNOT_FOUND;

if((errstatus=ap_set_content_length(r,r-

>finfo.st_size))

||(errstatus=ap_set_last_modified(r,r-

>finfo.st_mtime)))

returnerrstatus;

f=fopen(r->filename,"r");

if(f==NULL){

log_reason("filepermissionsdenyserveraccess",r-

>filename,r);

returnFORBIDDEN;

}

register_timeout("send",r);

ap_send_http_header(r);

if(!r->header_only)send_fd(f,r);

ap_pfclose(r->pool,f);

returnOK;

}

Finally,ifallofthisistoomuchofachallenge,thereareafew

waysoutofit.Firstoff,asshownabove,aresponsehandlerwhichhasnotyetproducedanyoutputcansimplyreturnanerrorcode,inwhichcasetheserverwillautomaticallyproduceanerrorresponse.Secondly,itcanpunttosomeotherhandlerbyinvokingap_internal_redirect,whichishowtheinternalredirectionmachinerydiscussedaboveisinvoked.AresponsehandlerwhichhasinternallyredirectedshouldalwaysreturnOK.

(Invokingap_internal_redirectfromhandlerswhicharenotresponsehandlerswillleadtoseriousconfusion).

SpecialconsiderationsforauthenticationhandlersStuffthatshouldbediscussedhereindetail:

Authentication-phasehandlersnotinvokedunlessauthisconfiguredforthedirectory.Commonauthconfigurationstoredinthecoreper-dirconfiguration;ithasaccessorsap_auth_type,ap_auth_name,andap_requires.Commonroutines,tohandletheprotocolendofthings,atleastforHTTPbasicauthentication(ap_get_basic_auth_pw,whichsetstheconnection->userstructurefieldautomatically,andap_note_basic_auth_failure,whicharrangesfortheproperWWW-Authenticate:headertobesentback).

SpecialconsiderationsforlogginghandlersWhenarequesthasinternallyredirected,thereisthequestionofwhattolog.Apachehandlesthisbybundlingtheentirechainofredirectsintoalistofrequest_recstructureswhicharethreadedthroughther->prevandr->nextpointers.Therequest_recwhichispassedtothelogginghandlersinsuchcasesistheonewhichwasoriginallybuiltfortheinitialrequestfromtheclient;note

thatthebytes_sentfieldwillonlybecorrectinthelastrequestinthechain(theoneforwhicharesponsewasactuallysent).

Resourceallocationandresourcepools

Oneoftheproblemsofwritinganddesigningaserver-poolserveristhatofpreventingleakage,thatis,allocatingresources(memory,openfiles,etc.),withoutsubsequentlyreleasingthem.Theresourcepoolmachineryisdesignedtomakeiteasytopreventthisfromhappening,byallowingresourcetobeallocatedinsuchawaythattheyareautomaticallyreleasedwhentheserverisdonewiththem.

Thewaythisworksisasfollows:thememorywhichisallocated,fileopened,etc.,todealwithaparticularrequestaretiedtoaresourcepoolwhichisallocatedfortherequest.Thepoolisadatastructurewhichitselftrackstheresourcesinquestion.

Whentherequesthasbeenprocessed,thepooliscleared.Atthatpoint,allthememoryassociatedwithitisreleasedforreuse,allfilesassociatedwithitareclosed,andanyotherclean-upfunctionswhichareassociatedwiththepoolarerun.Whenthisisover,wecanbeconfidentthatalltheresourcetiedtothepoolhavebeenreleased,andthatnoneofthemhaveleaked.

Serverrestarts,andallocationofmemoryandresourcesforper-serverconfiguration,arehandledinasimilarway.Thereisaconfigurationpool,whichkeepstrackofresourceswhichwereallocatedwhilereadingtheserverconfigurationfiles,andhandlingthecommandstherein(forinstance,thememorythatwasallocatedforper-servermoduleconfiguration,logfilesandotherfilesthatwereopened,andsoforth).Whentheserverrestarts,andhastorereadtheconfigurationfiles,theconfigurationpooliscleared,andsothememoryandfiledescriptorswhichweretakenupbyreadingthemthelasttimearemadeavailableforreuse.

Itshouldbenotedthatuseofthepoolmachineryisn'tgenerallyobligatory,exceptforsituationslikelogginghandlers,whereyoureallyneedtoregistercleanupstomakesurethatthelogfilegets

closedwhentheserverrestarts(thisismosteasilydonebyusingthefunctionap_pfopen,whichalsoarrangesfortheunderlyingfiledescriptortobeclosedbeforeanychildprocesses,suchasforCGIscripts,areexeced),orincaseyouareusingthetimeoutmachinery(whichisn'tyetevendocumentedhere).However,therearetwobenefitstousingit:resourcesallocatedtoapoolneverleak(evenifyouallocateascratchstring,andjustforgetaboutit);also,formemoryallocation,ap_pallocisgenerallyfasterthanmalloc.

Webeginherebydescribinghowmemoryisallocatedtopools,andthendiscusshowotherresourcesaretrackedbytheresourcepoolmachinery.

AllocationofmemoryinpoolsMemoryisallocatedtopoolsbycallingthefunctionap_palloc,whichtakestwoarguments,onebeingapointertoaresourcepoolstructure,andtheotherbeingtheamountofmemorytoallocate(inchars).Withinhandlersforhandlingrequests,themostcommonwayofgettingaresourcepoolstructureisbylookingatthepoolslotoftherelevantrequest_rec;hencetherepeatedappearanceofthefollowingidiominmodulecode:

intmy_handler(request_rec*r)

{

structmy_structure*foo;

...

foo=(foo*)ap_palloc(r->pool,sizeof(my_structure));

}

Notethatthereisnoap_pfree--ap_pallocedmemoryisfreedonlywhentheassociatedresourcepooliscleared.Thismeansthatap_pallocdoesnothavetodoasmuchaccountingasmalloc();allitdoesinthetypicalcaseistoroundupthesize,

bumpapointer,anddoarangecheck.

(Italsoraisesthepossibilitythatheavyuseofap_palloccouldcauseaserverprocesstogrowexcessivelylarge.Therearetwowaystodealwiththis,whicharedealtwithbelow;briefly,youcanusemalloc,andtrytobesurethatallofthememorygetsexplicitlyfreed,oryoucanallocateasub-poolofthemainpool,allocateyourmemoryinthesub-pool,andclearitoutperiodically.Thelattertechniqueisdiscussedinthesectiononsub-poolsbelow,andisusedinthedirectory-indexingcode,inordertoavoidexcessivestorageallocationwhenlistingdirectorieswiththousandsoffiles).

AllocatinginitializedmemoryTherearefunctionswhichallocateinitializedmemory,andarefrequentlyuseful.Thefunctionap_pcallochasthesameinterfaceasap_palloc,butclearsoutthememoryitallocatesbeforeitreturnsit.Thefunctionap_pstrduptakesaresourcepoolandachar*asarguments,andallocatesmemoryforacopyofthestringthepointerpointsto,returningapointertothecopy.Finallyap_pstrcatisavarargs-stylefunction,whichtakesapointertoaresourcepool,andatleasttwochar*arguments,thelastofwhichmustbeNULL.Itallocatesenoughmemorytofitcopiesofeachofthestrings,asaunit;forinstance:

ap_pstrcat(r->pool,"foo","/","bar",NULL);

returnsapointerto8bytesworthofmemory,initializedto"foo/bar".

Commonly-usedpoolsintheApacheWebserverApoolisreallydefinedbyitslifetimemorethananythingelse.

Therearesomestaticpoolsinhttp_mainwhicharepassedtovariousnon-http_mainfunctionsasargumentsatopportunetimes.Heretheyare:

permanent_pool

neverpassedtoanythingelse,thisistheancestorofallpools

pconf

subpoolofpermanent_poolcreatedatthebeginningofaconfig"cycle";existsuntiltheserveristerminatedorrestarts;passedtoallconfig-timeroutines,eitherviacmd->pool,orasthe"pool*p"argumentonthosewhichdon'ttakepoolspassedtothemoduleinit()functions

ptemp

sorryIlie,thispoolisn'tcalledthiscurrentlyin1.3,Irenameditthisinmypthreadsdevelopment.I'mreferringtotheuseofptransintheparent...contrastthiswiththelaterdefinitionofptransinthechild.subpoolofpermanent_poolcreatedatthebeginningofaconfig"cycle";existsuntiltheendofconfigparsing;passedtoconfig-timeroutinesviacmd->temp_pool.Somewhatofa"bastardchild"becauseitisn'tavailableeverywhere.Usedfortemporaryscratchspacewhichmaybeneededbysomeconfigroutinesbutwhichisdeletedattheendofconfig.

pchild

subpoolofpermanent_poolcreatedwhenachildisspawned(orathreadiscreated);livesuntilthatchild(thread)isdestroyedpassedtothemodulechild_initfunctionsdestructionhappensrightafterthechild_exitfunctionsarecalled...(whichmayexplainwhyIthinkchild_exitis

redundantandunneeded)

ptrans

shouldbeasubpoolofpchild,butcurrentlyisasubpoolofpermanent_pool,seeaboveclearedbythechildbeforegoingintotheaccept()looptoreceiveaconnectionusedasconnection->pool

r->pool

forthemainrequestthisisasubpoolofconnection->pool;forsubrequestsitisasubpooloftheparentrequest'spool.existsuntiltheendoftherequest(i.e.,ap_destroy_sub_req,orinchild_mainafterprocess_requesthasfinished)notethatritselfisallocatedfromr->pool;i.e.,r->poolisfirstcreatedandthenristhefirstthingpalloc()dfromit

Foralmosteverythingfolksdo,r->poolisthepooltouse.Butyoucanseehowotherlifetimes,suchaspchild,areusefultosomemodules...suchasmodulesthatneedtoopenadatabaseconnectiononceperchild,andwishtocleanitupwhenthechilddies.

Youcanalsoseehowsomebugshavemanifestedthemself,suchassettingconnection->usertoavaluefromr->pool--inthiscaseconnectionexistsforthelifetimeofptrans,whichislongerthanr->pool(especiallyifr->poolisasubrequest!).Sothecorrectthingtodoistoallocatefromconnection->pool.

Andtherewasanotherinterestingbuginmod_include/mod_cgi.You'llseeinthosethattheydothistesttodecideiftheyshoulduser->poolorr->main->pool.Inthiscasetheresourcethattheyareregisteringforcleanupisachildprocess.If

itwereregisteredinr->pool,thenthecodewouldwait()forthechildwhenthesubrequestfinishes.Withmod_includethiscouldbeanyold#include,andthedelaycanbeupto3seconds...andhappenedquitefrequently.Insteadthesubprocessisregisteredinr->main->poolwhichcausesittobecleanedupwhentheentirerequestisdone--i.e.,aftertheoutputhasbeensenttotheclientandlogginghashappened.

Trackingopenfiles,etc.Asindicatedabove,resourcepoolsarealsousedtotrackothersortsofresourcesbesidesmemory.Themostcommonareopenfiles.Theroutinewhichistypicallyusedforthisisap_pfopen,whichtakesaresourcepoolandtwostringsasarguments;thestringsarethesameasthetypicalargumentstofopen,e.g.,

...

FILE*f=ap_pfopen(r->pool,r->filename,"r");

if(f==NULL){...}else{...}

Thereisalsoaap_popenfroutine,whichparallelsthelower-levelopensystemcall.Bothoftheseroutinesarrangeforthefiletobeclosedwhentheresourcepoolinquestioniscleared.

Unlikethecaseformemory,therearefunctionstoclosefilesallocatedwithap_pfopen,andap_popenf,namelyap_pfcloseandap_pclosef.(Thisisbecause,onmanysystems,thenumberoffileswhichasingleprocesscanhaveopenisquitelimited).Itisimportanttousethesefunctionstoclosefilesallocatedwithap_pfopenandap_popenf,sincetodootherwisecouldcausefatalerrorsonsystemssuchasLinux,whichreactbadlyifthesameFILE*isclosedmorethanonce.

(Usingtheclosefunctionsisnotmandatory,sincethefilewill

eventuallybeclosedregardless,butyoushouldconsideritincaseswhereyourmoduleisopening,orcouldopen,alotoffiles).

Othersortsofresources--cleanupfunctionsMoretextgoeshere.Describethecleanupprimitivesintermsofwhichthefilestuffisimplemented;also,spawn_process.

Poolcleanupsliveuntilclear_pool()iscalled:clear_pool(a)recursivelycallsdestroy_pool()onallsubpoolsofa;thencallsallthecleanupsfora;thenreleasesallthememoryfora.destroy_pool(a)callsclear_pool(a)andthenreleasesthepoolstructureitself.i.e.,clear_pool(a)doesn'tdeletea,itjustfreesupalltheresourcesandyoucanstartusingitagainimmediately.

Finecontrol--creatinganddealingwithsub-pools,withanoteonsub-requestsOnrareoccasions,too-freeuseofap_palloc()andtheassociatedprimitivesmayresultinundesirablyprofligateresourceallocation.Youcandealwithsuchacasebycreatingasub-pool,allocatingwithinthesub-poolratherthanthemainpool,andclearingordestroyingthesub-pool,whichreleasestheresourceswhichwereassociatedwithit.(Thisreallyisararesituation;theonlycaseinwhichitcomesupinthestandardmodulesetisincaseoflistingdirectories,andthenonlywithverylargedirectories.Unnecessaryuseoftheprimitivesdiscussedherecanhairupyourcodequiteabit,withverylittlegain).

Theprimitiveforcreatingasub-poolisap_make_sub_pool,whichtakesanotherpool(theparentpool)asanargument.Whenthemainpooliscleared,thesub-poolwillbedestroyed.Thesub-poolmayalsobeclearedordestroyedatanytime,bycallingthefunctionsap_clear_poolandap_destroy_pool,respectively.

(Thedifferenceisthatap_clear_poolfreesresourcesassociatedwiththepool,whileap_destroy_poolalsodeallocatesthepoolitself.Intheformercase,youcanallocatenewresourceswithinthepool,andclearitagain,andsoforth;inthelattercase,itissimplygone).

Onefinalnote--sub-requestshavetheirownresourcepools,whicharesub-poolsoftheresourcepoolforthemainrequest.Thepolitewaytoreclaimtheresourcesassociatedwithasubrequestwhichyouhaveallocated(usingtheap_sub_req_...functions)isap_destroy_sub_req,whichfreestheresourcepool.Beforecallingthisfunction,besuretocopyanythingthatyoucareaboutwhichmightbeallocatedinthesub-request'sresourcepoolintosomeplacealittlelessvolatile(forinstance,thefilenameinitsrequest_recstructure).

(Again,undermostcircumstances,youshouldn'tfeelobligedtocallthisfunction;only2Kofmemoryorsoareallocatedforatypicalsubrequest,anditwillbefreedanywaywhenthemainrequestpooliscleared.Itisonlywhenyouareallocatingmany,manysub-requestsforasinglemainrequestthatyoushouldseriouslyconsidertheap_destroy_...functions).

Configuration,commandsandthelike

OneofthedesigngoalsforthisserverwastomaintainexternalcompatibilitywiththeNCSA1.3server---thatis,toreadthesameconfigurationfiles,toprocessallthedirectivesthereincorrectly,andingeneraltobeadrop-inreplacementforNCSA.Ontheotherhand,anotherdesigngoalwastomoveasmuchoftheserver'sfunctionalityintomoduleswhichhaveaslittleaspossibletodowiththemonolithicservercore.Theonlywaytoreconcilethesegoalsistomovethehandlingofmostcommandsfromthecentralserverintothemodules.

However,justgivingthemodulescommandtablesisnotenoughtodivorcethemcompletelyfromtheservercore.Theserverhastorememberthecommandsinordertoactonthemlater.Thatinvolvesmaintainingdatawhichisprivatetothemodules,andwhichcanbeeitherper-server,orper-directory.Mostthingsareper-directory,includinginparticularaccesscontrolandauthorizationinformation,butalsoinformationonhowtodeterminefiletypesfromsuffixes,whichcanbemodifiedbyAddTypeandDefaultTypedirectives,andsoforth.Ingeneral,thegoverningphilosophyisthatanythingwhichcanbemadeconfigurablebydirectoryshouldbe;per-serverinformationisgenerallyusedinthestandardsetofmodulesforinformationlikeAliasesandRedirectswhichcomeintoplaybeforetherequestistiedtoaparticularplaceintheunderlyingfilesystem.

AnotherrequirementforemulatingtheNCSAserverisbeingabletohandletheper-directoryconfigurationfiles,generallycalled.htaccessfiles,thoughevenintheNCSAservertheycancontaindirectiveswhichhavenothingatalltodowithaccesscontrol.Accordingly,afterURI->filenametranslation,butbeforeperforminganyotherphase,theserverwalksdownthedirectoryhierarchyoftheunderlyingfilesystem,followingthetranslatedpathname,toreadany.htaccessfileswhichmightbepresent.

Theinformationwhichisreadinthenhastobemergedwiththeapplicableinformationfromtheserver'sownconfigfiles(eitherfromthe<Directory>sectionsinaccess.conf,orfromdefaultsinsrm.conf,whichactuallybehavesformostpurposesalmostexactlylike<Directory/>).

Finally,afterhavingservedarequestwhichinvolvedreading.htaccessfiles,weneedtodiscardthestorageallocatedforhandlingthem.Thatissolvedthesamewayitissolvedwhereverelsesimilarproblemscomeup,bytyingthosestructurestotheper-transactionresourcepool.

Per-directoryconfigurationstructuresLet'slookouthowallofthisplaysoutinmod_mime.c,whichdefinesthefiletypinghandlerwhichemulatestheNCSAserver'sbehaviorofdeterminingfiletypesfromsuffixes.Whatwe'llbelookingat,here,isthecodewhichimplementstheAddTypeandAddEncodingcommands.Thesecommandscanappearin.htaccessfiles,sotheymustbehandledinthemodule'sprivateper-directorydata,whichinfact,consistsoftwoseparatetablesforMIMEtypesandencodinginformation,andisdeclaredasfollows:

typedefstruct{

table*forced_types;/*AdditionalAddTypedstuff*/

table*encoding_types;/*AddedwithAddEncoding...*/

}mime_dir_config;

Whentheserverisreadingaconfigurationfile,or<Directory>section,whichincludesoneoftheMIMEmodule'scommands,itneedstocreateamime_dir_configstructure,sothosecommandshavesomethingtoacton.Itdoesthisbyinvokingthefunctionitfindsinthemodule's`createper-dirconfigslot',withtwoarguments:thenameofthedirectorytowhichthisconfiguration

informationapplies(orNULLforsrm.conf),andapointertoaresourcepoolinwhichtheallocationshouldhappen.

(Ifwearereadinga.htaccessfile,thatresourcepoolistheper-requestresourcepoolfortherequest;otherwiseitisaresourcepoolwhichisusedforconfigurationdata,andclearedonrestarts.Eitherway,itisimportantforthestructurebeingcreatedtovanishwhenthepooliscleared,byregisteringacleanuponthepoolifnecessary).

FortheMIMEmodule,theper-dirconfigcreationfunctionjustap_pallocsthestructureabove,andacreatesacoupleoftablestofillit.Thatlookslikethis:

void*create_mime_dir_config(pool*p,char*dummy)

{

mime_dir_config*new=

(mime_dir_config*)ap_palloc(p,

sizeof(mime_dir_config));

new->forced_types=ap_make_table(p,4);

new->encoding_types=ap_make_table(p,4);

returnnew;

}

Now,supposewe'vejustreadina.htaccessfile.Wealreadyhavetheper-directoryconfigurationstructureforthenextdirectoryupinthehierarchy.Ifthe.htaccessfilewejustreadindidn'thaveanyAddTypeorAddEncodingcommands,itsper-directoryconfigstructurefortheMIMEmoduleisstillvalid,andwecanjustuseit.Otherwise,weneedtomergethetwostructuressomehow.

Todothat,theserverinvokesthemodule'sper-directoryconfigmergefunction,ifoneispresent.Thatfunctiontakesthreearguments:thetwostructuresbeingmerged,andaresourcepoolinwhichtoallocatetheresult.FortheMIMEmodule,allthatneeds

tobedoneisoverlaythetablesfromthenewper-directoryconfigstructurewiththosefromtheparent:

void*merge_mime_dir_configs(pool*p,void*parent_dirv,void

*subdirv)

{

mime_dir_config*parent_dir=(mime_dir_config

*)parent_dirv;

mime_dir_config*subdir=(mime_dir_config*)subdirv;

mime_dir_config*new=

(mime_dir_config*)ap_palloc(p,sizeof(mime_dir_config));

new->forced_types=ap_overlay_tables(p,subdir-

>forced_types,

parent_dir->forced_types);

new->encoding_types=ap_overlay_tables(p,subdir-

>encoding_types,

parent_dir->encoding_types);

returnnew;

}

Asanote--ifthereisnoper-directorymergefunctionpresent,theserverwilljustusethesubdirectory'sconfigurationinfo,andignoretheparent's.Forsomemodules,thatworksjustfine(e.g.,fortheincludesmodule,whoseper-directoryconfigurationinformationconsistssolelyofthestateoftheXBITHACK),andforthosemodules,youcanjustnotdeclareone,andleavethecorrespondingstructureslotinthemoduleitselfNULL.

CommandhandlingNowthatwehavethesestructures,weneedtobeabletofigureouthowtofillthem.ThatinvolvesprocessingtheactualAddTypeandAddEncodingcommands.Tofindcommands,theserverlooksinthemodule'scommandtable.Thattablecontainsinformationonhowmanyargumentsthecommandstake,andinwhatformats,whereitispermitted,andsoforth.Thatinformationissufficienttoallowtheservertoinvokemostcommand-handlingfunctionswithpre-parsedarguments.Withoutfurtherado,let's

lookattheAddTypecommandhandler,whichlookslikethis(theAddEncodingcommandlooksbasicallythesame,andwon'tbeshownhere):

char*add_type(cmd_parms*cmd,mime_dir_config*m,char*ct,

char*ext)

{

if(*ext=='.')++ext;

ap_table_set(m->forced_types,ext,ct);

returnNULL;

}

Thiscommandhandlerisunusuallysimple.Asyoucansee,ittakesfourarguments,twoofwhicharepre-parsedarguments,thethirdbeingtheper-directoryconfigurationstructureforthemoduleinquestion,andthefourthbeingapointertoacmd_parmsstructure.Thatstructurecontainsabunchofargumentswhicharefrequentlyofusetosome,butnotall,commands,includingaresourcepool(fromwhichmemorycanbeallocated,andtowhichcleanupsshouldbetied),andthe(virtual)serverbeingconfigured,fromwhichthemodule'sper-serverconfigurationdatacanbeobtainedifrequired.

Anotherwayinwhichthisparticularcommandhandlerisunusuallysimpleisthattherearenoerrorconditionswhichitcanencounter.Iftherewere,itcouldreturnanerrormessageinsteadofNULL;thiscausesanerrortobeprintedoutontheserver'sstderr,followedbyaquickexit,ifitisinthemainconfigfiles;fora.htaccessfile,thesyntaxerrorisloggedintheservererrorlog(alongwithanindicationofwhereitcamefrom),andtherequestisbouncedwithaservererrorresponse(HTTPerrorstatus,code500).

TheMIMEmodule'scommandtablehasentriesforthesecommands,whichlooklikethis:

command_recmime_cmds[]={

{"AddType",add_type,NULL,OR_FILEINFO,TAKE2,

"amimetypefollowedbyafileextension"},

{"AddEncoding",add_encoding,NULL,OR_FILEINFO,TAKE2,

"anencoding(e.g.,gzip),followedbyafileextension"

},

{NULL}

};

Theentriesinthesetablesare:

ThenameofthecommandThefunctionwhichhandlesita(void*)pointer,whichispassedinthecmd_parmsstructuretothecommandhandler---thisisusefulincasemanysimilarcommandsarehandledbythesamefunction.Abitmaskindicatingwherethecommandmayappear.TherearemaskbitscorrespondingtoeachAllowOverrideoption,andanadditionalmaskbit,RSRC_CONF,indicatingthatthecommandmayappearintheserver'sownconfigfiles,butnotinany.htaccessfile.Aflagindicatinghowmanyargumentsthecommandhandlerwantspre-parsed,andhowtheyshouldbepassedin.TAKE2indicatestwopre-parsedarguments.OtheroptionsareTAKE1,whichindicatesonepre-parsedargument,FLAG,whichindicatesthattheargumentshouldbeOnorOff,andispassedinasabooleanflag,RAW_ARGS,whichcausestheservertogivethecommandtheraw,unparsedarguments(everythingbutthecommandnameitself).ThereisalsoITERATE,whichmeansthatthehandlerlooksthesameasTAKE1,butthatifmultipleargumentsarepresent,itshouldbecalledmultipletimes,andfinallyITERATE2,whichindicatesthatthecommandhandlerlookslikeaTAKE2,butifmoreargumentsarepresent,thenitshouldbecalledmultipletimes,holdingthefirstargumentconstant.

Finally,wehaveastringwhichdescribestheargumentsthatshouldbepresent.Iftheargumentsintheactualconfigfilearenotasrequired,thisstringwillbeusedtohelpgiveamorespecificerrormessage.(YoucansafelyleavethisNULL).

Finally,havingsetthisallup,wehavetouseit.Thisisultimatelydoneinthemodule'shandlers,specificallyforitsfile-typinghandler,whichlooksmoreorlesslikethis;notethattheper-directoryconfigurationstructureisextractedfromtherequest_rec'sper-directoryconfigurationvectorbyusingtheap_get_module_configfunction.

intfind_ct(request_rec*r)

{

inti;

char*fn=ap_pstrdup(r->pool,r->filename);

mime_dir_config*conf=(mime_dir_config*)

ap_get_module_config(r->per_dir_config,&mime_module);

char*type;

if(S_ISDIR(r->finfo.st_mode)){

r->content_type=DIR_MAGIC_TYPE;

returnOK;

}

if((i=ap_rind(fn,'.'))<0)returnDECLINED;

++i;

if((type=ap_table_get(conf->encoding_types,&fn[i])))

{

r->content_encoding=type;

/*gobacktopreviousextensiontotrytouseitasa

type*/

fn[i-1]='\0';

if((i=ap_rind(fn,'.'))<0)returnOK;

++i;

}

if((type=ap_table_get(conf->forced_types,&fn[i])))

{

r->content_type=type;

}

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

returnOK;

}

Sidenotes--per-serverconfiguration,virtualservers,etc.Thebasicideasbehindper-servermoduleconfigurationarebasicallythesameasthoseforper-directoryconfiguration;thereisacreationfunctionandamergefunction,thelatterbeinginvokedwhereavirtualserverhaspartiallyoverriddenthebaseserverconfiguration,andacombinedstructuremustbecomputed.(Aswithper-directoryconfiguration,thedefaultifnomergefunctionisspecified,andamoduleisconfiguredinsomevirtualserver,isthatthebaseconfigurationissimplyignored).

Theonlysubstantialdifferenceisthatwhenacommandneedstoconfiguretheper-serverprivatemoduledata,itneedstogotothecmd_parmsdatatogetatit.Here'sanexample,fromthealiasmodule,whichalsoindicateshowasyntaxerrorcanbereturned(notethattheper-directoryconfigurationargumenttothecommandhandlerisdeclaredasadummy,sincethemoduledoesn'tactuallyhaveper-directoryconfigdata):

char*add_redirect(cmd_parms*cmd,void*dummy,char*f,char

*url)

{

server_rec*s=cmd->server;

alias_server_conf*conf=(alias_server_conf*)

ap_get_module_config(s->module_config,&alias_module);

alias_entry*new=ap_push_array(conf->redirects);

if(!ap_is_url(url))return"Redirecttonon-URL";

new->fake=f;new->real=url;

returnNULL;

}

Modules|Directives|FAQ|Glossary|Sitemap

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>DeveloperDocumentation

DebuggingMemoryAllocationinAPR

Theallocationmechanism'swithinAPRhaveanumberofdebuggingmodesthatcanbeusedtoassistinfindingmemoryproblems.Thisdocumentdescribesthemodesavailableandgivesinstructionsonactivatingthem.

Availabledebuggingoptions

AllocationDebugging-ALLOC_DEBUG

Debuggingsupport:Definethistoenablecodewhichhelpsdetectre-useoffree()dmemoryandothersuchnonsense.

Thetheoryissimple.TheFILL_BYTE(0xa5)iswrittenoverallmalloc'dmemoryaswereceiveit,andiswrittenovereverythingthatwefreeupduringaclear_pool.WecheckthatblocksonthefreelistalwayshavetheFILL_BYTEinthem,andwecheckduringpalloc()thatthebytesstillhaveFILL_BYTEinthem.IfyoueverseegarbageURLsorwhatnotcontaininglotsof0xa5sthenyouknowsomethinguseddatathat'sbeenfreedoruninitialized.

MallocSupport-ALLOC_USE_MALLOC

Ifdefinedallallocationswillbedonewithmalloc()andfree()dappropriatelyattheend.

ThisisintendedtobeusedwithsomethinglikeElectricFenceorPurifytohelpdetectmemoryproblems.Notethatifyou'reusingefencethenyoushouldalsoaddinALLOC_DEBUG.Butdon'taddinALLOC_DEBUGifyou'reusingPurifybecauseALLOC_DEBUGwouldhidealltheuninitializedreaderrorsthatPurifycandiagnose.

PoolDebugging-POOL_DEBUG

Thisisintendedtodetectcaseswherethewrongpoolisusedwhenassigningdatatoanobjectinanotherpool.

Inparticular,itcausesthetable_{set,add,merge}nroutinestocheckthattheirargumentsaresafefortheapr_table_tthey'rebeingplacedin.Itcurrentlyonlyworkswiththeunixmultiprocessmodel,butcouldbeextendedtoothers.

TableDebugging-MAKE_TABLE_PROFILE

Providediagnosticinformationaboutmake_table()callswhicharepossiblytoosmall.

Thisrequiresarecentgccwhichsupports__builtin_return_address().Theerror_logoutputwillbeamessagesuchas:

table_push:apr_table_tcreatedby0x804d874hitlimitof10

Usel*0x804d874tofindthesourcethatcorrespondsto.Itindicatesthataapr_table_tallocatedbyacallatthataddresshaspossiblytoosmallaninitialapr_table_tsizeguess.

AllocationStatistics-ALLOC_STATS

Providesomestatisticsonthecostofallocations.

Thisrequiresabitofanunderstandingofhowalloc.cworks.

AllowableCombinations

Notalltheoptionsoutlinedabovecanbeactivatedatthesametime.thefollowingtablegivesmoreinformation.

ALLOCDEBUG

ALLOCUSEMALLOC

POOLDEBUG

MAKETABLEPROFILE

ALLOCSTATS

ALLOCDEBUG

- No Yes Yes Yes

ALLOCUSEMALLOC

No - No No No

POOLDEBUG

Yes No - Yes Yes

MAKETABLEPROFILE

Yes No Yes - Yes

ALLOCSTATS

Yes No Yes Yes -

Additionallythedebuggingoptionsarenotsuitableformulti-threadedversionsoftheserver.Whentryingtodebugwiththeseoptionstheservershouldbestartedinsingleprocessmode.

ActivatingDebuggingOptions

Thevariousoptionsfordebuggingmemoryarenowenabledintheapr_general.hheaderfileinAPR.Thevariousoptionsareenabledbyuncommentingthedefinefortheoptionyouwishtouse.Thesectionofthecodecurrentlylookslikethis(containedinsrclib/apr/include/apr_pools.h)

/*

#defineALLOC_DEBUG

#definePOOL_DEBUG

#defineALLOC_USE_MALLOC

#defineMAKE_TABLE_PROFILE

#defineALLOC_STATS

*/

typedefstructap_pool_t{

unionblock_hdr*first;

unionblock_hdr*last;

structcleanup*cleanups;

structprocess_chain*subprocesses;

structap_pool_t*sub_pools;

structap_pool_t*sub_next;

structap_pool_t*sub_prev;

structap_pool_t*parent;

char*free_first_avail;

#ifdefALLOC_USE_MALLOC

void*allocation_list;

#endif

#ifdefPOOL_DEBUG

structap_pool_t*joined;

#endif

int(*apr_abort)(intretcode);

structdatastruct*prog_data;

}ap_pool_t;

Toenableallocationdebuggingsimplymovethe#defineALLOC_DEBUGabovethestartofthecommentsblockandrebuildtheserver.

Note

Inordertousethevariousoptionstheservermustberebuiltaftereditingtheheaderfile.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>DeveloperDocumentation

DocumentingApache2.0

Apache2.0usesDoxygentodocumenttheAPIsandglobalvariablesinthecode.ThiswillexplainthebasicsofhowtodocumentusingDoxygen.

BriefDescription

Tostartadocumentationblock,use/**Toendadocumentationblock,use*/

Inthemiddleoftheblock,therearemultipletagswecanuse:

Descriptionofthisfunctionspurpose

@paramparameter_namedescription

@returndescription

@deffuncsignatureofthefunction

Thedeffuncisnotalwaysnecessary.DoxyGendoesnothaveafullparserinit,soanyprototypethatuseamacrointhereturntypedeclarationistoocomplexforscandoc.Thosefunctionsrequireadeffunc.Anexample(using&gt;ratherthan>):

/**

*returnthefinalelementofthepathname

*@parampathnameThepathtogetthefinalelementof

*@returnthefinalelementofthepath

*@tipExamples:

*<pre>

*"/foo/bar/gum"-&gt;"gum"

*"/foo/bar/gum/"-&gt;""

*"gum"-&gt;"gum"

*"wi\\n32\\stuff"-&gt;"stuff"

*</pre>

*@deffuncconstchar*ap_filename_of_pathname(constchar

*pathname)

*/

Atthetopoftheheaderfile,alwaysinclude:

/**

*@packageNameoflibraryheader

*/

DoxygenusesanewHTMLfileforeachpackage.TheHTMLfilesarenamed{Name_of_library_header}.html,sotrytobeconcisewithyournames.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ForafurtherdiscussionofthepossibilitiespleaserefertotheDoxygensite.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>DeveloperDocumentation

Apache2.0HookFunctions

Warning

Thisdocumentisstillindevelopmentandmaybepartiallyoutofdate.

Ingeneral,ahookfunctionisonethatApachewillcallatsomepointduringtheprocessingofarequest.Modulescanprovidefunctionsthatarecalled,andspecifywhentheygetcalledincomparisontoothermodules.

Creatingahookfunction

Inordertocreateanewhook,fourthingsneedtobedone:

DeclarethehookfunctionUsetheAP_DECLARE_HOOKmacro,whichneedstobegiventhereturntypeofthehookfunction,thenameofthehook,andthearguments.Forexample,ifthehookreturnsanintandtakesarequest_rec*andanintandiscalleddo_something,thendeclareitlikethis:

AP_DECLARE_HOOK(int,do_something,(request_rec*r,intn))

Thisshouldgoinaheaderwhichmoduleswillincludeiftheywanttousethehook.

CreatethehookstructureEachsourcefilethatexportsahookhasaprivatestructurewhichisusedtorecordthemodulefunctionsthatusethehook.Thisisdeclaredasfollows:

APR_HOOK_STRUCT(

APR_HOOK_LINK(do_something)

...

)

ImplementthehookcallerThesourcefilethatexportsthehookhastoimplementafunctionthatwillcallthehook.Therearecurrentlythreepossiblewaystodothis.Inallcases,thecallingfunctioniscalledap_run_hookname().

VoidhooksIfthereturnvalueofahookisvoid,thenallthehooksarecalled,

andthecallerisimplementedlikethis:

AP_IMPLEMENT_HOOK_VOID(do_something,(request_rec*r,intn),

(r,n))

Thesecondandthirdargumentsarethedummyargumentdeclarationandthedummyargumentsastheywillbeusedwhencallingthehook.Inotherwords,thismacroexpandstosomethinglikethis:

voidap_run_do_something(request_rec*r,intn)

{

...

do_something(r,n);

}

HooksthatreturnavalueIfthehookreturnsavalue,thenitcaneitherberununtilthefirsthookthatdoessomethinginteresting,likeso:

AP_IMPLEMENT_HOOK_RUN_FIRST(int,do_something,(request_rec*r,

intn),(r,n),DECLINED)

ThefirsthookthatdoesnotreturnDECLINEDstopstheloopanditsreturnvalueisreturnedfromthehookcaller.NotethatDECLINEDisthetraditionApachehookreturnmeaning"Ididn'tdoanything",butitcanbewhateversuitsyou.

Alternatively,allhookscanberununtilanerroroccurs.Thisboilsdowntopermittingtworeturnvalues,oneofwhichmeans"Ididsomething,anditwasOK"andtheothermeaning"Ididnothing".Thefirstfunctionthatreturnsavalueotherthanoneofthosetwostopstheloop,anditsreturnisthereturnvalue.Declaretheselikeso:

AP_IMPLEMENT_HOOK_RUN_ALL(int,do_something,(request_rec*r,

intn),(r,n),OK,DECLINED)

Again,OKandDECLINEDarethetraditionalvalues.Youcanusewhatyouwant.

CallthehookcallersAtappropriatemomentsinthecode,callthehookcaller,likeso:

intn,ret;

request_rec*r;

ret=ap_run_do_something(r,n);

Hookingthehook

Amodulethatwantsahooktobecalledneedstodotwothings.

ImplementthehookfunctionIncludetheappropriateheader,anddefineastaticfunctionofthecorrecttype:

staticintmy_something_doer(request_rec*r,intn)

{

...

returnOK;

}

AddahookregisteringfunctionDuringinitialisation,Apachewillcalleachmoduleshookregisteringfunction,whichisincludedinthemodulestructure:

staticvoidmy_register_hooks()

{

ap_hook_do_something(my_something_doer,NULL,NULL,

HOOK_MIDDLE);

}

modeMODULE_VAR_EXPORTmy_module=

{

...

my_register_hooks/*registerhooks*/

};

ControllinghookcallingorderIntheexampleabove,wedidn'tusethethreeargumentsinthehookregistrationfunctionthatcontrolcallingorder.Therearetwomechanismsfordoingthis.Thefirst,rathercrude,method,allowsustospecifyroughlywherethehookisrunrelativetoothermodules.Thefinalargumentcontrolthis.Therearethreepossiblevalues:HOOK_FIRST,HOOK_MIDDLEandHOOK_LAST.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Allmodulesusinganyparticularvaluemayberuninanyorderrelativetoeachother,but,ofcourse,allmodulesusingHOOK_FIRSTwillberunbeforeHOOK_MIDDLEwhicharebeforeHOOK_LAST.Modulesthatdon'tcarewhentheyarerunshoulduseHOOK_MIDDLE.(IspacedtheseoutsopeoplecoulddostufflikeHOOK_FIRST-2togetinslightlyearlier,butisthiswise?-Ben)

Notethattherearetwomorevalues,HOOK_REALLY_FIRSTandHOOK_REALLY_LAST.Theseshouldonlybeusedbythehookexporter.

Theothermethodallowsfinercontrol.Whenamoduleknowsthatitmustberunbefore(orafter)someothermodules,itcanspecifythembyname.Thesecond(third)argumentisaNULL-terminatedarrayofstringsconsistingofthenamesofmodulesthatmustberunbefore(after)thecurrentmodule.Forexample,supposewewant"mod_xyz.c"and"mod_abc.c"torunbeforewedo,thenwe'dhookasfollows:

staticvoidregister_hooks()

{

staticconstchar*constaszPre[]={"mod_xyz.c",

"mod_abc.c",NULL};

ap_hook_do_something(my_something_doer,aszPre,NULL,

HOOK_MIDDLE);

}

Notethatthesortusedtoachievethisisstable,soorderingsetbyHOOK_ORDERispreserved,asfarasispossible.

BenLaurie,15thAugust1999

Modules|Directives|FAQ|Glossary|Sitemap

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >DeveloperDocumentation

Apache1.3Apache2.0

mod_mmap_staticApache2.0

apr_status_t apr_status_tARP_SUCCESS

apr_pool_t*p

apr_pool_t*plog

apr_pool_t*ptemp

server_rec*s

APR

poolbecomesapr_pool_ttablebecomesapr_table_t

mod_mmap_static:

staticvoidregister_hooks(void)

{

staticconstchar*constaszPre[]={"http_core.c",NULL};

ap_hook_post_config(mmap_post_config,NULL,NULL,HOOK_MIDDLE);

ap_hook_translate_name(mmap_static_xlat,aszPre,NULL,HOOK_LAST);

};

post_config(?

ap_hook_phase_name(function_name,predecessors,successors,

position);

HOOK_FIRST

HOOK_MIDDLE

HOOK_LAST

mod_mmap_static post_configmmap_static_xlatcore aszPre

moduleMODULE_VAR_EXPORTmodule_name_module=

{

STANDARD_MODULE_STUFF,

/*initializer*/

/*dirconfigcreater*/

/*dirmerger---defaultistooverride*/

/*serverconfig*/

/*mergeserverconfig*/

/*commandhandlers*/

/*handlers*/

/*filenametranslation*/

/*check_user_id*/

/*checkauth*/

/*checkaccess*/

/*type_checker*/

/*fixups*/

/*logger*/

/*headerparser*/

/*child_init*/

/*child_exit*/

/*postread-request*/

};

moduleMODULE_VAR_EXPORTmodule_name_module=

{

STANDARD20_MODULE_STUFF,

/*createper-directoryconfigstructures*/

/*mergeper-directoryconfigstructures*/

/*createper-serverconfigstructures*/

/*mergeper-serverconfigstructures*/

/*commandhandlers*/

/*handlers*/

/*registerhooks*/

};

:

/**/

/**/

/**/

/**/

/**/

/**/

/**/

/**/

/**/

/*apr_table_t*/

/**/

/**/

ap_hook_post_config

( _init)

ap_hook_http_method

(HTTP())

ap_hook_open_logs

()

ap_hook_auth_checker

()

ap_hook_access_checker

()

ap_hook_check_user_id

(ID)

ap_hook_default_port

()

ap_hook_pre_connection

(accept)

ap_hook_process_connection

()

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

ap_hook_child_init

()

ap_hook_create_request

(??)

ap_hook_fixups

()

ap_hook_handler

()

ap_hook_header_parser

(post_read_request)

ap_hook_insert_filter

()

ap_hook_log_transaction

()

ap_hook_optional_fn_retrieve

()

ap_hook_post_read_request

()

ap_hook_quick_handler

ap_hook_translate_name

(URI)

ap_hook_type_checker

()

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>DeveloperDocumentation

RequestProcessinginApache2.0

Warning

Warning-thisisafirst(fast)draftthatneedsfurtherrevision!

SeveralchangesinApache2.0affecttheinternalrequestprocessingmechanics.Moduleauthorsneedtobeawareofthesechangessotheymaytakeadvantageoftheoptimizationsandsecurityenhancements.

Thefirstmajorchangeistothesubrequestandredirectmechanisms.TherewereanumberofdifferentcodepathsinApache1.3toattempttooptimizesubrequestorredirectbehavior.Aspatcheswereintroducedto2.0,theseoptimizations(andtheserverbehavior)werequicklybrokenduetothisduplicationofcode.Allduplicatecodehasbeenfoldedbackintoap_process_request_internal()topreventthecodefromfallingoutofsyncagain.

Thismeansthatmuchoftheexistingcodewas'unoptimized'.ItistheApacheHTTPProject'sfirstgoaltocreatearobustandcorrectimplementationoftheHTTPserverRFC.Additionalgoalsincludesecurity,scalabilityandoptimization.Newmethodsweresoughttooptimizetheserver(beyondtheperformanceofApache1.3)withoutintroducingfragileorinsecurecode.

TheRequestProcessingCycle

Allrequestspassthroughap_process_request_internal()inrequest.c,includingsubrequestsandredirects.Ifamoduledoesn'tpassgeneratedrequeststhroughthiscode,theauthoriscautionedthatthemodulemaybebrokenbyfuturechangestorequestprocessing.

Tostreamlinerequests,themoduleauthorcantakeadvantageofthehooksofferedtodropoutoftherequestcycleearly,ortobypasscoreApachehookswhichareirrelevant(andcostlyintermsofCPU.)

TheRequestParsingPhase

UnescapestheURLTherequest'sparsed_uripathisunescaped,onceandonlyonce,atthebeginningofinternalrequestprocessing.

Thisstepisbypassediftheproxyreqflagisset,ortheparsed_uri.pathelementisunset.Themodulehasnofurthercontrolofthisone-timeunescapeoperation,eitherfailingtounescapeormultiplyunescapingtheURLleadstosecurityreprecussions.

StripsParentandThisElementsfromtheURIAll/../and/./elementsareremovedbyap_getparents().Thishelpstoensurethepathis(nearly)absolutebeforetherequestprocessingcontinues.

Thisstepcannotbebypassed.

InitialURILocationWalkEveryrequestissubjecttoanap_location_walk()call.Thisensuresthat<Location>sectionsareconsistentlyenforcedforallrequests.Iftherequestisaninternalredirectorasub-request,itmayborrowsomeoralloftheprocessingfromthepreviousorparentrequest'sap_location_walk,sothisstepisgenerallyveryefficientafterprocessingthemainrequest.

translate_nameModulescandeterminethefilename,oralterthegivenURIinthisstep.Forexample,mod_vhost_aliaswilltranslatetheURI'spathintotheconfiguredvirtualhost,mod_aliaswilltranslatethepathtoanaliaspath,andiftherequestfallsbackonthecore,the

DocumentRootisprependedtotherequestresource.

IfallmodulesDECLINEthisphase,anerror500isreturnedtothebrowser,anda"couldn'ttranslatename"errorisloggedautomatically.

Hook:map_to_storageAfterthefileorcorrectURIwasdetermined,theappropriateper-dirconfigurationsaremergedtogether.Forexample,mod_proxycomparesandmergestheappropriate<Proxy>sections.IftheURIisnothingmorethanalocal(non-proxy)TRACErequest,thecorehandlestherequestandreturnsDONE.IfnomoduleanswersthishookwithOKorDONE,thecorewillruntherequestfilenameagainstthe<Directory>and<Files>sections.Iftherequest'filename'isn'tanabsolute,legalfilename,anoteissetforlatertermination.

URILocationWalkEveryrequestishardenedbyasecondap_location_walk()call.Thisreassuresthatatranslatedrequestisstillsubjectedtotheconfigured<Location>sections.Therequestagainborrowssomeoralloftheprocessingfromitspreviouslocation_walkabove,sothisstepisalmostalwaysveryefficientunlessthetranslatedURImappedtoasubstantiallydifferentpathorVirtualHost.

Hook:header_parserThemainrequestthenparsestheclient'sheaders.Thispreparestheremainingrequestprocessingstepstobetterservetheclient'srequest.

TheSecurityPhase

NeedsDocumentation.Codeis:

switch(ap_satisfies(r)){

caseSATISFY_ALL:

caseSATISFY_NOSPEC:

if((access_status=ap_run_access_checker(r))!=0){

returndecl_die(access_status,"checkaccess",r);

}

if(ap_some_auth_required(r)){

if(((access_status=ap_run_check_user_id(r))!=0)

||!ap_auth_type(r)){

returndecl_die(access_status,ap_auth_type(r)

?"checkuser.Nouserfile?"

:"performauthentication.AuthTypenotset!",

r);

}

if(((access_status=ap_run_auth_checker(r))!=0)

||!ap_auth_type(r)){

returndecl_die(access_status,ap_auth_type(r)

?"checkaccess.Nogroupsfile?"

:"performauthentication.AuthTypenotset!",

r);

}

}

break;

caseSATISFY_ANY:

if(((access_status=ap_run_access_checker(r))!=0)){

if(!ap_some_auth_required(r)){

returndecl_die(access_status,"checkaccess",r);

}

if(((access_status=ap_run_check_user_id(r))!=0)

||!ap_auth_type(r)){

returndecl_die(access_status,ap_auth_type(r)

?"checkuser.Nouserfile?"

:"performauthentication.AuthTypenotset!",

r);

}

if(((access_status=ap_run_auth_checker(r))!=0)

||!ap_auth_type(r)){

returndecl_die(access_status,ap_auth_type(r)

?"checkaccess.Nogroupsfile?"

:"performauthentication.AuthTypenotset!",

r);

}

}

break;

}

ThePreparationPhase

Hook:type_checkerThemoduleshaveanopportunitytotesttheURIorfilenameagainstthetargetresource,andsetmimeinformationfortherequest.Bothmod_mimeandmod_mime_magicusethisphasetocomparethefilenameorcontentsagainsttheadministrator'sconfigurationandsetthecontenttype,language,charactersetandrequesthandler.Somemodulesmaysetuptheirfiltersorotherrequesthandlingparametersatthistime.

IfallmodulesDECLINEthisphase,anerror500isreturnedtothebrowser,anda"couldn'tfindtypes"errorisloggedautomatically.

Hook:fixupsManymodulesare'trounced'bysomephaseabove.Thefixupsphaseisusedbymodulesto'reassert'theirownershiporforcetherequest'sfieldstotheirappropriatevalues.Itisn'talwaysthecleanestmechanism,butoccasionallyit'stheonlyoption.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

TheHandlerPhase

Thisphaseisnotpartoftheprocessinginap_process_request_internal().Manymodulesprepareoneormoresubrequestspriortocreatinganycontentatall.Afterthecore,oramodulecallsap_process_request_internal()itthencallsap_invoke_handler()togeneratetherequest.

Hook:insert_filterModulesthattransformthecontentinsomewaycaninserttheirvaluesandoverrideexistingfilters,suchthatiftheuserconfiguredamoreadvancedfilterout-of-order,thenthemodulecanmoveitsorderasneedbe.Thereisnoresultcode,soactionsinthishookbetterbetrustedtoalwayssucceed.

Hook:handlerThemodulefinallyhasachancetoservetherequestinitshandlerhook.Notethatnoteverypreparedrequestissenttothehandlerhook.Manymodules,suchasmod_autoindex,willcreatesubrequestsforagivenURI,andthenneverservethesubrequest,butsimplylistsitfortheuser.Remembernottoputrequiredteardownfromthehooksaboveintothismodule,butregisterpoolcleanupsagainsttherequestpooltofreeresourcesasrequired.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>DeveloperDocumentation

HowfiltersworkinApache2.0

Warning

Thisisacut'npastejobfromanemail(<022501c1c529$f63a9550$7f00000a@KOJ>)andonlyreformattedforbetterreadability.It'snotuptodatebutmaybeagoodstartforfurtherresearch.

FilterTypes

Therearethreebasicfiltertypes(eachoftheseisactuallybrokendownintotwocategories,butthatcomeslater).

CONNECTION

Filtersofthistypearevalidforthelifetimeofthisconnection.(AP_FTYPE_CONNECTION,AP_FTYPE_NETWORK)

PROTOCOL

Filtersofthistypearevalidforthelifetimeofthisrequestfromthepointofviewoftheclient,thismeansthattherequestisvalidfromthetimethattherequestissentuntilthetimethattheresponseisreceived.(AP_FTYPE_PROTOCOL,AP_FTYPE_TRANSCODE)

RESOURCE

Filtersofthistypearevalidforthetimethatthiscontentisusedtosatisfyarequest.Forsimplerequests,thisisidenticaltoPROTOCOL,butinternalredirectsandsub-requestscanchangethecontentwithoutendingtherequest.(AP_FTYPE_RESOURCE,AP_FTYPE_CONTENT_SET)

Itisimportanttomakethedistinctionbetweenaprotocolandaresourcefilter.Aresourcefilteristiedtoaspecificresource,itmayalsobetiedtoheaderinformation,butthemainbindingistoaresource.Ifyouarewritingafilterandyouwanttoknowifitisresourceorprotocol,thecorrectquestiontoaskis:"Canthisfilterberemovediftherequestisredirectedtoadifferentresource?"Iftheanswerisyes,thenitisaresourcefilter.Ifitisno,thenitismostlikelyaprotocolorconnectionfilter.Iwon'tgointoconnectionfilters,becausetheyseemtobewellunderstood.Withthisdefinition,afewexamplesmighthelp:

ByterangeWehavecodedittobeinsertedforallrequests,anditisremovedifnotused.Becausethisfilterisactiveatthe

beginningofallrequests,itcannotberemovedifitisredirected,sothisisaprotocolfilter.

http_headerThisfilteractuallywritestheheaderstothenetwork.Thisisobviouslyarequiredfilter(exceptintheasiscasewhichisspecialandwillbedealtwithbelow)andsoitisaprotocolfilter.

DeflateTheadministratorconfiguresthisfilterbasedonwhichfilehasbeenrequested.Ifwedoaninternalredirectfromanautoindexpagetoanindex.htmlpage,thedeflatefiltermaybeaddedorremovedbasedonconfig,sothisisaresourcefilter.

Thefurtherbreakdownofeachcategoryintotwomorefiltertypesisstrictlyforordering.Wecouldremoveit,andonlyallowforonefiltertype,buttheorderwouldtendtobewrong,andwewouldneedtohackthingstomakeitwork.Currently,theRESOURCEfiltersonlyhaveonefiltertype,butthatshouldchange.

Howarefiltersinserted?

Thisisactuallyrathersimpleintheory,butthecodeiscomplex.Firstofall,itisimportantthateverybodyrealizethattherearethreefilterlistsforeachrequest,buttheyareallconcatenatedtogether.So,thefirstlistisr->output_filters,thenr->proto_output_filters,andfinallyr->connection->output_filters.ThesecorrespondtotheRESOURCE,PROTOCOL,andCONNECTIONfiltersrespectively.Theproblempreviously,wasthatweusedasinglylinkedlisttocreatethefilterstack,andwestartedfromthe"correct"location.ThismeansthatifIhadaRESOURCEfilteronthestack,andIaddedaCONNECTIONfilter,theCONNECTIONfilterwouldbeignored.Thisshouldmakesense,becausewewouldinserttheconnectionfilteratthetopofthec->output_filterslist,buttheendofr->output_filterspointedtothefilterthatusedtobeatthefrontofc->output_filters.Thisisobviouslywrong.Thenewinsertioncodeusesadoublylinkedlist.Thishastheadvantagethatweneverloseafilterthathasbeeninserted.Unfortunately,itcomeswithaseparatesetofheadaches.

Theproblemisthatwehavetwodifferentcaseswereweusesubrequests.Thefirstistoinsertmoredataintoaresponse.Thesecondistoreplacetheexistingresponsewithaninternalredirect.Thesearetwodifferentcasesandneedtobetreatedassuch.

Inthefirstcase,wearecreatingthesubrequestfromwithinahandlerorfilter.Thismeansthatthenextfiltershouldbepassedtomake_sub_requestfunction,andthelastresourcefilterinthesub-requestwillpointtothenextfilterinthemainrequest.Thismakessense,becausethesub-request'sdataneedstoflowthroughthesamesetoffiltersasthemainrequest.Agraphicalrepresentationmighthelp:

Default_handler-->includes_filter-->byterange-->...

Iftheincludesfiltercreatesasubrequest,thenwedon'twantthedatafromthatsub-requesttogothroughtheincludesfilter,becauseitmightnotbeSSIdata.So,thesubrequestaddsthefollowing:

Default_handler-->includes_filter-/->byterange-->...

/

Default_handler-->sub_request_core

WhathappensifthesubrequestisSSIdata?Well,that'seasy,theincludes_filterisaresourcefilter,soitwillbeaddedtothesubrequestinbetweentheDefault_handlerandthesub_request_corefilter.

Thesecondcaseforsub-requestsiswhenonesub-requestisgoingtobecometherealrequest.Thishappenswheneverasub-requestiscreatedoutsideofahandlerorfilter,andNULLispassedasthenextfiltertothemake_sub_requestfunction.

Inthiscase,theresourcefiltersnolongermakesenseforthenewrequest,becausetheresourcehaschanged.So,insteadofstartingfromscratch,wesimplypointthefrontoftheresourcefiltersforthesub-requesttothefrontoftheprotocolfiltersfortheoldrequest.Thismeansthatwewon'tloseanyoftheprotocolfilters,neitherwillwetrytosendthisdatathroughafilterthatshouldn'tseeit.

Theproblemisthatweareusingadoubly-linkedlistforourfilterstacksnow.But,youshouldnoticethatitispossiblefortwoliststointersectinthismodel.So,youdoyouhandlethepreviouspointer?Thisisaverydifficultquestiontoanswer,becausethereisno"right"answer,eithermethodisequallyvalid.Ilookedatwhyweusethepreviouspointer.Theonlyreasonforitistoallowforeasieradditionofnewservers.Withthatbeingsaid,thesolutionI

chosewastomakethepreviouspointeralwaysstayontheoriginalrequest.

Thiscausessomemorecomplexlogic,butitworksforallcases.Myconcerninhavingitmovetothesub-request,isthatforthemorecommoncase(whereasub-requestisusedtoadddatatoaresponse),themainfilterchainwouldbewrong.Thatdidn'tseemlikeagoodideatome.

Asis

Thefinaltopic.:-)Mod_Asisisabitofahack,butthehandlerneedstoremoveallfiltersexceptforconnectionfilters,andsendthedata.Ifyouareusingmod_asis,allotherbetsareoff.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Explanations

Theabsolutelylastpointisthatthereasonthiscodewassohardtogetright,wasbecausewehadhackedsomuchtoforceittowork.Iwrotemostofthehacksoriginally,soIamverymuchtoblame.However,nowthatthecodeisright,Ihavestartedtoremovesomehacks.Mostpeopleshouldhaveseenthatthereset_filtersandadd_required_filtersfunctionsaregone.Thoseinsertedprotocollevelfiltersforerrorconditions,infact,bothfunctionsdidthesamething,oneaftertheother,itwasreallystrange.Becausewedon'tloseprotocolfiltersforerrorcasesanymore,thosehackswentaway.TheHTTP_HEADER,Content-length,andByterangefiltersarealladdedintheinsert_filtersphase,becauseiftheywereaddedearlier,wehadsomeinterestinginteractions.Now,thosecouldallbemovedtobeinsertedwiththeHTTP_IN,CORE,andCORE_INfilters.Thatwouldmakethecodeeasiertofollow.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

Glossary

ThisglossarydefinessomeofthecommonterminologyrelatedtoApacheinparticular,andwebservingingeneral.Moreinformationoneachconceptisprovidedinthelinks.

Definitions

AccessControlTherestrictionofaccesstonetworkrealms.InanApachecontextusuallytherestrictionofaccesstocertainURLs.See:Authentication,Authorization,andAccessControl

AlgorithmAnunambiguousformulaorsetofrulesforsolvingaprobleminafinitenumberofsteps.AlgorithmsforencryptionareusuallycalledCiphers.

APacheeXtensionTool(apxs)Aperlscriptthataidsincompiling→modulesourcesintoDynamicSharedObjects(→DSOs)andhelpsinstallthemintheApacheWebserver.See:ManualPage:apxs

AuthenticationThepositiveidentificationofanetworkentitysuchasaserver,aclient,orauser.See:Authentication,Authorization,andAccessControl

CertificateAdatarecordusedforauthenticatingnetworkentitiessuchasaserveroraclient.AcertificatecontainsX.509informationpiecesaboutitsowner(calledthesubject)andthesigning→CertificationAuthority(calledtheissuer),plustheowner's→publickeyandthesignaturemadebytheCA.NetworkentitiesverifythesesignaturesusingCAcertificates.See:SSL/TLSEncryption

CertificateSigningRequest(CSR)Anunsigned→certificateforsubmissiontoa→CertificationAuthority,whichsignsitwiththe→PrivateKeyoftheirCACertificate.OncetheCSRissigned,itbecomesarealcertificate.See:SSL/TLSEncryption

CertificationAuthority(CA)Atrustedthirdpartywhosepurposeistosigncertificatesfornetworkentitiesithasauthenticatedusingsecuremeans.OthernetworkentitiescancheckthesignaturetoverifythataCAhasauthenticatedthebearerofacertificate.See:SSL/TLSEncryption

CipherAnalgorithmorsystemfordataencryption.ExamplesareDES,IDEA,RC4,etc.See:SSL/TLSEncryption

CiphertextTheresultafter→Plaintextispassedthrougha→Cipher.See:SSL/TLSEncryption

CommonGatewayInterface(CGI)Astandarddefinitionforaninterfacebetweenawebserverandanexternalprogramthatallowstheexternalprogramtoservicerequests.TheinterfacewasoriginallydefinedbyNCSAbutthereisalsoanRFCproject.See:DynamicContentwithCGI

ConfigurationDirectiveSee:→Directive

ConfigurationFileAtextfilecontaining→DirectivesthatcontroltheconfigurationofApache.See:ConfigurationFiles

CONNECTAnHTTP→methodforproxyingrawdatachannelsoverHTTP.Itcanbeusedtoencapsulateotherprotocols,suchastheSSLprotocol.

ContextAnareainthe→configurationfileswherecertaintypesof

→directivesareallowed.See:TermsUsedtoDescribeApacheDirectives

DigitalSignatureAnencryptedtextblockthatvalidatesacertificateorotherfile.A→CertificationAuthoritycreatesasignaturebygeneratingahashofthePublicKeyembeddedinaCertificate,thenencryptingthehashwithitsownPrivateKey.OnlytheCA'spublickeycandecryptthesignature,verifyingthattheCAhasauthenticatedthenetworkentitythatownstheCertificate.See:SSL/TLSEncryption

DirectiveAconfigurationcommandthatcontrolsoneormoreaspectsofApache'sbehavior.Directivesareplacedinthe→ConfigurationFileSee:DirectiveIndex

DynamicSharedObject(DSO)→ModulescompiledseparatelyfromtheApachehttpdbinarythatcanbeloadedon-demand.See:DynamicSharedObjectSupport

EnvironmentVariable(env-variable)Namedvariablesmanagedbytheoperatingsystemshellandusedtostoreinformationandcommunicatebetweenprograms.Apachealsocontainsinternalvariablesthatarereferredtoasenvironmentvariables,butarestoredininternalApachestructures,ratherthanintheshellenvironment.See:EnvironmentVariablesinApache

Export-CrippledDiminishedincryptographicstrength(andsecurity)inordertocomplywiththeUnitedStates'ExportAdministrationRegulations(EAR).Export-crippledcryptographicsoftwareislimitedtoasmallkeysize,resultinginCiphertextwhichusuallycanbedecryptedbybruteforce.

See:SSL/TLSEncryption

FilterAprocessthatisappliedtodatathatissentorreceivedbytheserver.Inputfiltersprocessdatasentbytheclienttotheserver,whileoutputfiltersprocessdocumentsontheserverbeforetheyaresenttotheclient.Forexample,theINCLUDESoutputfilterprocessesdocumentsfor→ServerSideIncludes.See:Filters

Fully-QualifiedDomain-Name(FQDN)Theuniquenameofanetworkentity,consistingofahostnameandadomainnamethatcanresolvetoanIPaddress.Forexample,wwwisahostname,example.comisadomainname,andwww.example.comisafully-qualifieddomainname.

HandlerAninternalApacherepresentationoftheactiontobeperformedwhenafileiscalled.Generally,fileshaveimplicithandlers,basedonthefiletype.Normally,allfilesaresimplyservedbytheserver,butcertainfiletypesare"handled"separately.Forexample,thecgi-scripthandlerdesignatesfilestobeprocessedas→CGIs.See:Apache'sHandlerUse

HashAmathematicalone-way,irreversablealgorithmgeneratingastringwithfixed-lengthfromanotherstringofanylength.Differentinputstringswillusuallyproducedifferenthashes(dependingonthehashfunction).

HeaderThepartofthe→HTTPrequestandresponsethatissentbeforetheactualcontent,andthatcontainsmeta-informationdescribingthecontent.

.htaccess

A→configurationfilethatisplacedinsidethewebtreeandappliesconfiguration→directivestothedirectorywhereitisplacedandallsub-directories.Despiteitsname,thisfilecanholdalmostanytypeofdirective,notjustaccess-controldirectives.See:ConfigurationFiles

httpd.confThemainApache→configurationfile.Thedefaultlocationis/usr/local/apache2/conf/httpd.conf,butitmaybemovedusingrun-timeorcompile-timeconfiguration.See:ConfigurationFiles

HyperTextTransferProtocol(HTTP)ThestandardtransmissionprotocolusedontheWorldWideWeb.Apacheimplementsversion1.1oftheprotocol,referredtoasHTTP/1.1anddefinedbyRFC2616.

HTTPSTheHyperTextTransferProtocol(Secure),thestandardencryptedcommunicationmechanismontheWorldWideWeb.ThisisactuallyjustHTTPover→SSL.See:SSL/TLSEncryption

MethodInthecontextof→HTTP,anactiontoperformonaresource,specifiedontherequestlinebytheclient.SomeofthemethodsavailableinHTTPareGET,POST,andPUT.

MessageDigestAhashofamessage,whichcanbeusedtoverifythatthecontentsofthemessagehavenotbeenalteredintransit.See:SSL/TLSEncryption

MIME-typeAwaytodescribethekindofdocumentbeingtransmitted.ItsnamecomesfromthatfactthatitsformatisborrowedfromtheMultipurposeInternetMailExtensions.Itconsistsofa

majortypeandaminortype,separatedbyaslash.Someexamplesaretext/html,image/gif,andapplication/octet-stream.InHTTP,theMIME-typeistransmittedintheContent-Type→header.See:mod_mime

ModuleAnindependentpartofaprogram.MuchofApache'sfunctionalityiscontainedinmodulesthatyoucanchoosetoincludeorexclude.ModulesthatarecompiledintotheApachehttpdbinaryarecalledstaticmodules,whilemodulesthatarestoredseparatelyandcanbeoptionallyloadedatrun-timearecalleddynamicmodulesor→DSOs.Modulesthatareincludedbydefaultarecalledbasemodules.ManymodulesareavailableforApachethatarenotdistributedaspartoftheApacheHTTPServer→tarball.Thesearereferredtoasthird-partymodules.See:ModuleIndex

ModuleMagicNumber(MMN)ModuleMagicNumberisaconstantdefinedintheApachesourcecodethatisassociatedwithbinarycompatibilityofmodules.ItischangedwheninternalApachestructures,functioncallsandothersignificantpartsofAPIchangeinsuchawaythatbinarycompatibilitycannotbeguaranteedanymore.OnMMNchange,allthirdpartymoduleshavetobeatleastrecompiled,sometimesevenslightlychangedinordertoworkwiththenewversionofApache.

OpenSSLTheOpenSourcetoolkitforSSL/TLSSeehttp://www.openssl.org/#

PassPhraseThewordorphrasethatprotectsprivatekeyfiles.Itpreventsunauthorizedusersfromencryptingthem.Usuallyit'sjustthe

secretencryption/decryptionkeyusedfor→Ciphers.See:SSL/TLSEncryption

PlaintextTheunencryptedtext.

PrivateKeyThesecretkeyina→PublicKeyCryptographysystem,usedtodecryptincomingmessagesandsignoutgoingones.See:SSL/TLSEncryption

ProxyAnintermediateserverthatsitsbetweentheclientandtheoriginserver.Itacceptsrequestsfromclients,transmitsthoserequestsontotheoriginserver,andthenreturnstheresponsefromtheoriginservertotheclient.Ifseveralclientsrequestthesamecontent,theproxycandeliverthatcontentfromitscache,ratherthanrequestingitfromtheoriginservereachtime,therebyreducingresponsetime.See:mod_proxy

PublicKeyThepubliclyavailablekeyina→PublicKeyCryptographysystem,usedtoencryptmessagesboundforitsownerandtodecryptsignaturesmadebyitsowner.See:SSL/TLSEncryption

PublicKeyCryptographyThestudyandapplicationofasymmetricencryptionsystems,whichuseonekeyforencryptionandanotherfordecryption.Acorrespondingpairofsuchkeysconstitutesakeypair.AlsocalledAsymmetricCryptography.See:SSL/TLSEncryption

RegularExpression(Regex)Awayofdescribingapatternintext-forexample,"allthewordsthatbeginwiththeletterA"or"every10-digitphonenumber"oreven"Everysentencewithtwocommasinit,and

nocapitalletterQ".RegularexpressionsareusefulinApachebecausetheyletyouapplycertainattributesagainstcollectionsoffilesorresourcesinveryflexibleways-forexample,all.gifand.jpgfilesunderany"images"directorycouldbewrittenas"/images/.*(jpg|gif)$".ApacheusesPerlCompatibleRegularExpressionsprovidedbythePCRElibrary.

ReverseProxyA→proxyserverthatappearstotheclientasifitisanoriginserver.Thisisusefultohidetherealoriginserverfromtheclientforsecurityreasons,ortoloadbalance.

SecureSocketsLayer(SSL)AprotocolcreatedbyNetscapeCommunicationsCorporationforgeneralcommunicationauthenticationandencryptionoverTCP/IPnetworks.ThemostpopularusageisHTTPS,i.e.theHyperTextTransferProtocol(HTTP)overSSL.See:SSL/TLSEncryption

ServerSideIncludes(SSI)AtechniqueforembeddingprocessingdirectivesinsideHTMLfiles.See:IntroductiontoServerSideIncludes

SessionThecontextinformationofacommunicationingeneral.

SSLeayTheoriginalSSL/TLSimplementationlibrarydevelopedbyEricA.Young

SymmetricCryptographyThestudyandapplicationofCiphersthatuseasinglesecretkeyforbothencryptionanddecryptionoperations.See:SSL/TLSEncryption

Tarball

Apackageoffilesgatheredtogetherusingthetarutility.Apachedistributionsarestoredincompressedtararchivesorusingpkzip.

TransportLayerSecurity(TLS)ThesuccessorprotocoltoSSL,createdbytheInternetEngineeringTaskForce(IETF)forgeneralcommunicationauthenticationandencryptionoverTCP/IPnetworks.TLSversion1isnearlyidenticalwithSSLversion3.See:SSL/TLSEncryption

UniformResourceLocator(URL)Thename/addressofaresourceontheInternet.Thisisthecommoninformaltermforwhatisformallycalleda→UniformResourceIdentifier.URLsareusuallymadeupofascheme,likehttporhttps,ahostname,andapath.AURLforthispageishttp://httpd.apache.org/docs/2.0/glossary.html

UniformResourceIdentifier(URI)Acompactstringofcharactersforidentifyinganabstractorphysicalresource.ItisformallydefinedbyRFC2396.URIsusedontheworld-widewebarecommonlyreferredtoas→URLs.

VirtualHostingServingmultiplewebsitesusingasingleinstanceofApache.IPvirtualhostingdifferentiatesbetweenwebsitesbasedontheirIPaddress,whilename-basedvirtualhostingusesonlythenameofthehostandcanthereforehostmanysitesonthesameIPaddress.See:ApacheVirtualHostdocumentation

X.509AnauthenticationcertificateschemerecommendedbytheInternationalTelecommunicationUnion(ITU-T)whichisusedforSSL/TLSauthentication.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

See:SSL/TLSEncryption

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

ApacheApache

A|B|C|D|E|F|G|H|I|K|L|M|N|O|P|R|S|T|U|V|W|X

AcceptMutexAcceptPathInfoAccessFileNameActionAddAltAddAltByEncodingAddAltByTypeAddCharsetAddDefaultCharsetAddDescriptionAddEncodingAddHandlerAddIconAddIconByEncodingAddIconByTypeAddInputFilterAddLanguageAddModuleInfoAddOutputFilterAddOutputFilterByTypeAddTypeAliasAliasMatchAllowAllowCONNECT

AllowEncodedSlashesAllowOverrideAnonymousAnonymous_AuthoritativeAnonymous_LogEmailAnonymous_MustGiveEmailAnonymous_NoUserIDAnonymous_VerifyEmailAssignUserIDAuthAuthoritativeAuthDBMAuthoritativeAuthDBMGroupFileAuthDBMTypeAuthDBMUserFileAuthDigestAlgorithmAuthDigestDomainAuthDigestFileAuthDigestGroupFileAuthDigestNcCheckAuthDigestNonceFormatAuthDigestNonceLifetimeAuthDigestQopAuthDigestShmemSizeAuthGroupFileAuthLDAPAuthoritativeAuthLDAPBindDNAuthLDAPBindPasswordAuthLDAPCharsetConfigAuthLDAPCompareDNOnServerAuthLDAPDereferenceAliasesAuthLDAPEnabledAuthLDAPFrontPageHackAuthLDAPGroupAttributeAuthLDAPGroupAttributeIsDN

AuthLDAPRemoteUserIsDNAuthLDAPUrlAuthNameAuthTypeAuthUserFileBrowserMatchBrowserMatchNoCaseBS2000AccountBufferedLogsCacheDefaultExpireCacheDirLengthCacheDirLevelsCacheDisableCacheEnableCacheExpiryCheckCacheFileCacheForceCompletionCacheGcCleanCacheGcDailyCacheGcIntervalCacheGcMemUsageCacheGcUnusedCacheIgnoreCacheControlCacheIgnoreHeadersCacheIgnoreNoLastModCacheLastModifiedFactorCacheMaxExpireCacheMaxFileSizeCacheMinFileSizeCacheNegotiatedDocsCacheRootCacheSizeCacheTimeMarginCGIMapExtension

CharsetDefaultCharsetOptionsCharsetSourceEncCheckSpellingChildPerUserIDContentDigestCookieDomainCookieExpiresCookieLogCookieNameCookieStyleCookieTrackingCoreDumpDirectoryCustomLogDavDavDepthInfinityDavLockDBDavMinTimeoutDefaultIconDefaultLanguageDefaultTypeDeflateBufferSizeDeflateCompressionLevelDeflateFilterNoteDeflateMemLevelDeflateWindowSizeDeny<Directory>DirectoryIndex<DirectoryMatch>DirectorySlashDocumentRootDumpIOInputDumpIOOutput

EnableExceptionHookEnableMMAPEnableSendfileErrorDocumentErrorLogExampleExpiresActiveExpiresByTypeExpiresDefaultExtendedStatusExtFilterDefineExtFilterOptionsFileETag<Files><FilesMatch>ForceLanguagePriorityForceTypeForensicLogGroupHeaderHeaderNameHostnameLookupsIdentityCheck<IfDefine><IfModule><IfVersion>ImapBaseImapDefaultImapMenuIncludeIndexIgnoreIndexOptionsIndexOrderDefaultISAPIAppendLogToErrors

ISAPIAppendLogToQueryISAPICacheFileISAPIFakeAsyncISAPILogNotSupportedISAPIReadAheadBufferKeepAliveKeepAliveTimeoutLanguagePriorityLDAPCacheEntriesLDAPCacheTTLLDAPConnectionTimeoutLDAPOpCacheEntriesLDAPOpCacheTTLLDAPSharedCacheFileLDAPSharedCacheSizeLDAPTrustedCALDAPTrustedCAType<Limit><LimitExcept>LimitInternalRecursionLimitRequestBodyLimitRequestFieldsLimitRequestFieldSizeLimitRequestLineLimitXMLRequestBodyListenListenBackLogLoadFileLoadModule<Location><LocationMatch>LockFileLogFormatLogLevel

MaxClientsMaxKeepAliveRequestsMaxMemFreeMaxRangesMaxRequestsPerChildMaxRequestsPerThreadMaxSpareServersMaxSpareThreadsMaxThreadsMaxThreadsPerChildMCacheMaxObjectCountMCacheMaxObjectSizeMCacheMaxStreamingBufferMCacheMinObjectSizeMCacheRemovalAlgorithmMCacheSizeMetaDirMetaFilesMetaSuffixMimeMagicFileMinSpareServersMinSpareThreadsMMapFileModMimeUsePathInfoMultiviewsMatchNameVirtualHostNoProxyNumServersNWSSLTrustedCertsNWSSLUpgradeableOptionsOrderPassEnvPidFile

ProtocolEcho<Proxy>ProxyBadHeaderProxyBlockProxyDomainProxyErrorOverrideProxyFtpDirCharsetProxyIOBufferSize<ProxyMatch>ProxyMaxForwardsProxyPassProxyPassReverseProxyPreserveHostProxyReceiveBufferSizeProxyRemoteProxyRemoteMatchProxyRequestsProxyTimeoutProxyViaReadmeNameReceiveBufferSizeRedirectRedirectMatchRedirectPermanentRedirectTempRemoveCharsetRemoveEncodingRemoveHandlerRemoveInputFilterRemoveLanguageRemoveOutputFilterRemoveTypeRequestHeaderRequire

RewriteBaseRewriteCondRewriteEngineRewriteLockRewriteLogRewriteLogLevelRewriteMapRewriteOptionsRewriteRuleRLimitCPURLimitMEMRLimitNPROCSatisfyScoreBoardFileScriptScriptAliasScriptAliasMatchScriptInterpreterSourceScriptLogScriptLogBufferScriptLogLengthScriptSockSecureListenSendBufferSizeServerAdminServerAliasServerLimitServerNameServerPathServerRootServerSignatureServerTokensSetEnvSetEnvIf

SetEnvIfNoCaseSetHandlerSetInputFilterSetOutputFilterSSIEndTagSSIErrorMsgSSIStartTagSSITimeFormatSSIUndefinedEchoSSLCACertificateFileSSLCACertificatePathSSLCARevocationFileSSLCARevocationPathSSLCertificateChainFileSSLCertificateFileSSLCertificateKeyFileSSLCipherSuiteSSLEngineSSLHonorCipherOrderSSLInsecureRenegotiationSSLMutexSSLOptionsSSLPassPhraseDialogSSLProtocolSSLProxyCACertificateFileSSLProxyCACertificatePathSSLProxyCARevocationFileSSLProxyCARevocationPathSSLProxyCipherSuiteSSLProxyEngineSSLProxyMachineCertificateFileSSLProxyMachineCertificatePathSSLProxyProtocolSSLProxyVerify

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

SSLProxyVerifyDepthSSLRandomSeedSSLRequireSSLRequireSSLSSLSessionCacheSSLSessionCacheTimeoutSSLUserNameSSLVerifyClientSSLVerifyDepthStartServersStartThreadsSuexecUserGroupThreadLimitThreadsPerChildThreadStackSizeTimeOutTraceEnableTransferLogTypesConfigUnsetEnvUseCanonicalNameUserUserDirVirtualDocumentRootVirtualDocumentRootIP<VirtualHost>VirtualScriptAliasVirtualScriptAliasIPWin32DisableAcceptExXBitHack

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0 >

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

Apache

1 2()

3,4

A|B|C|D|E|F|G|H|I|K|L|M|N|O|P|R|

S|T|U|V|W|X

s

v

d

h .htaccess

C CoreM MPMB BaseE ExtensionX Experimental

AcceptMutexdefault|method defaultacceptApache

AcceptPathInfoOn|Off|Default Default

AccessFileNamefilename[filename]... .htaccess

Actionaction-typecgi-scriptCGI

AddAltstringfile[file]...

AddAltByEncodingstringMIME-encoding[MIME-encoding]...MIME

AddAltByTypestringMIME-type[MIME-type]...MIME

AddCharsetcharsetextension[extension]...

AddDefaultCharsetOn|Off|charset Off

AddDescriptionstringfile[file]...

AddEncodingMIME-encextension[extension]...

AddHandlerhandler-nameextension[extension]...

AddIconiconname[name]...

AddIconByEncodingiconMIME-encoding[MIME-encoding]...MIME

AddIconByTypeiconMIME-type[MIME-type]...MIME

AddInputFilterfilter[;filter...]extension[extension]...

AddLanguageMIME-langextension[extension]...

AddModuleInfomodule-namestringserver-info

AddOutputFilterfilter[;filter...]extension[extension]...

AddOutputFilterByTypefilter[;filter...]MIME-type[MIME-type]...MIME-type

AddTypeMIME-typeextension[extension]...

AliasURL-pathfile-path|directory-pathURL

AliasMatchregexfile-path|directory-pathURL

Allowfromall|host|env=env-variable[host|env=env-variable]...

AllowCONNECTport[port]... 443563PortsthatareallowedtoCONNECTthroughtheproxy

AllowEncodedSlashesOn|Off OffURL

AllowOverrideAll|None|directive-type[directive-type]...

All

.htaccess

Anonymoususer[user]...SpecifiesuserIDsthatareallowedaccesswithoutpasswordverification

Anonymous_AuthoritativeOn|Off OffConfiguresifauthorizationwillfall-throughtoothermethods

Anonymous_LogEmailOn|Off OnSetswhetherthepasswordenteredwillbeloggedintheerrorlog

Anonymous_MustGiveEmailOn|Off OnSpecifieswhetherblankpasswordsareallowed

Anonymous_NoUserIDOn|Off OffSetswhethertheuserIDfieldmaybeempty

Anonymous_VerifyEmailOn|Off OffSetswhethertocheckthepasswordfieldforacorrectlyformattedemailaddress

AssignUserIDuser-idgroup-idTieavirtualhosttoauserandgroupID

AuthAuthoritativeOn|Off On

AuthDBMAuthoritativeOn|Off OnSetswhetherauthenticationandauthorizationwillbepassedontolowerlevelmodules

AuthDBMGroupFilefile-pathSetsthenameofthedatabasefilecontainingthelistofusergroupsforauthentication

AuthDBMType default

default|SDBM|GDBM|NDBM|DBSetsthetypeofdatabasefilethatisusedtostorepasswords

AuthDBMUserFilefile-pathSetsthenameofadatabasefilecontainingthelistofusersandpasswordsforauthentication

AuthDigestAlgorithmMD5|MD5-sess MD5Selectsthealgorithmusedtocalculatethechallengeandresponsehasesindigestauthentication

AuthDigestDomainURI[URI]...URIsthatareinthesameprotectionspacefordigestauthentication

AuthDigestFilefile-pathLocationofthetextfilecontainingthelistofusersandencodedpasswordsfordigestauthentication

AuthDigestGroupFilefile-pathNameofthetextfilecontainingthelistofgroupsfordigestauthentication

AuthDigestNcCheckOn|Off OffEnablesordisablescheckingofthenonce-countsentbytheserver

AuthDigestNonceFormatformatDetermineshowthenonceisgenerated

AuthDigestNonceLifetimeseconds 300Howlongtheservernonceisvalid

AuthDigestQopnone|auth|auth-int[auth|auth-int]

auth

Determinesthequality-of-protectiontouseindigestauthentication

AuthDigestShmemSizesize 1000Theamountofsharedmemorytoallocateforkeepingtrackofclients

AuthGroupFilefile-path

AuthLDAPAuthoritativeon|off onPreventotherauthenticationmodulesfromauthenticatingtheuserifthisonefails

AuthLDAPBindDNdistinguished-nameOptionalDNtouseinbindingtotheLDAPserver

AuthLDAPBindPasswordpasswordPasswordusedinconjuctionwiththebindDN

AuthLDAPCharsetConfigfile-pathLanguagetocharsetconversionconfigurationfile

AuthLDAPCompareDNOnServeron|off onUsetheLDAPservertocomparetheDNs

AuthLDAPDereferenceAliasesnever|searching|finding|always

Always

Whenwillthemodulede-referencealiases

AuthLDAPEnabledon|off onTurnonoroffLDAPauthentication

AuthLDAPFrontPageHackon|off offAllowLDAPauthenticationtoworkwithMSFrontPage

AuthLDAPGroupAttributeattributeLDAPattributesusedtocheckforgroupmembership

AuthLDAPGroupAttributeIsDNon|off onUsetheDNoftheclientusernamewhencheckingforgroupmembership

AuthLDAPRemoteUserIsDNon|off offUsetheDNoftheclientusernametosettheREMOTE_USERenvironmentvariable

AuthLDAPUrlurlURLspecifyingtheLDAPsearchparameters

AuthNameauth-domainHTTP(:realm)

AuthTypeBasic|Digest

AuthUserFilefile-path

BrowserMatchregex[!]env-variable[=value][[!]env-variable[=value]]...HTTPUser-Agent

BrowserMatchNoCaseregex[!]env-variable[=value][[!]env-variable[=value]]...HTTPUser-Agent

BS2000AccountaccountBS2000

BufferedLogsOn|Off OffBufferlogentriesinmemorybeforewritingtodisk

CacheDefaultExpireseconds 3600(onehour)Thedefaultdurationtocacheadocumentwhennoexpirydateisspecified.

CacheDirLengthlength 2Thenumberofcharactersinsubdirectorynames

CacheDirLevelslevels 3Thenumberoflevelsofsubdirectoriesinthecache.

CacheDisableurl-stringDisablecachingofspecifiedURLs

CacheEnablecache_typeurl-stringEnablecachingofspecifiedURLsusingaspecifiedstoragemanager

CacheExpiryCheckOn|Off OnIndicatesifthecacheobservesExpiresdateswhenseekingfiles

CacheFilefile-path[file-path]...Cachealistoffilehandlesatstartuptime

CacheForceCompletionPercentage 60Percentageofdocumentserved,afterwhichtheserverwillcompletecachingthefileeveniftherequestiscancelled.

CacheGcCleanhoursurl-string ?ThetimetoretainunchangedcachedfilesthatmatchaURL

CacheGcDailytime ?Therecurringtimeeachdayforgarbagecollectiontoberun.(24hourclock)

CacheGcIntervalhoursTheintervalbetweengarbagecollectionattempts.

CacheGcMemUsageKBytes ?Themaximumkilobytesofmemoryusedforgarbagecollection

CacheGcUnusedhoursurl-string ?ThetimetoretainunreferencedcachedfilesthatmatchaURL.

CacheIgnoreCacheControlOn|Off OffIgnorethefactthattheclientrequestedthecontentnotbecached.

CacheIgnoreHeadersheader-string[header-string]...

None

DonotstorethegivenHTTPheader(s)inthecache.

CacheIgnoreNoLastModOn|Off OffIgnorethefactthataresponsehasnoLastModifiedheader.

CacheLastModifiedFactorfloat 0.1ThefactorusedtocomputeanexpirydatebasedontheLastModifieddate.

CacheMaxExpireseconds 86400(oneday)Themaximumtimeinsecondstocacheadocument

CacheMaxFileSizebytes 1000000

Themaximumsize(inbytes)ofadocumenttobeplacedinthecache

CacheMinFileSizebytes 1Theminimumsize(inbytes)ofadocumenttobeplacedinthecache

CacheNegotiatedDocsOn|Off Off

CacheRootdirectoryThedirectoryrootunderwhichcachefilesarestored

CacheSizeKBytes 1000000ThemaximumamountofdiskspacethatwillbeusedbythecacheinKBytes

CacheTimeMargin? ?Theminimumtimemargintocacheadocument

CGIMapExtensioncgi-path.extensionCGI

CharsetDefaultcharsetCharsettotranslateinto

CharsetOptionsoption[option]... DebugLevel=0NoImpl+Configurescharsettranslationbehavior

CharsetSourceEnccharsetSourcecharsetoffiles

CheckSpellingon|off Offspelling

ChildPerUserIDuser-idgroup-idnum-childrenSpecifyuserIDandgroupIDforanumberofchildprocesses

ContentDigestOn|Off OffContent-MD5HTTP

CookieDomaindomainThedomaintowhichthetrackingcookieapplies

CookieExpiresexpiry-periodExpirytimeforthetrackingcookie

CookieLogfilename

CookieNametoken ApacheNameofthetrackingcookie

CookieStyleNetscape|Cookie|Cookie2|RFC2109|RFC2965

Netscape

Formatofthecookieheaderfield

CookieTrackingon|off offEnablestrackingcookie

CoreDumpDirectorydirectoryApache

CustomLogfile|pipeformat|nickname[env=[!]environment-variable]

DavOn|Off|provider-name OffWebDAVHTTP

DavDepthInfinityon|off offPROPFIND,Depth:Infinity

DavLockDBfile-pathDAV

DavMinTimeoutseconds 0DAV

DefaultIconurl-path

DefaultLanguageMIME-lang

DefaultTypeMIME-type text/plainMIME

DeflateBufferSizevalue 8096zlib

DeflateCompressionLevelvalue

DeflateFilterNote[type]notename

DeflateMemLevelvalue 9zlib

DeflateWindowSizevalue 15Zlib

Denyfromall|host|env=env-variable[host|env=env-variable]...

<Directorydirectory-path>...</Directory>

DirectoryIndexlocal-url[local-url]... index.html

<DirectoryMatchregex>...</DirectoryMatch>

DirectorySlashOn|Off On

DocumentRootdirectory-path /usr/local/apache/h+

DumpIOInputOn|Off OffDumpallinputdatatotheerrorlog

DumpIOOutputOn|Off OffDumpalloutputdatatotheerrorlog

EnableExceptionHookOn|Off Off

EnableMMAPOn|Off On

EnableSendfileOn|Off Onsendfile

ErrorDocumenterror-codedocument

ErrorLogfile-path|syslog[:facility] logs/error_log(Uni+

ExampleDemonstrationdirectivetoillustratetheApachemoduleAPI

ExpiresActiveOn|OffExpires

ExpiresByTypeMIME-type<code>secondsMIME Expires

ExpiresDefault<code>seconds

ExtendedStatusOn|Off Off

ExtFilterDefinefilternameparameters

Defineanexternalfilter

ExtFilterOptionsoption[option]... DebugLevel=0NoLogS+

Configuremod_ext_filteroptions

FileETagcomponent... INodeMTimeSizeETagHTTP

<Filesfilename>...</Files>

<FilesMatchregex>...</FilesMatch>

ForceLanguagePriorityNone|Prefer|Fallback[Prefer|Fallback]

Prefer

ForceTypeMIME-type|NoneMIME

ForensicLogfilename|pipeSetsfilenameoftheforensiclog

Groupunix-group #-1

Header[condition]set|append|add|unset|echoheader[value][env=[!]variable]ConfigureHTTPresponseheaders

HeaderNamefilename

HostnameLookupsOn|Off|Double OffIPDNS

IdentityCheckOn|Off OffRFC1413

<IfDefine[!]parameter-name>...</IfDefine>

<IfModule[!]module-name>...</IfModule>

<IfVersion[[!]operator]version>...</IfVersion>

ImapBasemap|referer|URL http://servername/Defaultbaseforimagemapfiles

ImapDefaulterror|nocontent|map|referer|URL nocontentDefaultactionwhenanimagemapiscalledwithcoordinatesthatarenotexplicitlymapped

ImapMenunone|formatted|semiformatted|unformattedActionifnocoordinatesaregivenwhencallinganimagemap

Includefile-path|directory-path

IndexIgnorefile[file]...

IndexOptions[+|-]option[[+|-]option]...

IndexOrderDefaultAscending|DescendingName|Date|Size|Description

AscendingName

ISAPIAppendLogToErrorson|off offRecordHSE_APPEND_LOG_PARAMETERrequestsfromISAPIextensionstotheerrorlog

ISAPIAppendLogToQueryon|off onRecordHSE_APPEND_LOG_PARAMETERrequestsfromISAPIextensionstothequeryfield

ISAPICacheFilefile-path[file-path]...ISAPI.dllfilestobeloadedatstartup

ISAPIFakeAsyncon|off offFakeasynchronoussupportforISAPIcallbacks

ISAPILogNotSupportedon|off offLogunsupportedfeaturerequestsfromISAPIextensions

ISAPIReadAheadBuffersize 49152SizeoftheReadAheadBuffersenttoISAPIextensions

KeepAliveOn|Off OnHTTP

KeepAliveTimeoutseconds 15

LanguagePriorityMIME-lang[MIME-lang]...variant

LDAPCacheEntriesnumber 1024

MaximumnumberofentriesintheprimaryLDAPcache

LDAPCacheTTLseconds 600Timethatcacheditemsremainvalid

LDAPConnectionTimeoutsecondsSpecifiesthesocketconnectiontimeoutinseconds

LDAPOpCacheEntriesnumber 1024NumberofentriesusedtocacheLDAPcompareoperations

LDAPOpCacheTTLseconds 600Timethatentriesintheoperationcacheremainvalid

LDAPSharedCacheFiledirectory-path/filenameSetsthesharedmemorycachefile

LDAPSharedCacheSizebytes 102400Sizeinbytesoftheshared-memorycache

LDAPTrustedCAdirectory-path/filenameSetsthefilecontainingthetrustedCertificateAuthoritycertificateordatabase

LDAPTrustedCATypetypeSpecifiesthetypeoftheCertificateAuthorityfile

<Limitmethod[method]...>...</Limit>HTTP

<LimitExceptmethod[method]...>...</LimitExcept>HTTP

LimitInternalRecursionnumber[number] 10

LimitRequestBodybytes 0HTTP

LimitRequestFieldsnumber 100HTTP

LimitRequestFieldsizebytesHTTP

LimitRequestLinebytes 8190HTTP

LimitXMLRequestBodybytes 1000000XML

Listen[IP-address:]portnumberlistenIP

ListenBacklogbacklog

LoadFilefilename[filename]...

LoadModulemodulefilename

<LocationURL-path|URL>...</Location>URL

<LocationMatchregex>...</LocationMatch>URL

LockFilefilename logs/accept.lock

LogFormatformat|nickname[nickname] "%h%l%u%t\"%r\"+

LogLevellevel warnErrorLog

MaxClientsnumber

MaxKeepAliveRequestsnumber 100

MaxMemFreeKBytes 0free()

MaxRangesdefault|unlimited|none|number-of-ranges

200

Numberofrangesallowedbeforereturningthecompleteresource

MaxRequestsPerChildnumber 10000

MaxRequestsPerThreadnumber 0Limitonthenumberofrequeststhatanindividualthreadwillhandleduringitslife

MaxSpareServersnumber 10

MaxSpareThreadsnumber

MaxThreadsnumber 2048Setthemaximumnumberofworkerthreads

MaxThreadsPerChildnumber 64Maximumnumberofthreadsperchildprocess

MCacheMaxObjectCountvalue 1009

MCacheMaxObjectSizebytes 10000()

MCacheMaxStreamingBuffersize_in_bytes of100000MCacheM+

MCacheMinObjectSizebytes 0()

MCacheRemovalAlgorithmLRU|GDSF GDSF

MCacheSizeKBytes 100

MetaDirdirectory .webNameofthedirectorytofindCERN-stylemetainformationfiles

MetaFileson|off offActivatesCERNmeta-fileprocessing

MetaSuffixsuffix .metaFilenamesuffixforthefilecontaingCERN-stylemetainformation

MimeMagicFilefile-pathEnableMIME-typedeterminationbasedonfilecontentsusingthespecifiedmagicfile

MinSpareServersnumber 5

MinSpareThreadsnumber

MMapFilefile-path[file-path]...Mapalistoffilesintomemoryatstartuptime

ModMimeUsePathInfoOn|Off Offpath_infomod_mime

MultiviewsMatchAny|NegotiatedOnly|Filters|Handlers

NegotiatedOnly

[Handlers|Filters]MultiViews

NameVirtualHostaddr[:port]IP

NoProxyhost[host]...Hosts,domains,ornetworksthatwillbeconnectedtodirectly

NumServersnumber 2Totalnumberofchildrenaliveatthesametime

NWSSLTrustedCertsfilename[filename]...Listofadditionalclientcertificates

NWSSLUpgradeable[IP-address:]portnumberAllowsaconnectiontobeupgradedtoanSSLconnectionuponrequest

Options[+|-]option[[+|-]option]... All

Orderordering Deny,AllowAllow Deny

PassEnvenv-variable[env-variable]...

PidFilefilename logs/httpd.pidID

ProtocolEchoOn|Off

<Proxywildcard-url>...</Proxy>Containerfordirectivesappliedtoproxiedresources

ProxyBadHeaderIsError|Ignore|StartBody IsErrorDetermineshowtohandlebadheaderlinesinaresponse

ProxyBlock*|word|host|domain[word|host|domain]...Words,hosts,ordomainsthatarebannedfrombeingproxied

ProxyDomainDomainDefaultdomainnameforproxiedrequests

ProxyErrorOverrideOn|Off OffOverrideerrorpagesforproxiedcontent

ProxyFtpDirCharsetcharacterset ISO-8859-1DefinethecharactersetforproxiedFTPlistings

ProxyIOBufferSizebytes 8192Determinesizeofinternaldatathroughputbuffer

<ProxyMatchregex>...</ProxyMatch>Containerfordirectivesappliedtoregular-expression-matchedproxiedresources

ProxyMaxForwardsnumber 10Maximiumnumberofproxiesthatarequestcanbeforwardedthrough

ProxyPass[path]!|urlMapsremoteserversintothelocalserverURL-space

ProxyPassReverse[path]urlAdjuststheURLinHTTPresponseheaderssentfromareverseproxiedserver

ProxyPreserveHostOn|Off OffUseincomingHostHTTPrequestheaderforproxyrequest

ProxyReceiveBufferSizebytes 0NetworkbuffersizeforproxiedHTTPandFTPconnections

ProxyRemotematchremote-serverRemoteproxyusedtohandlecertainrequests

ProxyRemoteMatchregexremote-serverRemoteproxyusedtohandlerequestsmatchedbyregularexpressions

ProxyRequestsOn|Off OffEnablesforward(standard)proxyrequests

ProxyTimeoutseconds 300Networktimeoutforproxiedrequests

ProxyViaOn|Off|Full|Block OffInformationprovidedintheViaHTTPresponseheaderforproxiedrequests

ReadmeNamefilename

ReceiveBufferSizebytes 0TCPreceivebuffersize

Redirect[status]URL-pathURLURL

RedirectMatch[status]regexURLURL

RedirectPermanentURL-pathURLURL

RedirectTempURL-pathURL

URL

RemoveCharsetextension[extension]...

RemoveEncodingextension[extension]...

RemoveHandlerextension[extension]...

RemoveInputFilterextension[extension]...

RemoveLanguageextension[extension]...

RemoveOutputFilterextension[extension]...

RemoveTypeextension[extension]...

RequestHeaderset|append|add|unsetheader[value[env=[!]variable]]ConfigureHTTPrequestheaders

Requireentity-name[entity-name]...

RewriteBaseURL-pathSetsthebaseURLforper-directoryrewrites

RewriteCondTestStringCondPatternDefinesaconditionunderwhichrewritingwilltakeplace

RewriteEngineon|off offEnablesordisablesruntimerewritingengine

RewriteLockfile-pathSetsthenameofthelockfileusedforRewriteMapsynchronization

RewriteLogfile-pathSetsthenameofthefileusedforloggingrewriteengineprocessing

RewriteLogLevelLevel 0Setstheverbosityofthelogfileusedbytherewriteengine

RewriteMapMapNameMapType:MapSourceDefinesamappingfunctionforkey-lookup

RewriteOptionsOptions MaxRedirects=10

Setssomespecialoptionsfortherewriteengine

RewriteRulePatternSubstitutionDefinesrulesfortherewritingengine

RLimitCPUseconds|max[seconds|max]ApacheCPU

RLimitMEMbytes|max[bytes|max]Apache

RLimitNPROCnumber|max[number|max]Apache

SatisfyAny|All All

ScoreBoardFilefile-path logs/apache_status

Scriptmethodcgi-scriptCGI

ScriptAliasURL-pathfile-path|directory-pathURLCGI

ScriptAliasMatchregexfile-path|directory-pathURLCGI

ScriptInterpreterSourceRegistry|Registry-Strict|Script

Script

CGI

ScriptLogfile-pathCGI

ScriptLogBufferbytes 1024PUTPOST

ScriptLogLengthbytes 10385760CGI

ScriptSockfile-path logs/cgisockCGI

SecureListen[IP-address:]portnumberCertificate-Name[MUTUAL]EnablesSSLencryptionforthespecifiedport

SendBufferSizebytes 0TCP

ServerAdminemail-address

ServerAliashostname[hostname]...

ServerLimitnumber

ServerNamefully-qualified-domain-name[:port]

ServerPathURL-pathURL

ServerRootdirectory-path /usr/local/apache

ServerSignatureOn|Off|EMail Off

ServerTokensMajor|Minor|Min[imal]|Prod[uctOnly]|OS|Full

Full

ServerHTTP

SetEnvenv-variablevalue

SetEnvIfattributeregex[!]env-variable[=value][[!]env-variable[=value]]...

SetEnvIfNoCaseattributeregex[!]env-variable[=value][[!]env-variable[=value]]...

SetHandlerhandler-name|None

SetInputFilterfilter[;filter...]POST

SetOutputFilterfilter[;filter...]

SSIEndTagtag "-->"include

SSIErrorMsgmessage "[anerroroccurred+

SSI

SSIStartTagtag "<!--#"include

SSITimeFormatformatstring "%A,%d-%b-%Y%H:%M+

SSIUndefinedEchostring "(none)"echo

SSLCACertificateFilefile-pathFileofconcatenatedPEM-encodedCACertificatesforClientAuth

SSLCACertificatePathdirectory-pathDirectoryofPEM-encodedCACertificatesforClientAuth

SSLCARevocationFilefile-pathFileofconcatenatedPEM-encodedCACRLsforClientAuth

SSLCARevocationPathdirectory-pathDirectoryofPEM-encodedCACRLsforClientAuth

SSLCertificateChainFilefile-pathFileofPEM-encodedServerCACertificates

SSLCertificateFilefile-pathServerPEM-encodedX.509Certificatefile

SSLCertificateKeyFilefile-pathServerPEM-encodedPrivateKeyfile

SSLCipherSuitecipher-spec ALL:!ADH:RC4+RSA:+H+

CipherSuiteavailablefornegotiationinSSLhandshake

SSLEngineon|off offSSLEngineOperationSwitch

SSLHonorCipherOrderflagOptiontoprefertheserver'scipherpreferenceorder

SSLInsecureRenegotiationflag offOptiontoenablesupportforinsecurerenegotiation

SSLMutextype noneSemaphoreforinternalmutualexclusionofoperations

SSLOptions[+|-]option...ConfigurevariousSSLenginerun-timeoptions

SSLPassPhraseDialogtype builtinTypeofpassphrasedialogforencryptedprivatekeys

SSLProtocol[+|-]protocol... allConfigureusableSSLprotocolflavors

SSLProxyCACertificateFilefile-pathFileofconcatenatedPEM-encodedCACertificatesforRemoteServerAuth

SSLProxyCACertificatePathdirectory-pathDirectoryofPEM-encodedCACertificatesforRemoteServerAuth

SSLProxyCARevocationFilefile-pathFileofconcatenatedPEM-encodedCACRLsforRemoteServerAuth

SSLProxyCARevocationPathdirectory-pathDirectoryofPEM-encodedCACRLsforRemoteServerAuth

SSLProxyCipherSuitecipher-spec ALL:!ADH:RC4+RSA:+H+

CipherSuiteavailablefornegotiationinSSLproxyhandshake

SSLProxyEngineon|off offSSLProxyEngineOperationSwitch

SSLProxyMachineCertificateFilefilenameFileofconcatenatedPEM-encodedclientcertificatesandkeystobeusedbytheproxy

SSLProxyMachineCertificatePathdirectoryDirectoryofPEM-encodedclientcertificatesandkeystobeusedbytheproxy

SSLProxyProtocol[+|-]protocol... allConfigureusableSSLprotocolflavorsforproxyusage

SSLProxyVerifylevel noneTypeofremoteserverCertificateverification

SSLProxyVerifyDepthnumber 1MaximumdepthofCACertificatesinRemoteServerCertificateverification

SSLRandomSeedcontextsource[bytes]PseudoRandomNumberGenerator(PRNG)seedingsource

SSLRequireexpressionAllowaccessonlywhenanarbitrarilycomplexbooleanexpressionistrue

SSLRequireSSLDenyaccesswhenSSLisnotusedfortheHTTPrequest

SSLSessionCachetype noneTypeoftheglobal/inter-processSSLSessionCache

SSLSessionCacheTimeoutseconds 300NumberofsecondsbeforeanSSLsessionexpiresintheSessionCache

SSLUserNamevarnameVariablenametodetermineusername

SSLVerifyClientlevel noneTypeofClientCertificateverification

SSLVerifyDepthnumber 1MaximumdepthofCACertificatesinClientCertificateverification

StartServersnumber

StartThreadsnumber

SuexecUserGroupUserGroupCGI

ThreadLimitnumber

ThreadsPerChildnumber

ThreadStackSizenumber 65536Determinethestacksizeforeachthread

TimeOutseconds 300

TraceEnable[on|off|extended] onDeterminesthebehaviouronTRACErequests

TransferLogfile|pipe

TypesConfigfile-path conf/mime.typesmime.types

UnsetEnvenv-variable[env-variable]...

UseCanonicalNameOn|Off|Dns On

Userunix-userid #-1ID

UserDirdirectory-filename public_html

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

VirtualDocumentRootinterpolated-directory|none

none

Dynamicallyconfigurethelocationofthedocumentrootforagivenvirtualhost

VirtualDocumentRootIPinterpolated-directory|none

none

Dynamicallyconfigurethelocationofthedocumentrootforagivenvirtualhost

<VirtualHostaddr[:port][addr[:port]]...>...</VirtualHost>IP

VirtualScriptAliasinterpolated-directory|none noneDynamicallyconfigurethelocationoftheCGIdirectoryforagivenvirtualhost

VirtualScriptAliasIPinterpolated-directory|none

none

Dynamicallyconfigurethelocationofthecgidirectoryforagivenvirtualhost

Win32DisableAcceptExaccept()AcceptEx

XBitHackon|off|full offSSI

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0

Apache

(MPMs)

MPM

coreApacheHTTP

mpm_common(MPM)

beosThisMulti-ProcessingModuleisoptimizedforBeOS.

leaderAnexperimentalvariantofthestandardworkerMPM

mpm_netwareMulti-ProcessingModuleimplementinganexclusivelythreadedwebserveroptimizedforNovellNetWare

mpmt_os2Hybridmulti-process,multi-threadedMPMforOS/2

perchildMulti-ProcessingModuleallowingfordaemonprocessesservingrequeststobeassignedavarietyofdifferentuserids

preforkfork

threadpoolYetanotherexperimentalvariantofthestandardworkerMPM

mpm_winntWindowsNT

worker

A|C|D|E|F|H|I|L|M|N|P|R|S|U|V

mod_accessIP

mod_actionsCGI

mod_alias

mod_asisHTTP

mod_auth

mod_auth_anonAllows"anonymous"useraccesstoauthenticatedareas

mod_auth_dbmProvidesforuserauthenticationusingDBMfiles

mod_auth_digestUserauthenticationusingMD5DigestAuthentication.

mod_auth_ldapAllowsanLDAPdirectorytobeusedtostorethedatabaseforHTTPBasicauthentication.

mod_autoindexUnix ls Win32 dir

mod_cacheContentcachekeyedtoURIs.

mod_cern_metaCERNhttpdmetafilesemantics

mod_cgiCGI

mod_cgidCGICGI

mod_charset_liteSpecifycharactersettranslationorrecoding

mod_dav(WebDAV)

mod_dav_fsmod_dav

mod_deflate

mod_dir

mod_disk_cacheContentcachestoragemanagerkeyedtoURIs

mod_dumpioDumpsallI/Otoerrorlogasdesired.

mod_echo

mod_envCGISSI

mod_exampleIllustratestheApachemoduleAPI

mod_expires Expires Cache-ControlHTTP

mod_ext_filterPasstheresponsebodythroughanexternalprogrambeforedeliverytotheclient

mod_file_cacheCachesastaticlistoffilesinmemory

mod_headersCustomizationofHTTPrequestandresponseheaders

mod_imapServer-sideimagemapprocessing

mod_includehtml(ServerSideIncludes)

mod_info

mod_isapiISAPIExtensionswithinApacheforWindows

mod_ldapLDAPconnectionpoolingandresultcachingservicesforusebyotherLDAPmodules

mod_log_config

mod_log_forensicForensicLoggingoftherequestsmadetotheserver

mod_logio

mod_mem_cacheURI

mod_mime ()(MIME)

mod_mime_magicDeterminestheMIMEtypeofafilebylookingatafewbytesofitscontents

mod_negotiation

mod_nw_sslEnableSSLencryptionforNetWare

mod_proxyHTTP/1.1proxy/gatewayserver

mod_proxy_connectmod_proxyextensionforCONNECTrequesthandling

mod_proxy_ftpFTPsupportmoduleformod_proxy

mod_proxy_httpHTTPsupportmoduleformod_proxy

mod_rewriteProvidesarule-basedrewritingenginetorewriterequestedURLsonthefly

mod_setenvif

mod_so

mod_spelingURL

mod_sslStrongcryptographyusingtheSecureSocketsLayer(SSL)andTransportLayerSecurity(TLS)protocols

mod_status

mod_suexecCGI

mod_unique_id

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

mod_userdir

mod_usertrackClickstreamloggingofuseractivityonasite

mod_version

mod_vhost_aliasProvidesfordynamicallyconfiguredmassvirtualhosting

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

FrequentlyAskedQuestions

ThelatestversionofthisFAQisalwaysavailablefromthemainApachewebsite,at<http://httpd.apache.org/docs/2.0/faq/>.Inaddition,youcanviewthisFAQallinonepageforeasysearchingandprinting.

SinceApache2.0isquitenew,wedon'tyetknowwhattheFrequentlyAskedQuestionswillbe.Whilethissectionfillsup,youshouldalsoconsulttheApache1.3FAQtoseeifyourquestionisansweredthere.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Topics

SupportWhatdoIdowhenIhaveproblems?

ErrorMessagesWhatdoesthiserrormessagemean?

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0

SiteMap

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

ApacheHTTP2.0

1.32.0Apache2.0ApacheLicense

ApacheHTTP

ApacheApache

Directory,Location,Files

URL

(DSO)

Apache(MPM)ApacheApache

suEXEC

URL

Apache

IP

VirtualHost

DNSApache

Apache

ApacheSSL/TLS

SSL/TLS:SSL/TLS:SSL/TLS:SSL/TLS:FAQ

CGIServerSideIncludes.htaccess

Apache

MicrosoftWindowsApacheMicrosoftWindowsApacheNovellNetWareApacheHPUXEBCDICApache

ApacheHTTP

:httpd:ab:apachectl:apxs:configure:dbmmanage:htdigest:htpasswd:logresolve:rotatelogs:suexec

Apache

FIN_WAIT_2Apache

Apache

Apache

ApacheApache

ApacheApacheMPMApacheMPMbeosApacheMPMleaderApacheMPMnetwareApacheMPMos2ApacheMPMperchildApacheMPMpreforkApacheMPMthreadpoolApacheMPMwinntApacheMPMworker

Apachemod_accessApachemod_actionsApachemod_aliasApachemod_asisApachemod_authApachemod_auth_anonApachemod_auth_dbmApachemod_auth_digestApachemod_auth_ldapApachemod_autoindexApachemod_cacheApachemod_cern_metaApachemod_cgiApachemod_cgidApachemod_charset_liteApachemod_davApachemod_dav_fsApachemod_deflate

Apachemod_dirApachemod_disk_cacheApachemod_dumpioApachemod_echoApachemod_envApachemod_exampleApachemod_expiresApachemod_ext_filterApachemod_file_cacheApachemod_headersApachemod_imapApachemod_includeApachemod_infoApachemod_isapiApachemod_ldapApachemod_log_configApachemod_log_forensicApachemod_logioApachemod_mem_cacheApachemod_mimeApachemod_mime_magicApachemod_negotiationApachemod_nw_sslApachemod_proxyApachemod_proxy_connectApachemod_proxy_ftpApachemod_proxy_httpApachemod_rewriteApachemod_setenvifApachemod_soApachemod_spelingApachemod_sslApachemod_statusApachemod_suexec

Apachemod_unique_idApachemod_userdirApachemod_usertrackApachemod_versionApachemod_vhost_alias

ApacheAPIAPRApache2.0Apache2.0Apache1.3Apache2.0Apache2.0Apache2.0

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

ServerandSupportingPrograms

ThispagedocumentsalltheexecutableprogramsincludedwiththeApacheHTTPServer.

Index

httpd

Apachehypertexttransferprotocolserver

apachectl

ApacheHTTPservercontrolinterface

ab

ApacheHTTPserverbenchmarkingtool

apxs

APacheeXtenSiontool

configure

Configurethesourcetree

dbmmanage

CreateandupdateuserauthenticationfilesinDBMformatforbasicauthentication

htdigest

Createandupdateuserauthenticationfilesfordigestauthentication

htdbm

ManipulateDBMpassworddatabases.

htpasswd

Createandupdateuserauthenticationfilesforbasicauthentication

logresolve

ResolvehostnamesforIP-addressesinApachelogfiles

rotatelogs

RotateApachelogswithouthavingtokilltheserver

suexec

SwitchUserForExec

OtherPrograms

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Supporttoolswithnoownmanualpage.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0

ApacheSSL/TLS

ApacheHTTP mod_ssl OpenSSLSecureSocktsLayerTransportLayerSecurityRalfS.Engelschallmod_ssl

Documentation

How-To

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

mod_ssl

mod_ssl

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0

Apache

Thistranslationmaybeoutofdate.ChecktheEnglishversionforrecentchanges.

1 (www.company1.comandwww.company2.comIP IPIP

ApacheIP 1.1Apache

Apache1.3

mod_vhost_alias

IP

(IP)IP(IP)

( )

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

<VirtualHost>

NameVirtualHost

ServerName

ServerAlias

ServerPath

Apache -S

/usr/local/apache2/bin/httpd-S

Apache IP

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

DeveloperDocumentationforApache2.0

ManyofthedocumentsontheseDeveloperpagesareliftedfromApache1.3'sdocumentation.WhiletheyareallbeingupdatedtoApache2.0,theyareindifferentstagesofprogress.Pleasebepatient,andpointoutanydiscrepanciesorerrorsonthedeveloper/pagesdirectlytothedev@httpd.apache.orgmailinglist.

Topics

Apache1.3APINotesApache2.0HookFunctionsRequestProcessinginApache2.0HowfiltersworkinApache2.0ConvertingModulesfromApache1.3toApache2.0DebuggingMemoryAllocationinAPRDocumentingApache2.0Apache2.0ThreadSafetyIssues

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

ExternalResources

ToolsprovidedbyIanHolsman:Apache2crossreferenceAutogeneratedApache2codedocumentation

ModuleDevelopmentTutorialsbyKevinO'DonnellIntegratingamoduleintotheApachebuildsystemHandlingconfigurationdirectives

SomenotesonApachemoduledevelopmentbyRyanBloom

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

ApacheMiscellaneousDocumentation

BelowisalistofadditionaldocumentationpagesthatapplytotheApachewebserverdevelopmentproject.

Warning

Someofthedocumentsbelowhavenotbeenfullyupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

HowtouseXSSIandNegotiationforcustomErrorDocuments

DescribesasolutionwhichusesXSSIandnegotiationtocustom-tailortheApacheErrorDocumentstotaste,addingtheadvantageofreturninginternationalizedversionsoftheerrormessagesdependingontheclient'slanguagepreferences.

FileDescriptoruseinApache

DescribeshowApacheusesfiledescriptorsandtalksaboutvariouslimitsimposedonthenumberofdescriptorsavailablebyvariousoperatingsystems.

FIN_WAIT_2

AdescriptionofthecausesofApacheprocessesgoingintotheFIN_WAIT_2state,andwhatyoucandoaboutit.

KnownClientProblems

AlistofproblemsinHTTPclientswhichcanbemitigatedbyApache.

PerformanceNotes-ApacheTuning

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Notesabouthowto(run-timeandcompile-time)configureApacheforhighestperformance.NotesexplainingwhyApachedoessomethings,andwhyitdoesn'tdootherthings(whichmakeitslower/faster).

SecurityTips

Some"do"s-and"don't"s-forkeepingyourApachewebsitesecure.

URLRewritingGuide

Thisdocumentsupplementsthemod_rewritereferencedocumentation.ItdescribeshowonecanuseApache'smod_rewritetosolvetypicalURL-basedproblemswebmastersareusuallyconfrontedwithinpractice.

ApacheTutorials

AlistofexternalresourceswhichhelptoaccomplishcommontaskswiththeApacheHTTPserver.

RelevantStandards

ThisdocumentactsasareferencepageformostoftherelevantstandardsthatApachefollows.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

PlatformSpecificNotes

MicrosoftWindows

UsingApacheThisdocumentexplainshowtoinstall,configureandrunApache2.0underMicrosoftWindows.

See:UsingApachewithMicrosoftWindows

CompilingApacheTherearemanyimportantpointsbeforeyoubegincompilingApache.Thisdocumentexplainthem.

See:CompilingApacheforMicrosoftWindows

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

OtherPlatforms

NovellNetWareThisdocumentexplainshowtoinstall,configureandrunApache2.0underNovellNetWare5.1andabove.

See:UsingApacheWithNovellNetWare

EBCDICVersion1.3oftheApacheHTTPServeristhefirstversionwhichincludesaporttoa(non-ASCII)mainframemachinewhichusestheEBCDICcharactersetasitsnativecodeset.

Warning:Thisdocumenthasnotbeenupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

See:TheApacheEBCDICPort

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

suexec-Switchuserbeforeexecutingexternalprograms

suexecisusedbytheApacheHTTPServertoswitchtoanotheruserbeforeexecutingCGIprograms.Inordertoachievethis,itmustrunasroot.SincetheHTTPdaemonnormallydoesn'trunasroot,thesuexecexecutableneedsthesetuidbitsetandmustbeownedbyroot.Itshouldneverbewritableforanyotherpersonthanroot.

Forfurtherinformationabouttheconceptsandandthesecuritymodelofsuexecpleaserefertothesuexecdocumentation(http://httpd.apache.org/docs/2.0/suexec.html).

Synopsissuexec-V

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Options

-V

Ifyouareroot,thisoptiondisplaysthecompileoptionsofsuexec.Forsecurityreasonsallconfigurationoptionsarechangeableonlyatcompiletime.

||FAQ||

ApacheHTTP2.0Apache>HTTP>>2.0

How-To/

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

||FAQ||

How-To/

:

CGICGI(CommonGatewayInterface) CGI Apache

: CGI:

.htaccess.htaccess

: .htaccess

ServerSideIncludesSSI(ServerSideIncludes)HTMLHTML

: ServerSideIncludes(SSI)

UserDir http://example.com/~username/ " username

UserDir

: ( public_html)

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>Programs

htdbm-ManipulateDBMpassworddatabases

htdbmisusedtomanipulatetheDBMformatfilesusedtostoreusernamesandpasswordforbasicauthenticationofHTTPusersviamod_auth_dbm.SeethedbmmanagedocumentationformoreinformationabouttheseDBMfiles.

Seealsohttpd

dbmmanage

mod_auth_dbm

Synopsishtdbm[-TDBTYPE][-c][-m|-d|-p|-s][

-t][-v][-x]filenameusername

htdbm-b[-TDBTYPE][-c][-m|-d|-p|-s

][-t][-v]filenameusernamepassword

htdbm-n[-c][-m|-d|-p|-s][-t][-v

]username

htdbm-nb[-c][-m|-d|-p|-s][-t][-

v]usernamepassword

htdbm-v[-TDBTYPE][-c][-m|-d|-p|-s

][-t][-v]filenameusername

htdbm-vb[-TDBTYPE][-c][-m|-d|-p|-s

][-t][-v]filenameusernamepassword

htdbm-x[-TDBTYPE][-m|-d|-p|-s]

filenameusername

htdbm-l[-TDBTYPE]

Options

-b

Usebatchmode;i.e.,getthepasswordfromthecommandlineratherthanpromptingforit.Thisoptionshouldbeusedwithextremecare,sincethepasswordisclearlyvisibleonthecommandline.

-c

Createthepasswdfile.Ifpasswdfilealreadyexists,itisrewrittenandtruncated.Thisoptioncannotbecombinedwiththe-noption.

-n

Displaytheresultsonstandardoutputratherthanupdatingadatabase.Thisoptionchangesthesyntaxofthecommandline,sincethepasswdfileargument(usuallythefirstone)isomitted.Itcannotbecombinedwiththe-coption.

-m

UseMD5encryptionforpasswords.OnWindows,NetwareandTPF,thisisthedefault.

-d

Usecrypt()encryptionforpasswords.ThedefaultonallplatformsbutWindows,NetwareandTPF.Thoughpossiblysupportedbyhtdbmonallplatforms,itisnotsupportedbythehttpdserveronWindows,NetwareandTPF.

-s

UseSHAencryptionforpasswords.Facilitatesmigrationfrom/toNetscapeserversusingtheLDAPDirectoryInterchangeFormat(ldif).

-p

Useplaintextpasswords.Thoughhtdbmwillsupportcreationonallplatforms,thehttpddaemonwillonlyacceptplaintextpasswordsonWindows,NetwareandTPF.

-l

Printeachoftheusernamesandcommentsfromthedatabaseonstdout.

-t

Interpretthefinalparameterasacomment.Whenthisoptionisspecified,anadditionalstringcanbeappendedtothecommandline;thisstringwillbestoredinthe"Comment"fieldofthedatabase,associatedwiththespecifiedusername.

-v

Verifytheusernameandpassword.Theprogramwillprintamessageindicatingwhetherthesuppliedpasswordisvalid.Ifthepasswordisinvalid,theprogramexitswitherrorcode3.

-x

Deleteuser.IftheusernameexistsinthespecifiedDBMfile,itwillbedeleted.

filename

ThefilenameoftheDBMformatfile.Usuallywithouttheextension.db,.pag,or.dir.If-cisgiven,theDBMfileiscreatedifitdoesnotalreadyexist,orupdatedifitdoesexist.

username

Theusernametocreateorupdateinpasswdfile.Ifusernamedoesnotexistinthisfile,anentryisadded.Ifitdoesexist,thepasswordischanged.

password

TheplaintextpasswordtobeencryptedandstoredintheDBMfile.Usedonlywiththe-bflag.

-TDBTYPE

TypeofDBMfile(SDBM,GDBM,DB,or"default").

Bugs

OneshouldbeawarethatthereareanumberofdifferentDBMfileformatsinexistence,andwithalllikelihood,librariesformorethanoneformatmayexistonyoursystem.ThethreeprimaryexamplesareSDBM,NDBM,GNUGDBM,andBerkeley/SleepycatDB2/3/4.Unfortunately,alltheselibrariesusedifferentfileformats,andyoumustmakesurethatthefileformatusedbyfilenameisthesameformatthathtdbmexpectstosee.htdbmcurrentlyhasnowayofdeterminingwhattypeofDBMfileitislookingat.Ifusedagainstthewrongformat,willsimplyreturnnothing,ormaycreateadifferentDBMfilewithadifferentname,oratworst,itmaycorrupttheDBMfileifyouwereattemptingtowritetoit.

OnecanusuallyusethefileprogramsuppliedwithmostUnixsystemstoseewhatformataDBMfileisin.

ExitStatus

htdbmreturnsazerostatus("true")iftheusernameandpasswordhavebeensuccessfullyaddedorupdatedintheDBMFile.htdbmreturns1ifitencounterssomeproblemaccessingfiles,2iftherewasasyntaxproblemwiththecommandline,3ifthepasswordwasenteredinteractivelyandtheverificationentrydidn'tmatch,4ifitsoperationwasinterrupted,5ifavalueistoolong(username,filename,password,orfinalcomputedrecord),6iftheusernamecontainsillegalcharacters(seetheRestrictionssection),and7ifthefileisnotavalidDBMpasswordfile.

Examples

htdbm/usr/local/etc/apache/.htdbm-usersjsmith

Addsormodifiesthepasswordforuserjsmith.Theuserispromptedforthepassword.IfexecutedonaWindowssystem,thepasswordwillbeencryptedusingthemodifiedApacheMD5algorithm;otherwise,thesystem'scrypt()routinewillbeused.Ifthefiledoesnotexist,htdbmwilldonothingexceptreturnanerror.

htdbm-c/home/doe/public_html/.htdbmjane

Createsanewfileandstoresarecordinitforuserjane.Theuserispromptedforthepassword.Ifthefileexistsandcannotberead,orcannotbewritten,itisnotalteredandhtdbmwilldisplayamessageandreturnanerrorstatus.

htdbm-mb/usr/web/.htdbm-alljonesPwd4Steve

Encryptsthepasswordfromthecommandline(Pwd4Steve)usingtheMD5algorithm,andstoresitinthespecifiedfile.

SecurityConsiderations

WebpasswordfilessuchasthosemanagedbyhtdbmshouldnotbewithintheWebserver'sURIspace--thatis,theyshouldnotbefetchablewithabrowser.

Theuseofthe-boptionisdiscouraged,sincewhenitisusedtheunencryptedpasswordappearsonthecommandline.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Restrictions

OntheWindowsandMPEplatforms,passwordsencryptedwithhtdbmarelimitedtonomorethan255charactersinlength.Longerpasswordswillbetruncatedto255characters.

TheMD5algorithmusedbyhtdbmisspecifictotheApachesoftware;passwordsencryptedusingitwillnotbeusablewithotherWebservers.

Usernamesarelimitedto255bytesandmaynotincludethecharacter:.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

Apachemod_rewrite

``Thegreatthingaboutmod_rewriteisitgivesyoualltheconfigurabilityandflexibilityofSendmail.Thedownsidetomod_rewriteisthatitgivesyoualltheconfigurabilityandflexibilityofSendmail.''

--BrianBehlendorfApacheGroup

``Despitethetonsofexamplesanddocs,mod_rewriteisvoodoo.Damnedcoolvoodoo,butstillvoodoo.''

--BrianMoorebem@news.cmc.net

Welcometomod_rewrite,theSwissArmyKnifeofURLmanipulation!

Thismoduleusesarule-basedrewritingengine(basedonaregular-expressionparser)torewriterequestedURLsonthefly.ItsupportsanunlimitednumberofrulesandanunlimitednumberofattachedruleconditionsforeachruletoprovideareallyflexibleandpowerfulURLmanipulationmechanism.TheURLmanipulationscandependonvarioustests,forinstanceservervariables,environmentvariables,HTTPheaders,timestampsandevenexternaldatabaselookupsinvariousformatscanbeusedtoachievegranularURLmatching.

ThismoduleoperatesonthefullURLs(includingthepath-infopart)bothinper-servercontext(httpd.conf)andper-directorycontext(.htaccess)andcanevengeneratequery-stringpartsonresult.Therewrittenresultcanleadtointernalsub-processing,externalrequestredirectionoreventoaninternalproxythroughput.

Butallthisfunctionalityandflexibilityhasitsdrawback:complexity.Sodon'texpecttounderstandthisentiremoduleinjustoneday.

Documentation

IntroductionTechnicaldetailsPracticalsolutionstocommonproblemsGlossary

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

mod_rewrite

Extensivedocumentationonthedirectivesprovidedbythismoduleisprovidedinthemod_rewritereferencedocumentation.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

URLRewritingGuide

Thisdocumentsupplementsthemod_rewritereferencedocumentation.ItdescribeshowonecanuseApache'smod_rewritetosolvetypicalURL-basedproblemswithwhichwebmastersarecommononyconfronted.WegivedetaileddescriptionsonhowtosolveeachproblembyconfiguringURLrewritingrulesets.

ATTENTION:Dependingonyourserverconfigurationitmaybenecessarytoslightlychangetheexamplesforyoursituation,e.g.addingthe[PT]flagwhenadditionallyusingmod_aliasandmod_userdir,etc.Orrewritingarulesettofitin.htaccesscontextinsteadofper-servercontext.Alwaystrytounderstandwhataparticularrulesetreallydoesbeforeyouuseit.Thisavoidsmanyproblems.

SeealsoModuledocumentationmod_rewriteintroductionTechnicaldetails

CanonicalURLs

Description:OnsomewebserverstherearemorethanoneURLforaresource.UsuallytherearecanonicalURLs(whichshouldbeactuallyusedanddistributed)andthosewhicharejustshortcuts,internalones,etc.IndependentofwhichURLtheusersuppliedwiththerequestheshouldfinallyseethecanonicaloneonly.

Solution:WedoanexternalHTTPredirectforallnon-canonicalURLstofixtheminthelocationviewoftheBrowserandforallsubsequentrequests.Intheexamplerulesetbelowwereplace/~userbythecanonical/u/userandfixamissingtrailingslashfor/u/user.

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

RewriteRule^/([uge])/([^/]+)$/$1/$2/[R]

CanonicalHostnames

Description:Thegoalofthisruleistoforcetheuseofaparticularhostname,inpreferencetootherhostnameswhichmaybeusedtoreachthesamesite.Forexample,ifyouwishtoforcetheuseofwww.example.cominsteadofexample.com,youmightuseavariantofthefollowingrecipe.

Solution:Forsitesrunningonaportotherthan80:

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]

Andforasiterunningonport80

RewriteCond%{HTTP_HOST}!^fully\.qualified\.domain\.name[NC]

RewriteCond%{HTTP_HOST}!^$

RewriteRule^/(.*)http://fully.qualified.domain.name/$1[L,R]

MovedDocumentRoot

Description:UsuallytheDocumentRootofthewebserverdirectlyrelatestotheURL"/".Butoftenthisdataisnotreallyoftop-levelpriority.Forexample,youmaywishforvisitors,onfirstenteringasite,togotoaparticularsubdirectory/about/.Thismaybeaccomplishedusingthefollowingruleset:

Solution:WeredirecttheURL/to/about/:

RewriteEngineon

RewriteRule^/$/about/[R]

NotethatthiscanalsobehandledusingtheRedirectMatchdirective:

RedirectMatch^/$http://example.com/e/www/

TrailingSlashProblem

Description:Thevastmajorityof"trailingslash"problemscanbedealtwithusingthetechniquesdiscussedintheFAQentry.However,occasionally,thereisaneedtousemod_rewritetohandleacasewhereamissingtrailingslashcausesaURLtofail.Thiscanhappen,forexample,afteraseriesofcomplexrewriterules.

Solution:Thesolutiontothissubtleproblemistolettheserveraddthetrailingslashautomatically.Todothiscorrectlywehavetouseanexternalredirect,sothebrowsercorrectlyrequestssubsequentimagesetc.Ifweonlydidainternalrewrite,thiswouldonlyworkforthedirectorypage,butwouldgowrongwhenanyimagesareincludedintothispagewithrelativeURLs,becausethebrowserwouldrequestanin-linedobject.Forinstance,arequestforimage.gifin/~quux/foo/index.htmlwouldbecome/~quux/image.gifwithouttheexternalredirect!

So,todothistrickwewrite:

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo$foo/[R]

Alternately,youcanputthefollowinginatop-level.htaccessfileinthecontentdirectory.Butnotethatthiscreatessomeprocessingoverhead.

RewriteEngineon

RewriteBase/~quux/

RewriteCond%{REQUEST_FILENAME}-d

RewriteRule^(.+[^/])$$1/[R]

MoveHomedirstoDifferentWebserver

Description:Manywebmastershaveaskedforasolutiontothefollowingsituation:Theywantedtoredirectjustallhomedirsonawebservertoanotherwebserver.Theyusuallyneedsuchthingswhenestablishinganewerwebserverwhichwillreplacetheoldoneovertime.

Solution:Thesolutionistrivialwithmod_rewrite.Ontheoldwebserverwejustredirectall/~user/anypathURLstohttp://newserver/~user/anypath.

RewriteEngineon

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

Searchpagesinmorethanonedirectory

Description:Sometimesitisnecessarytoletthewebserversearchforpagesinmorethanonedirectory.HereMultiViewsorothertechniquescannothelp.

Solution:Weprogramaexplicitrulesetwhichsearchesforthefilesinthedirectories.

RewriteEngineon

#firsttrytofinditincustom/...

#...andiffoundstopandbehappy:

RewriteCond/your/docroot/dir1/%{REQUEST_FILENAME}-f

RewriteRule^(.+)/your/docroot/dir1/$1[L]

#secondtrytofinditinpub/...

#...andiffoundstopandbehappy:

RewriteCond/your/docroot/dir2/%{REQUEST_FILENAME}-f

RewriteRule^(.+)/your/docroot/dir2/$1[L]

#elsegoonforotherAliasorScriptAliasdirectives,

#etc.

RewriteRule^(.+)-[PT]

SetEnvironmentVariablesAccordingToURLParts

Description:PerhapsyouwanttokeepstatusinformationbetweenrequestsandusetheURLtoencodeit.Butyoudon'twanttouseaCGIwrapperforallpagesjusttostripoutthisinformation.

Solution:WeusearewriteruletostripoutthestatusinformationandrememberitviaanenvironmentvariablewhichcanbelaterdereferencedfromwithinXSSIorCGI.ThiswayaURL/foo/S=java/bar/getstranslatedto/foo/bar/andtheenvironmentvariablenamedSTATUSissettothevalue"java".

RewriteEngineon

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

VirtualUserHosts

Description:Assumethatyouwanttoprovidewww.username.host.domain.comforthehomepageofusernameviajustDNSArecordstothesamemachineandwithoutanyvirtualhostsonthismachine.

Solution:ForHTTP/1.0requeststhereisnosolution,butforHTTP/1.1requestswhichcontainaHost:HTTPheaderwecanusethefollowingrulesettorewritehttp://www.username.host.com/anypathinternallyto/home/username/anypath:

RewriteEngineon

RewriteCond%{HTTP_HOST}^www\.[^.]+\.host\.com$

RewriteRule^(.+)%{HTTP_HOST}$1[C]

RewriteRule^www\.([^.]+)\.host\.com(.*)/home/$1$2

RedirectHomedirsForForeigners

Description:WewanttoredirecthomedirURLstoanotherwebserverwww.somewhere.comwhentherequestinguserdoesnotstayinthelocaldomainourdomain.com.Thisissometimesusedinvirtualhostcontexts.

Solution:Justarewritecondition:

RewriteEngineon

RewriteCond%{REMOTE_HOST}!^.+\.ourdomain\.com$

RewriteRule^(/~.+)http://www.somewhere.com/$1[R,L]

RedirectingAnchors

Description:Bydefault,redirectingtoanHTMLanchordoesn'twork,becausemod_rewriteescapesthe#character,turningitinto%23.This,inturn,breakstheredirection.

Solution:Usethe[NE]flagontheRewriteRule.NEstandsforNoEscape.

Time-DependentRewriting

Description:Whentricksliketime-dependentcontentshouldhappenalotofwebmastersstilluseCGIscriptswhichdoforinstanceredirectstospecializedpages.Howcanitbedoneviamod_rewrite?

Solution:TherearealotofvariablesnamedTIME_xxxforrewriteconditions.Inconjunctionwiththespeciallexicographiccomparisonpatterns<STRING,>STRINGand=STRINGwecandotime-dependentredirects:

RewriteEngineon

RewriteCond%{TIME_HOUR}%{TIME_MIN}>0700

RewriteCond%{TIME_HOUR}%{TIME_MIN}<1900

RewriteRule^foo\.html$foo.day.html

RewriteRule^foo\.html$foo.night.html

Thisprovidesthecontentoffoo.day.htmlundertheURLfoo.htmlfrom07:00-19:00andattheremainingtimethecontentsoffoo.night.html.Justanicefeatureforahomepage...

BackwardCompatibilityforYYYYtoXXXXmigration

Description:HowcanwemakeURLsbackwardcompatible(stillexistingvirtually)aftermigratingdocument.YYYYtodocument.XXXX,e.g.aftertranslatingabunchof.htmlfilesto.phtml?

Solution:Wejustrewritethenametoitsbasenameandtestforexistenceofthenewextension.Ifitexists,wetakethatname,elsewerewritetheURLtoitsoriginalstate.

#backwardcompatibilityrulesetfor

#rewritingdocument.htmltodocument.phtml

#whenandonlywhendocument.phtmlexists

#butnolongerdocument.html

RewriteEngineon

RewriteBase/~quux/

#parseoutbasename,butrememberthefact

RewriteRule^(.*)\.html$$1[C,E=WasHTML:yes]

#rewritetodocument.phtmlifexists

RewriteCond%{REQUEST_FILENAME}.phtml-f

RewriteRule^(.*)$$1.phtml[S=1]

#elsereversethepreviousbasenamecutout

RewriteCond%{ENV:WasHTML}^yes$

RewriteRule^(.*)$$1.html

ContentHandling

FromOldtoNew(intern)Description:

Assumewehaverecentlyrenamedthepagefoo.htmltobar.htmlandnowwanttoprovidetheoldURLforbackwardcompatibility.ActuallywewantthatusersoftheoldURLevennotrecognizethatthepageswasrenamed.

Solution:WerewritetheoldURLtothenewoneinternallyviathefollowingrule:

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo\.html$bar.html

FromOldtoNew(extern)Description:

Assumeagainthatwehaverecentlyrenamedthepagefoo.htmltobar.htmlandnowwanttoprovidetheoldURLforbackwardcompatibility.ButthistimewewantthattheusersoftheoldURLgethintedtothenewone,i.e.theirbrowsersLocationfieldshouldchange,too.

Solution:WeforceaHTTPredirecttothenewURLwhichleadstoachangeofthebrowsersandthustheusersview:

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo\.html$bar.html[R]

FromStatictoDynamicDescription:

Howcanwetransformastaticpagefoo.htmlintoadynamicvariantfoo.cgiinaseamlessway,i.e.withoutnoticebythebrowser/user.

Solution:WejustrewritetheURLtotheCGI-scriptandforcethecorrectMIME-typesoitgetsreallyrunasaCGI-script.Thiswayarequestto/~quux/foo.htmlinternallyleadstotheinvocationof/~quux/foo.cgi.

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo\.html$foo.cgi[T=application/x-httpd-cgi

AccessRestriction

BlockingofRobotsDescription:

Howcanweblockareallyannoyingrobotfromretrievingpagesofaspecificwebarea?A/robots.txtfilecontainingentriesofthe"RobotExclusionProtocol"istypicallynotenoughtogetridofsucharobot.

Solution:WeusearulesetwhichforbidstheURLsofthewebarea/~quux/foo/arc/(perhapsaverydeepdirectoryindexedareawheretherobottraversalwouldcreatebigserverload).Wehavetomakesurethatweforbidaccessonlytotheparticularrobot,i.e.justforbiddingthehostwheretherobotrunsisnotenough.Thiswouldblockusersfromthishost,too.WeaccomplishthisbyalsomatchingtheUser-AgentHTTPheaderinformation.

RewriteCond%{HTTP_USER_AGENT}^NameOfBadRobot.*

RewriteCond%{REMOTE_ADDR}^123\.45\.67\.[8-9]$

RewriteRule^/~quux/foo/arc/.+-[F]

BlockedInline-ImagesDescription:

Assumewehaveunderhttp://www.quux-corp.de/~quux/somepageswithinlinedGIFgraphics.Thesegraphicsarenice,soothersdirectlyincorporatethemviahyperlinkstotheirpages.Wedon'tlikethispracticebecauseitaddsuselesstraffictoourserver.

Solution:Whilewecannot100%protecttheimagesfrominclusion,we

canatleastrestrictthecaseswherethebrowsersendsaHTTPRefererheader.

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]

ProxyDenyDescription:

HowcanweforbidacertainhostorevenauserofaspecialhostfromusingtheApacheproxy?

Solution:Wefirsthavetomakesuremod_rewriteisbelow(!)mod_proxyintheConfigurationfilewhencompilingtheApachewebserver.Thiswayitgetscalledbeforemod_proxy.Thenweconfigurethefollowingforahost-dependentdeny...

RewriteCond%{REMOTE_HOST}^badhost\.mydomain\.com$

RewriteRule!^http://[^/.]\.mydomain.com.*-[F]

...andthisoneforauser@host-dependentdeny:

RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}^badguy@badhost\.mydomain\.com$

RewriteRule!^http://[^/.]\.mydomain.com.*-[F]

Other

ExternalRewritingEngineDescription:

AFAQ:HowcanwesolvetheFOO/BAR/QUUX/etc.problem?Thereseemsnosolutionbytheuseofmod_rewrite...

Solution:UseanexternalRewriteMap,i.e.aprogramwhichactslikeaRewriteMap.ItisrunonceonstartupofApachereceivestherequestedURLsonSTDINandhastoputtheresulting(usuallyrewritten)URLonSTDOUT(sameorder!).

RewriteEngineon

RewriteMapquux-mapprg:/path/to/map.quux.pl

RewriteRule^/~quux/(.*)$/~quux/${quux-map:$1}

#!/path/to/perl

#disablebufferedI/Owhichwouldlead

#todeadloopsfortheApacheserver

$|=1;

#readURLsoneperlinefromstdinand

#generatesubstitutionURLonstdout

while(<>){

s|^foo/|bar/|;

print$_;

}

Thisisademonstration-onlyexampleandjustrewritesallURLs/~quux/foo/...to/~quux/bar/....Actuallyyoucanprogramwhateveryoulike.Butnoticethatwhilesuch

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

mapscanbeusedalsobyanaverageuser,onlythesystemadministratorcandefineit.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

URLRewritingGuide-Advancedtopics

Thisdocumentsupplementsthemod_rewritereferencedocumentation.ItdescribeshowonecanuseApache'smod_rewritetosolvetypicalURL-basedproblemswithwhichwebmastersarecommonlyconfronted.WegivedetaileddescriptionsonhowtosolveeachproblembyconfiguringURLrewritingrulesets.

ATTENTION:Dependingonyourserverconfigurationitmaybenecessarytoadjusttheexamplesforyoursituation,e.g.,addingthe[PT]flagifusingmod_aliasandmod_userdir,etc.Orrewritingarulesettoworkin.htaccesscontextinsteadofper-servercontext.Alwaystrytounderstandwhataparticularrulesetreallydoesbeforeyouuseit;thisavoidsmanyproblems.

SeealsoModuledocumentationmod_rewriteintroductionTechnicaldetails

WebClusterwithConsistentURLSpace

Description:WewanttocreateahomogeneousandconsistentURLlayoutacrossallWWWserversonanIntranetwebcluster,i.e.,allURLs(bydefinitionserver-localandthusserver-dependent!)becomeserverindependent!WhatwewantistogivetheWWWnamespaceasingleconsistentlayout:noURLshouldrefertoanyparticulartargetserver.Theclusteritselfshouldconnectusersautomaticallytoaphysicaltargethostasneeded,invisibly.

Solution:First,theknowledgeofthetargetserverscomesfrom(distributed)externalmapswhichcontaininformationonwhereourusers,groups,andentitiesreside.Theyhavetheform:

user1server_of_user1

user2server_of_user2

::

Weputthemintofilesmap.xxx-to-host.SecondweneedtoinstructallserverstoredirectURLsoftheforms:

/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

whenanyURLpathneednotbevalidoneveryserver.Thefollowingrulesetdoesthisforuswiththehelpofthemapfiles(assumingthatserver0isadefaultserverwhichwillbeusedifauserhasnoentryinthemap):

RewriteEngineon

RewriteMapuser-to-hosttxt:/path/to/map.user-to-host

RewriteMapgroup-to-hosttxt:/path/to/map.group-to-host

RewriteMapentity-to-hosttxt:/path/to/map.entity-to-host

RewriteRule^/u/([^/]+)/?(.*)http://${user-to-host:$1|server0}

RewriteRule^/g/([^/]+)/?(.*)http://${group-to-host:$1|server0}

RewriteRule^/e/([^/]+)/?(.*)http://${entity-to-host:$1|server0}

RewriteRule^/([uge])/([^/]+)/?$/$1/$2/.www/

RewriteRule^/([uge])/([^/]+)/([^.]+.+)/$1/$2/.www/$3\

StructuredHomedirs

Description:Somesiteswiththousandsofusersuseastructuredhomedirlayout,i.e.eachhomedirisinasubdirectorywhichbegins(forinstance)withthefirstcharacteroftheusername.So,/~foo/anypathis/home/f/foo/.www/anypathwhile/~bar/anypathis/home/b/bar/.www/anypath.

Solution:WeusethefollowingrulesettoexpandthetildeURLsintotheabovelayout.

RewriteEngineon

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

FilesystemReorganization

Description:Thisreallyisahardcoreexample:akillerapplicationwhichheavilyusesper-directoryRewriteRulestogetasmoothlookandfeelontheWebwhileitsdatastructureisnevertouchedoradjusted.Background:net.swismyarchiveoffreelyavailableUnixsoftwarepackages,whichIstartedtocollectin1992.Itisbothmyhobbyandjobtodothis,becausewhileI'mstudyingcomputerscienceIhavealsoworkedformanyyearsasasystemandnetworkadministratorinmysparetime.EveryweekIneedsomesortofsoftwaresoIcreatedadeephierarchyofdirectorieswhereIstoredthepackages:

drwxrwxr-x2netswusers512Aug318:39Audio/

drwxrwxr-x2netswusers512Jul914:37Benchmark/

drwxrwxr-x12netswusers512Jul900:34Crypto/

drwxrwxr-x5netswusers512Jul900:41Database/

drwxrwxr-x4netswusers512Jul3019:25Dicts/

drwxrwxr-x10netswusers512Jul901:54Graphic/

drwxrwxr-x5netswusers512Jul901:58Hackers/

drwxrwxr-x8netswusers512Jul903:19InfoSys/

drwxrwxr-x3netswusers512Jul903:21Math/

drwxrwxr-x3netswusers512Jul903:24Misc/

drwxrwxr-x9netswusers512Aug116:33Network/

drwxrwxr-x2netswusers512Jul905:53Office/

drwxrwxr-x7netswusers512Jul909:24SoftEng/

drwxrwxr-x7netswusers512Jul912:17System/

drwxrwxr-x12netswusers512Aug320:15Typesetting/

drwxrwxr-x10netswusers512Jul914:08X11/

InJuly1996IdecidedtomakethisarchivepublictotheworldviaaniceWebinterface."Nice"meansthatIwantedtoofferaninterfacewhereyoucanbrowsedirectlythroughthe

archivehierarchy.And"nice"meansthatIdidn'twanttochangeanythinginsidethishierarchy-notevenbyputtingsomeCGIscriptsatthetopofit.Why?BecausetheabovestructureshouldlaterbeaccessibleviaFTPaswell,andIdidn'twantanyWeborCGIstuffmixedinthere.

Solution:Thesolutionhastwoparts:ThefirstisasetofCGIscriptswhichcreateallthepagesatalldirectorylevelson-the-fly.Iputthemunder/e/netsw/.www/asfollows:

-rw-r--r--1netswusers1318Aug118:10.wwwacl

drwxr-xr-x18netswusers512Aug515:51DATA/

-rw-rw-rw-1netswusers372982Aug516:35LOGFILE

-rw-r--r--1netswusers659Aug409:27TODO

-rw-r--r--1netswusers5697Aug118:01netsw-about.html

-rwxr-xr-x1netswusers579Aug210:33netsw-access.pl

-rwxr-xr-x1netswusers1532Aug117:35netsw-changes.cgi

-rwxr-xr-x1netswusers2866Aug514:49netsw-home.cgi

drwxr-xr-x2netswusers512Jul823:47netsw-img/

-rwxr-xr-x1netswusers24050Aug515:49netsw-lsdir.cgi

-rwxr-xr-x1netswusers1589Aug318:43netsw-search.cgi

-rwxr-xr-x1netswusers1885Aug117:41netsw-tree.cgi

-rw-r--r--1netswusers234Jul3016:35netsw-unlimit.lst

TheDATA/subdirectoryholdstheabovedirectorystructure,i.e.therealnet.swstuff,andgetsautomaticallyupdatedviardistfromtimetotime.Thesecondpartoftheproblemremains:howtolinkthesetwostructurestogetherintoonesmooth-lookingURLtree?WewanttohidetheDATA/directoryfromtheuserwhilerunningtheappropriateCGIscriptsforthevariousURLs.Hereisthesolution:firstIputthefollowingintotheper-directoryconfigurationfileintheDocumentRootoftheservertorewritethepublicURLpath

/net.sw/totheinternalpath/e/netsw:

RewriteRule^net.sw$net.sw/[R]

RewriteRule^net.sw/(.*)$e/netsw/$1

Thefirstruleisforrequestswhichmissthetrailingslash!Thesecondruledoestherealthing.Andthencomesthekillerconfigurationwhichstaysintheper-directoryconfigfile/e/netsw/.www/.wwwacl:

OptionsExecCGIFollowSymLinksIncludesMultiViews

RewriteEngineon

#wearereachedvia/net.sw/prefix

RewriteBase/net.sw/

#firstwerewritetherootdirto

#thehandlingcgiscript

RewriteRule^$netsw-home.cgi[L]

RewriteRule^index\.html$netsw-home.cgi[L]

#stripoutthesubdirswhen

#thebrowserrequestsusfromperdirpages

RewriteRule^.+/(netsw-[^/]+/.+)$$1[L]

#andnowbreaktherewritingforlocalfiles

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]

#anythingelseisasubdirwhichgetshandled

#byanothercgiscript

RewriteRule!^netsw-lsdir\.cgi.*-[C]

RewriteRule(.*)netsw-lsdir.cgi/$1

Somehintsforinterpretation:

1. NoticetheL(last)flagandnosubstitutionfield('-')inthefourthpart

2. Noticethe!(not)characterandtheC(chain)flagatthefirstruleinthelastpart

3. Noticethecatch-allpatterninthelastrule

RedirectFailingURLstoAnotherWebServer

Description:AtypicalFAQaboutURLrewritingishowtoredirectfailingrequestsonwebserverAtowebserverB.UsuallythisisdoneviaErrorDocumentCGIscriptsinPerl,butthereisalsoamod_rewritesolution.ButnotethatthisperformsmorepoorlythanusinganErrorDocumentCGIscript!

Solution:Thefirstsolutionhasthebestperformancebutlessflexibility,andislesssafe:

RewriteEngineon

RewriteCond/your/docroot/%{REQUEST_FILENAME}!-f

RewriteRule^(.+)http://webserverB

TheproblemhereisthatthiswillonlyworkforpagesinsidetheDocumentRoot.WhileyoucanaddmoreConditions(forinstancetoalsohandlehomedirs,etc.)thereisabettervariant:

RewriteEngineon

RewriteCond%{REQUEST_URI}!-U

RewriteRule^(.+)http://webserverB.dom/$1

ThisusestheURLlook-aheadfeatureofmod_rewrite.TheresultisthatthiswillworkforalltypesofURLsandissafe.Butitdoeshaveaperformanceimpactonthewebserver,becauseforeveryrequestthereisonemoreinternalsubrequest.So,ifyourwebserverrunsonapowerfulCPU,usethisone.Ifitisaslowmachine,usethefirstapproachorbetteranErrorDocumentCGIscript.

ArchiveAccessMultiplexer

Description:DoyouknowthegreatCPAN(ComprehensivePerlArchiveNetwork)underhttp://www.perl.com/CPAN?CPANautomaticallyredirectsbrowserstooneofmanyFTPserversaroundtheworld(generallyoneneartherequestingclient);eachservercarriesafullCPANmirror.ThisiseffectivelyanFTPaccessmultiplexingservice.CPANrunsviaCGIscripts,buthowcouldasimilarapproachbeimplementedviamod_rewrite?

Solution:Firstwenoticethatasofversion3.0.0,mod_rewritecanalsousethe"ftp:"schemeonredirects.Andsecond,thelocationapproximationcanbedonebyaRewriteMapoverthetop-leveldomainoftheclient.Withatrickychainedrulesetwecanusethistop-leveldomainasakeytoourmultiplexingmap.

RewriteEngineon

RewriteMapmultiplextxt:/path/to/map.cxan

RewriteRule^/CxAN/(.*)%{REMOTE_HOST}::$1[C]

RewriteRule^.+\.([a-zA-Z]+)::(.*)$${multiplex:$1|ftp.default.dom}$2[R,L]

##

##map.cxan--MultiplexingMapforCxAN

##

deftp://ftp.cxan.de/CxAN/

ukftp://ftp.cxan.uk/CxAN/

comftp://ftp.cxan.com/CxAN/

:

##EOF##

ContentHandling

BrowserDependentContentDescription:

Atleastforimportanttop-levelpagesitissometimesnecessarytoprovidetheoptimumofbrowserdependentcontent,i.e.,onehastoprovideoneversionforcurrentbrowsers,adifferentversionfortheLynxandtext-modebrowsers,andanotherforotherbrowsers.

Solution:Wecannotusecontentnegotiationbecausethebrowsersdonotprovidetheirtypeinthatform.InsteadwehavetoactontheHTTPheader"User-Agent".Thefollowingconfigdoesthefollowing:IftheHTTPheader"User-Agent"beginswith"Mozilla/3",thepagefoo.htmlisrewrittentofoo.NS.htmlandtherewritingstops.Ifthebrowseris"Lynx"or"Mozilla"ofversion1or2,theURLbecomesfoo.20.html.Allotherbrowsersreceivepagefoo.32.html.Thisisdonewiththefollowingruleset:

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]

DynamicMirrorDescription:

Assumetherearenicewebpagesonremotehostswewant

tobringintoournamespace.ForFTPserverswewouldusethemirrorprogramwhichactuallymaintainsanexplicitup-to-datecopyoftheremotedataonthelocalmachine.ForawebserverwecouldusetheprogramwebcopywhichrunsviaHTTP.Butbothtechniqueshaveamajordrawback:Thelocalcopyisalwaysonlyasup-to-dateasthelasttimewerantheprogram.Itwouldbemuchbetterifthemirrorwasnotastaticonewehavetoestablishexplicitly.Insteadwewantadynamicmirrorwithdatawhichgetsupdatedautomaticallyasneededontheremotehost(s).

Solution:ToprovidethisfeaturewemaptheremotewebpageoreventhecompleteremotewebareatoournamespacebytheuseoftheProxyThroughputfeature(flag[P]):

RewriteEngineon

RewriteBase/~quux/

RewriteRule^hotsheet/(.*)$http://www.tstimpreso.com/hotsheet/

RewriteEngineon

RewriteBase/~quux/

RewriteRule^usa-news\.html$http://www.quux-corp.com/news/index.html

ReverseDynamicMirrorDescription:

...

Solution:

RewriteEngineon

RewriteCond/mirror/of/remotesite/$1-U

RewriteRule^http://www\.remotesite\.com/(.*)$/mirror/of/remotesite/$1

RetrieveMissingDatafromIntranetDescription:

Thisisatrickywayofvirtuallyrunningacorporate(external)Internetwebserver(www.quux-corp.dom),whileactuallykeepingandmaintainingitsdataonan(internal)Intranetwebserver(www2.quux-corp.dom)whichisprotectedbyafirewall.Thetrickisthattheexternalwebserverretrievestherequesteddataon-the-flyfromtheinternalone.

Solution:First,wemustmakesurethatourfirewallstillprotectstheinternalwebserverandonlytheexternalwebserverisallowedtoretrievedatafromit.Onapacket-filteringfirewall,forinstance,wecouldconfigureafirewallrulesetlikethefollowing:

ALLOWHostwww.quux-corp.domPort>1024-->Hostwww2.quux-corp.domPort

DENYHost*Port*-->Hostwww2.quux-corp.domPort

Justadjustittoyouractualconfigurationsyntax.Nowwecanestablishthemod_rewriteruleswhichrequestthemissingdatainthebackgroundthroughtheproxythroughputfeature:

RewriteRule^/~([^/]+)/?(.*)/home/$1/.www/$2

RewriteCond%{REQUEST_FILENAME}!-f

RewriteCond%{REQUEST_FILENAME}!-d

RewriteRule^/home/([^/]+)/.www/?(.*)http://www2.quux-corp.dom/~$1/pub/$2[

LoadBalancingDescription:

Supposewewanttoloadbalancethetraffictowww.foo.comoverwww[0-5].foo.com(atotalof6servers).Howcanthis

bedone?

Solution:Therearemanypossiblesolutionsforthisproblem.WewillfirstdiscussacommonDNS-basedmethod,andthenonebasedonmod_rewrite:

1. DNSRound-RobinThesimplestmethodforload-balancingistouseDNSround-robin.Hereyoujustconfigurewww[0-9].foo.comasusualinyourDNSwithA(address)records,e.g.,

www0INA1.2.3.1

www1INA1.2.3.2

www2INA1.2.3.3

www3INA1.2.3.4

www4INA1.2.3.5

www5INA1.2.3.6

Thenyouadditionallyaddthefollowingentries:

wwwINA1.2.3.1

wwwINA1.2.3.2

wwwINA1.2.3.3

wwwINA1.2.3.4

wwwINA1.2.3.5

Nowwhenwww.foo.comgetsresolved,BINDgivesoutwww0-www5-butinapermutated(rotated)ordereverytime.Thiswaytheclientsarespreadoverthevariousservers.Butnoticethatthisisnotaperfectloadbalancingscheme,becauseDNSresolutionsarecachedbyclientsandothernameservers,soonceaclienthas

resolvedwww.foo.comtoaparticularwwwN.foo.com,allitssubsequentrequestswillcontinuetogotothesameIP(andthusasingleserver),ratherthanbeingdistributedacrosstheotheravailableservers.Buttheoverallresultisokaybecausetherequestsarecollectivelyspreadoverthevariouswebservers.

2. DNSLoad-BalancingAsophisticatedDNS-basedmethodforload-balancingistousetheprogramlbnamedwhichcanbefoundathttp://www.stanford.edu/~schemers/docs/lbnamed/lbnamed.htmlItisaPerl5programwhich,inconjunctionwithauxilliarytools,providesrealload-balancingviaDNS.

3. ProxyThroughputRound-RobinInthisvariantweusemod_rewriteanditsproxythroughputfeature.Firstwededicatewww0.foo.comtobeactuallywww.foo.combyusingasingle

wwwINCNAMEwww0.foo.com.

entryintheDNS.Thenweconvertwww0.foo.comtoaproxy-onlyserver,i.e.,weconfigurethismachinesoallarrivingURLsaresimplypassedthroughitsinternalproxytooneofthe5otherservers(www1-www5).Toaccomplishthiswefirstestablisharulesetwhichcontactsaloadbalancingscriptlb.plforallURLs.

RewriteEngineon

RewriteMaplbprg:/path/to/lb.pl

RewriteRule^/(.+)$${lb:$1}[P,L]

Thenwewritelb.pl:

#!/path/to/perl

##

##lb.pl--loadbalancingscript

##

$|=1;

$name="www";#thehostnamebase

$first=1;#thefirstserver(not0here,because0ismyself)

$last=5;#thelastserverintheround-robin

$domain="foo.dom";#thedomainname

$cnt=0;

while(<STDIN>){

$cnt=(($cnt+1)%($last+1-$first));

$server=sprintf("%s%d.%s",$name,$cnt+$first,$domain);

print"http://$server/$_";

}

##EOF##

Alastnotice:Whyisthisuseful?Seemslikewww0.foo.comstillisoverloaded?Theanswerisyes,itisoverloaded,butwithplainproxythroughputrequests,only!AllSSI,CGI,ePerl,etc.processingishandleddoneontheothermachines.Foracomplicatedsite,thismayworkwell.Thebiggestriskhereisthatwww0isnowasinglepointoffailure--ifitcrashes,theotherserversareinaccessible.

4. DedicatedLoadBalancersTherearemoresophisticatedsolutions,aswell.Cisco,F5,andseveralothercompaniessellhardwareload

balancers(typicallyusedinpairsforredundancy),whichoffersophisticatedloadbalancingandauto-failoverfeatures.Therearesoftwarepackageswhichoffersimilarfeaturesoncommodityhardware,aswell.Ifyouhaveenoughmoneyorneed,checktheseout.Thelb-lmailinglistisagoodplacetoresearch.

NewMIME-type,NewServiceDescription:

OnthenettherearemanyniftyCGIprograms.Buttheirusageisusuallyboring,soalotofwebmastersdon'tusethem.EvenApache'sActionhandlerfeatureforMIME-typesisonlyappropriatewhentheCGIprogramsdon'tneedspecialURLs(actuallyPATH_INFOandQUERY_STRINGS)astheirinput.First,letusconfigureanewfiletypewithextension.scgi(forsecureCGI)whichwillbeprocessedbythepopularcgiwrapprogram.TheproblemhereisthatforinstanceifweuseaHomogeneousURLLayout(seeabove)afileinsidetheuserhomedirsmighthaveaURLlike/u/user/foo/bar.scgi,butcgiwrapneedsURLsintheform/~user/foo/bar.scgi/.Thefollowingrulesolvestheproblem:

RewriteRule^/[uge]/([^/]+)/\.www/(.+)\.scgi(.*)...

.../internal/cgi/user/cgiwrap/~$1/$2.scgi$3[NS,T=application/x-http-cgi

Orassumewehavesomemoreniftyprograms:wwwlog(whichdisplaystheaccess.logforaURLsubtree)andwwwidx(whichrunsGlimpseonaURLsubtree).WehavetoprovidetheURLareatotheseprogramssotheyknowwhichareatheyarereallyworkingwith.Butusuallythisiscomplicated,becausetheymaystillberequestedbythealternateURLform,i.e.,typicallywewouldruntheswwidx

programfromwithin/u/user/foo/viahyperlinkto

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

whichisugly,becausewehavetohard-codeboththelocationoftheareaandthelocationoftheCGIinsidethehyperlink.Whenwehavetoreorganize,wespendalotoftimechangingthevarioushyperlinks.

Solution:ThesolutionhereistoprovideaspecialnewURLformatwhichautomaticallyleadstotheproperCGIinvocation.Weconfigurethefollowing:

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

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

Nowthehyperlinktosearchat/u/user/foo/readsonly

HREF="*"

whichinternallygetsautomaticallytransformedto

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

ThesameapproachleadstoaninvocationfortheaccesslogCGIprogramwhenthehyperlink:loggetsused.

On-the-flyContent-RegenerationDescription:

Herecomesareallyesotericfeature:Dynamicallygeneratedbutstaticallyservedpages,i.e.,pagesshouldbedeliveredas

purestaticpages(readfromthefilesystemandjustpassedthrough),buttheyhavetobegenerateddynamicallybythewebserverifmissing.ThiswayyoucanhaveCGI-generatedpageswhicharestaticallyservedunlessanadmin(oracronjob)removesthestaticcontents.Thenthecontentsgetsrefreshed.

Solution:Thisisdoneviathefollowingruleset:

RewriteCond%{REQUEST_FILENAME}!-s

RewriteRule^page\.html$page.cgi[T=application/x-httpd-cgi,L]

Herearequestforpage.htmlleadstoaninternalrunofacorrespondingpage.cgiifpage.htmlismissingorhasfilesizenull.Thetrickhereisthatpage.cgiisaCGIscriptwhich(additionallytoitsSTDOUT)writesitsoutputtothefilepage.html.Onceithascompleted,theserversendsoutpage.html.Whenthewebmasterwantstoforcearefreshofthecontents,hejustremovespage.html(typicallyfromcron).

DocumentWithAutorefreshDescription:

Wouldn'titbenice,whilecreatingacomplexwebpage,ifthewebbrowserwouldautomaticallyrefreshthepageeverytimewesaveanewversionfromwithinoureditor?Impossible?

Solution:No!WejustcombinetheMIMEmultipartfeature,thewebserverNPHfeature,andtheURLmanipulationpowerofmod_rewrite.First,weestablishanewURLfeature:Addingjust:refreshtoanyURLcausesthe'page'toberefreshed

everytimeitisupdatedonthefilesystem.

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

NowwhenwereferencetheURL

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

thisleadstotheinternalinvocationoftheURL

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

TheonlymissingpartistheNPH-CGIscript.Althoughonewouldusuallysay"leftasanexercisetothereader";-)Iwillprovidethis,too.

#!/sw/bin/perl

##

##nph-refresh--NPH/CGIscriptforautorefreshingpages

##Copyright(c)1997RalfS.Engelschall,AllRightsReserved.

##

$|=1;

#splittheQUERY_STRINGvariable

@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=1if($QS_seq'');

$QS_n=3600if($QS_neq'');

if($QS_feq''){

print"HTTP/1.0200OK\n";

print"Content-type:text/html\n\n";

print"&lt;b&gt;ERROR&lt;/b&gt;:Nofilegiven\n";

exit(0);

}

if(!-f$QS_f){

print"HTTP/1.0200OK\n";

print"Content-type:text/html\n\n";

print"&lt;b&gt;ERROR&lt;/b&gt;:File$QS_fnotfound\n";

exit(0);

}

subprint_http_headers_multipart_begin{

print"HTTP/1.0200OK\n";

$bound="ThisRandomString12345";

print"Content-type:multipart/x-mixed-replace;boundary=$bound\n";

&print_http_headers_multipart_next;

}

subprint_http_headers_multipart_next{

print"\n--$bound\n";

}

subprint_http_headers_multipart_end{

print"\n--$bound--\n";

}

subdisplayhtml{

local($buffer)=@_;

$len=length($buffer);

print"Content-type:text/html\n";

print"Content-length:$len\n\n";

print$buffer;

}

subreadfile{

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);

submystat{

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($mtimene$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##

MassVirtualHostingDescription:

The<VirtualHost>featureofApacheisniceandworksgreatwhenyoujusthaveafewdozenvirtualhosts.ButwhenyouareanISPandhavehundredsofvirtualhosts,thisfeatureissuboptimal.

Solution:ToprovidethisfeaturewemaptheremotewebpageoreventhecompleteremotewebareatoournamespaceusingtheProxyThroughputfeature(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

##

:

#usethecanonicalhostnameonredirects,etc.

UseCanonicalNameon

:

#addthevirtualhostinfrontoftheCLF-format

CustomLog/path/to/access_log"%{VHOST}e%h%l%u%t\"%r\"%>s%b"

:

#enabletherewritingengineinthemainserver

RewriteEngineon

#definetwomaps:oneforfixingtheURLandonewhichdefines

#theavailablevirtualhostswiththeircorresponding

#DocumentRoot.

RewriteMaplowercaseint:tolower

RewriteMapvhosttxt:/path/to/vhost.map

#Nowdotheactualvirtualhostmapping

#viaahugeandcomplicatedsinglerule:

#

#1.makesurewedon'tmapforcommonlocations

RewriteCond%{REQUEST_URI}!^/commonurl1/.*

RewriteCond%{REQUEST_URI}!^/commonurl2/.*

:

RewriteCond%{REQUEST_URI}!^/commonurlN/.*

#

#2.makesurewehaveaHostheader,because

#currentlyourapproachonlysupports

#virtualhostingthroughthisheader

RewriteCond%{HTTP_HOST}!^$

#

#3.lowercasethehostname

RewriteCond${lowercase:%{HTTP_HOST}|NONE}^(.+)$

#

#4.lookupthishostnameinvhost.mapand

#rememberitonlywhenitisapath

#(andnot"NONE"fromabove)

RewriteCond${vhost:%1}^(/.*)$

#

#5.finallywecanmaptheURLtoitsdocrootlocation

#andrememberthevirtualhostforloggingpurposes

RewriteRule^/(.*)$%1/$1[E=VHOST:${lowercase:%{HTTP_HOST}}]

:

AccessRestriction

HostDenyDescription:

Howcanweforbidalistofexternallyconfiguredhostsfromusingourserver?

Solution:ForApache>=1.3b6:

RewriteEngineon

RewriteMaphosts-denytxt:/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]

ForApache<=1.3b6:

RewriteEngineon

RewriteMaphosts-denytxt:/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!Thisisamap,notalist,evenwhenwetreatitassuch.

##mod_rewriteparsesitforkey/valuepairs,soatleasta

##dummyvalue"-"mustbepresentforeachentry.

##

193.102.180.41-

bsdti1.sdm.de-

192.76.162.40-

ProxyDenyDescription:

HowcanweforbidacertainhostorevenauserofaspecialhostfromusingtheApacheproxy?

Solution:Wefirsthavetomakesuremod_rewriteisbelow(!)mod_proxyintheConfigurationfilewhencompilingtheApachewebserver.Thiswayitgetscalledbeforemod_proxy.Thenweconfigurethefollowingforahost-dependentdeny...

RewriteCond%{REMOTE_HOST}^badhost\.mydomain\.com$

RewriteRule!^http://[^/.]\.mydomain.com.*-[F]

...andthisoneforauser@host-dependentdeny:

RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}^badguy@badhost\.mydomain\.com$

RewriteRule!^http://[^/.]\.mydomain.com.*-[F]

SpecialAuthenticationVariantDescription:

Sometimesveryspecialauthenticationisneeded,forinstanceauthenticationwhichchecksforasetofexplicitlyconfiguredusers.Onlytheseshouldreceiveaccessandwithoutexplicitprompting(whichwouldoccurwhenusingBasicAuthviamod_auth).

Solution:Weusealistofrewriteconditionstoexcludeallexceptourfriends:

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-basedDeflectorDescription:

HowcanweprogramaflexibleURLDeflectorwhichactsonthe"Referer"HTTPheaderandcanbeconfiguredwithasmanyreferringpagesaswelike?

Solution:Usethefollowingreallytrickyruleset...

RewriteMapdeflectortxt:/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]

...inconjunctionwithacorrespondingrewritemap:

##

##deflector.map

##

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

http://www.badguys.com/bad/index.html-

http://www.badguys.com/bad/index2.html-

http://www.badguys.com/bad/index3.htmlhttp://somewhere.com/

Thisautomaticallyredirectstherequestbacktothereferringpage(when"-"isusedasthevalueinthemap)ortoaspecificURL(whenanURLisspecifiedinthemapasthesecondargument).

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

Apachemod_rewriteTechnicalDetails

Thisdocumentdiscussessomeofthetechnicaldetailsofmod_rewriteandURLmatching.

SeealsoModuledocumentationmod_rewriteintroductionPracticalsolutionstocommonproblems

InternalProcessing

Theinternalprocessingofthismoduleisverycomplexbutneedstobeexplainedonceeventotheaverageusertoavoidcommonmistakesandtoletyouexploititsfullfunctionality.

APIPhases

FirstyouhavetounderstandthatwhenApacheprocessesaHTTPrequestitdoesthisinphases.AhookforeachofthesephasesisprovidedbytheApacheAPI.Mod_rewriteusestwoofthesehooks:theURL-to-filenametranslationhookwhichisusedaftertheHTTPrequesthasbeenreadbutbeforeanyauthorizationstartsandtheFixuphookwhichistriggeredaftertheauthorizationphasesandaftertheper-directoryconfigfiles(.htaccess)havebeenread,butbeforethecontenthandlerisactivated.

So,afterarequestcomesinandApachehasdeterminedthecorrespondingserver(orvirtualserver)therewritingenginestartsprocessingofallmod_rewritedirectivesfromtheper-serverconfigurationintheURL-to-filenamephase.Afewstepslaterwhenthefinaldatadirectoriesarefound,theper-directoryconfigurationdirectivesofmod_rewritearetriggeredintheFixupphase.Inbothsituationsmod_rewriterewritesURLseithertonewURLsortofilenames,althoughthereisnoobviousdistinctionbetweenthem.ThisisausageoftheAPIwhichwasnotintendedtobethiswaywhentheAPIwasdesigned,butasofApache1.xthisistheonlywaymod_rewritecanoperate.Tomakethispointmoreclearrememberthefollowingtwopoints:

1. Althoughmod_rewriterewritesURLstoURLs,URLstofilenamesandevenfilenamestofilenames,theAPIcurrentlyprovidesonlyaURL-to-filenamehook.InApache2.0thetwomissinghookswillbeaddedtomaketheprocessingmoreclear.Butthispointhasnodrawbacksfortheuser,itisjustafactwhichshouldberemembered:ApachedoesmoreintheURL-to-filenamehookthantheAPIintendsforit.

2. Unbelievablymod_rewriteprovidesURLmanipulationsinper-directorycontext,i.e.,within.htaccessfiles,althoughthesearereachedaverylongtimeaftertheURLshavebeentranslatedtofilenames.Ithastobethiswaybecause

.htaccessfilesliveinthefilesystem,soprocessinghasalreadyreachedthisstage.Inotherwords:AccordingtotheAPIphasesatthistimeitistoolateforanyURLmanipulations.Toovercomethischickenandeggproblemmod_rewriteusesatrick:WhenyoumanipulateaURL/filenameinper-directorycontextmod_rewritefirstrewritesthefilenamebacktoitscorrespondingURL(whichisusuallyimpossible,butseetheRewriteBasedirectivebelowforthetricktoachievethis)andtheninitiatesanewinternalsub-requestwiththenewURL.ThisrestartsprocessingoftheAPIphases.Againmod_rewritetrieshardtomakethiscomplicatedsteptotallytransparenttotheuser,butyoushouldrememberhere:WhileURLmanipulationsinper-servercontextarereallyfastandefficient,per-directoryrewritesareslowandinefficientduetothischickenandeggproblem.Butontheotherhandthisistheonlywaymod_rewritecanprovide(locallyrestricted)URLmanipulationstotheaverageuser.

Don'tforgetthesetwopoints!

RulesetProcessing

Nowwhenmod_rewriteistriggeredinthesetwoAPIphases,itreadstheconfiguredrulesetsfromitsconfigurationstructure(whichitselfwaseithercreatedonstartupforper-servercontextorduringthedirectorywalkoftheApachekernelforper-directorycontext).ThentheURLrewritingengineisstartedwiththecontainedruleset(oneormorerulestogetherwiththeirconditions).TheoperationoftheURLrewritingengineitselfisexactlythesameforbothconfigurationcontexts.Onlythefinalresultprocessingisdifferent.

Theorderofrulesintherulesetisimportantbecausetherewritingengineprocessestheminaspecial(andnotveryobvious)order.Theruleisthis:Therewritingengineloopsthroughtherulesetrulebyrule(RewriteRuledirectives)andwhenaparticularrulematchesitoptionallyloopsthroughexistingcorrespondingconditions(RewriteConddirectives).Forhistoricalreasonstheconditionsaregivenfirst,andsothecontrolflowisalittlebitlong-winded.SeeFigure1formoredetails.

Copyright2013TheApacheSoftwareFoundation.

Figure1:Thecontrolflowthroughtherewritingruleset

Asyoucansee,firsttheURLismatchedagainstthePatternofeachrule.Whenitfailsmod_rewriteimmediatelystopsprocessingthisruleandcontinueswiththenextrule.IfthePatternmatches,mod_rewritelooksforcorrespondingruleconditions.Ifnonearepresent,itjustsubstitutestheURLwithanewvaluewhichisconstructedfromthestringSubstitutionandgoesonwithitsrule-looping.Butifconditionsexist,itstartsaninnerloopforprocessingthemintheorderthattheyarelisted.Forconditionsthelogicisdifferent:wedon'tmatchapatternagainstthecurrentURL.InsteadwefirstcreateastringTestStringbyexpandingvariables,back-references,maplookups,etc.andthenwetrytomatchCondPatternagainstit.Ifthepatterndoesn'tmatch,thecompletesetofconditionsandthecorrespondingrulefails.Ifthepatternmatches,thenthenextconditionisprocesseduntilnomoreconditionsareavailable.Ifallconditionsmatch,processingiscontinuedwiththesubstitutionoftheURLwithSubstitution.

LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>FAQ

FrequentlyAskedQuestions

ThelatestversionofthisFAQisalwaysavailablefromthemainApachewebsite,at<http://httpd.apache.org/docs/2.0/faq/>.

SinceApache2.0isquitenew,wedon'tyetknowwhattheFrequentlyAskedQuestionswillbe.Whilethissectionfillsup,youshouldalsoconsulttheApache1.3FAQtoseeifyourquestionisansweredthere.

Topics

SupportWhatdoIdowhenIhaveproblems?

ErrorMessagesWhatdoesthiserrormessagemean?

Support

"Whycan'tI...?Whywon't...work?"WhattodoincaseofproblemsWhomdoIcontactforsupport?

"Whycan'tI...?Whywon't...work?"WhattodoincaseofproblemsIfyouarehavingtroublewithyourApacheserversoftware,youshouldtakethefollowingsteps:

Checktheerrorlog!Apachetriestobehelpfulwhenitencountersaproblem.Inmanycases,itwillprovidesomedetailsbywritingoneormessagestotheservererrorlog.Sometimesthisisenoughforyoutodiagnose&fixtheproblemyourself(suchasfilepermissionsorthelike).Thedefaultlocationoftheerrorlogis/usr/local/apache2/logs/error_log,butseetheErrorLogdirectiveinyourconfigfilesforthelocationonyourserver.

ChecktheFAQ!ThelatestversionoftheApacheFrequently-AskedQuestionslistcanalwaysbefoundatthemainApachewebsite.

ChecktheApachebugdatabaseMostproblemsthatgetreportedtoTheApacheGrouparerecordedinthebugdatabase.Pleasechecktheexistingreports,openandclosed,beforeaddingone.Ifyoufindthatyourissuehasalreadybeenreported,pleasedon'tadda"me,too"report.Iftheoriginalreportisn'tclosedyet,wesuggestthatyoucheckitperiodically.Youmightalsoconsidercontactingtheoriginalsubmitter,becausetheremaybeanemailexchangegoingonabouttheissuethatisn'tgettingrecordedinthedatabase.

AskinausersupportforumApachehasanactivecommunityofuserswhoarewillingtosharetheirknowledge.Participatinginthiscommunityisusuallythebestandfastestwaytogetanswerstoyourquestionsandproblems.

Usersmailinglist

#httpdonFreenodeIRCisavailableforusersupportissues.

USENETnewsgroups:

comp.infosystems.www.servers.unix[news][google]comp.infosystems.www.servers.ms-windows[news][google]comp.infosystems.www.authoring.cgi[news][google]

Ifallelsefails,reporttheprobleminthebugdatabaseIfyou'vegonethroughthosestepsabovethatareappropriateandhaveobtainednorelief,thenpleasedoletthehttpddevelopersknowabouttheproblembyloggingabugreport.

Ifyourprobleminvolvestheservercrashingandgeneratingacoredump,pleaseincludeabacktrace(ifpossible).Asanexample,

#cdServerRoot

#dbxhttpdcore

(dbx)where

(SubstitutetheappropriatelocationsforyourServerRootandyourhttpdandcorefiles.Youmayhavetousegdbinsteadofdbx.)

WhomdoIcontactforsupport?

Withseveralmillionusersandfewerthanfortyvolunteerdevelopers,wecannotprovidepersonalsupportforApache.Forfreesupport,wesuggestparticipatinginauserforum.

ErrorMessages

Invalidargument:core_output_filter:writingdatatothenetworkAcceptExfailedPrematureendofscriptheaders

Invalidargument:core_output_filter:writingdatatothenetworkApacheusesthesendfilesyscallonplatformswhereitisavailableinordertospeedsendingofresponses.Unfortunately,onsomesystems,Apachewilldetectthepresenceofsendfileatcompile-time,evenwhenitdoesnotworkproperly.Thishappensmostfrequentlywhenusingnetworkorothernon-standardfile-system.

Symptomsofthisproblemincludetheabovemessageintheerrorlogandzero-lengthresponsestonon-zero-sizedfiles.Theproblemgenerallyoccursonlyforstaticfiles,sincedynamiccontentusuallydoesnotmakeuseofsendfile.

Tofixthisproblem,simplyusetheEnableSendfiledirectivetodisablesendfileforallorpartofyourserver.AlsoseetheEnableMMAP,whichcanhelpwithsimilarproblems.

AcceptExFailedIfyougeterrormessagesrelatedtotheAcceptExsyscallonwin32,seetheWin32DisableAcceptExdirective.

PrematureendofscriptheadersMostproblemswithCGIscriptsresultinthismessagewrittenintheerrorlogtogetherwithanInternalServerErrordeliveredtothebrowser.Aguidetohelpingdebugthistypeof

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

problemisavailableintheCGItutorial.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0>DeveloperDocumentation

Apache2.0ThreadSafetyIssues

WhenusinganyofthethreadedmpmsinApache2.0itisimportantthateveryfunctioncalledfromApachebethreadsafe.Whenlinkingin3rdpartyextensionsitcanbedifficulttodeterminewhethertheresultingserverwillbethreadsafe.Casualtestinggenerallywon'ttellyouthiseitherasthreadsafetyproblemscanleadtosubtleraceconditonsthatmayonlyshowupincertainconditionsunderheavyload.

Globalandstaticvariables

Whenwritingyourmoduleorwhentryingtodetermineifamoduleor3rdpartylibraryisthreadsafetherearesomecommonthingstokeepinmind.

First,youneedtorecognizethatinathreadedmodeleachindividualthreadhasitsownprogramcounter,stackandregisters.Localvariablesliveonthestack,sothosearefine.Youneedtowatchoutforanystaticorglobalvariables.Thisdoesn'tmeanthatyouareabsolutelynotallowedtousestaticorglobalvariables.Therearetimeswhenyouactuallywantsomethingtoaffectallthreads,butgenerallyyouneedtoavoidusingthemifyouwantyourcodetobethreadsafe.

Inthecasewhereyouhaveaglobalvariablethatneedstobeglobalandaccessedbyallthreads,beverycarefulwhenyouupdateit.If,forexample,itisanincrementingcounter,youneedtoatomicallyincrementittoavoidraceconditionswithotherthreads.Youdothisusingamutex(mutualexclusion).Lockthemutex,readthecurrentvalue,incrementitandwriteitbackandthenunlockthemutex.Anyotherthreadthatwantstomodifythevaluehastofirstcheckthemutexandblockuntilitiscleared.

IfyouareusingAPR,havealookattheapr_atomic_*functionsandtheapr_thread_mutex_*functions.

errno

Thisisacommonglobalvariablethatholdstheerrornumberofthelasterrorthatoccurred.Ifonethreadcallsalow-levelfunctionthatsetserrnoandthenanotherthreadchecksit,wearebleedingerrornumbersfromonethreadintoanother.Tosolvethis,makesureyourmoduleorlibrarydefines_REENTRANToriscompiledwith-D_REENTRANT.Thiswillmakeerrnoaper-threadvariableandshouldhopefullybetransparenttothecode.Itdoesthisbydoingsomethinglikethis:

#defineerrno(*(__errno_location()))

whichmeansthataccessingerrnowillcall__errno_location()whichisprovidedbythelibc.Setting_REENTRANTalsoforcesredefinitionofsomeotherfunctionstotheir*_requivalentsandsometimeschangesthecommongetc/putcmacrosintosaferfunctioncalls.Checkyourlibcdocumentationforspecifics.Insteadof,orinadditionto_REENTRANTthesymbolsthatmayaffectthisare_POSIX_C_SOURCE,_THREAD_SAFE,_SVID_SOURCE,and_BSD_SOURCE.

Commonstandardtroublesomefunctions

Notonlydothingshavetobethreadsafe,buttheyalsohavetobereentrant.strtok()isanobviousone.Youcallitthefirsttimewithyourdelimiterwhichitthenremembersandoneachsubsequentcallitreturnsthenexttoken.Obviouslyifmultiplethreadsarecallingityouwillhaveaproblem.Mostsystemshaveareentrantversionofofthefunctioncalledstrtok_r()whereyoupassinanextraargumentwhichcontainsanallocatedchar*whichthefunctionwilluseinsteadofitsownstaticstorageformaintainingthetokenizingstate.IfyouareusingAPRyoucanuseapr_strtok().

crypt()isanotherfunctionthattendstonotbereentrant,soifyourunacrosscallstothatfunctioninalibrary,watchout.Onsomesystemsitisreentrantthough,soitisnotalwaysaproblem.Ifyoursystemhascrypt_r()chancesareyoushouldbeusingthat,orifpossiblesimplyavoidthewholemessbyusingmd5instead.

Common3rdPartyLibraries

Thefollowingisalistofcommonlibrariesthatareusedby3rdpartyApachemodules.Youcanchecktoseeifyourmoduleisusingapotentiallyunsafelibrarybyusingtoolssuchasldd(1)andnm(1).ForPHP,forexample,trythis:

%lddlibphp4.so

libsablot.so.0=>/usr/local/lib/libsablot.so.0(0x401f6000)

libexpat.so.0=>/usr/lib/libexpat.so.0(0x402da000)

libsnmp.so.0=>/usr/lib/libsnmp.so.0(0x402f9000)

libpdf.so.1=>/usr/local/lib/libpdf.so.1(0x40353000)

libz.so.1=>/usr/lib/libz.so.1(0x403e2000)

libpng.so.2=>/usr/lib/libpng.so.2(0x403f0000)

libmysqlclient.so.11=>/usr/lib/libmysqlclient.so.11

(0x40411000)

libming.so=>/usr/lib/libming.so(0x40449000)

libm.so.6=>/lib/libm.so.6(0x40487000)

libfreetype.so.6=>/usr/lib/libfreetype.so.6(0x404a8000)

libjpeg.so.62=>/usr/lib/libjpeg.so.62(0x404e7000)

libcrypt.so.1=>/lib/libcrypt.so.1(0x40505000)

libssl.so.2=>/lib/libssl.so.2(0x40532000)

libcrypto.so.2=>/lib/libcrypto.so.2(0x40560000)

libresolv.so.2=>/lib/libresolv.so.2(0x40624000)

libdl.so.2=>/lib/libdl.so.2(0x40634000)

libnsl.so.1=>/lib/libnsl.so.1(0x40637000)

libc.so.6=>/lib/libc.so.6(0x4064b000)

/lib/ld-linux.so.2=>/lib/ld-linux.so.2(0x80000000)

Inadditiontotheselibrariesyouwillneedtohavealookatanylibrarieslinkedstaticallyintothemodule.Youcanusenm(1)tolookforindividualsymbolsinthemodule.

LibraryList

Pleasedropanotetodev@httpd.apache.orgifyouhaveadditionsorcorrectionstothislist.

Library Version ThreadSafe?

Notes

ASpell/PSpell ?BerkeleyDB 3.x,4.x Yes Becarefulaboutsharingaconnectionacross

threads.bzip2 Yes Bothlow-levelandhigh-levelAPIsarethread-safe.

However,high-levelAPIrequiresthread-safeaccesstoerrno.

cdb ?C-Client Perhaps c-clientusesstrtok()andgethostbyname()

whicharenotthread-safeonmostCimplementations.c-client'sstaticdataismeanttobesharedacrossthreads.Ifstrtok()gethostbyname()arethread-safeonyourOS,c-clientmaybethread-safe.

cpdflib ?libcrypt ?Expat Yes NeedaseparateparserinstanceperthreadFreeTDS ?FreeType ?GD1.8.x ?GD2.0.x ?gdbm No Errorsreturnedviaastaticgdbm_error

ImageMagick 5.2.2 Yes ImageMagickdocsclaimitisthreadsafesinceversion5.2.2(seeChangelog).

Imlib2 ?libjpeg v6b ?

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

libmysqlclient Yes Usemysqlclient_rlibraryvarianttoensurethread-safety.Formoreinformation,pleasereadhttp://www.mysql.com/doc/en/Threaded_clients.html

Ming 0.2a ?Net-SNMP 5.0.x ?OpenLDAP 2.1.x Yes Useldap_rlibraryvarianttoensure

OpenSSL 0.9.6g Yes RequiresproperusageofCRYPTO_num_locksCRYPTO_set_locking_callback

CRYPTO_set_id_callback

liboci8(Oracle8+)

8.x,9.x ?

pdflib 5.0.x Yes PDFLibdocsclaimitisthreadsafe;changes.txtindicatesithasbeenpartiallythread-safesinceV1.91:http://www.pdflib.com/products/pdflib/index.html

libpng 1.0.x ?libpng 1.2.x ?libpq(PostgreSQL)

7.x Yes Don'tshareconnectionsacrossthreadsandwatchoutforcrypt()calls

Sablotron 0.95 ?zlib 1.1.4 Yes Reliesuponthread-safezallocandzfreefunctions

Defaultistouselibc'scalloc/freewhicharethread-safe.

Modules|Directives|FAQ|Glossary|Sitemap

ApacheHTTPServerVersion2.0Apache>HTTPServer>Documentation>Version2.0

Apachemod_rewriteIntroduction

Thisdocumentsupplementsthemod_rewritereferencedocumentation.Itdescribesthebasicconceptsnecessaryforuseofmod_rewrite.Otherdocumentsgointogreaterdetail,butthisdocshouldhelpthebeginnergettheirfeetwet.

SeealsoModuledocumentationTechnicaldetailsPracticalsolutionstocommonproblems

Introduction

TheApachemodulemod_rewriteisaverypowerfulandsophisticatedmodulewhichprovidesawaytodoURLmanipulations.Withit,youcandonearlyalltypesofURLrewritingthatyoumayneed.Itis,however,somewhatcomplex,andmaybeintimidatingtothebeginner.Thereisalsoatendencytotreatrewriterulesasmagicincantation,usingthemwithoutactuallyunderstandingwhattheydo.

Thisdocumentattemptstogivesufficientbackgroundsothatwhatfollowsisunderstood,ratherthanjustcopiedblindly.

RegularExpressions

Basicregexbuildingblocks

RewriteRulebasics

BasicanatomyofaRewriteRule,withexhaustivelyannotatedsimpleexamples.

RewriteFlags

DiscussionoftheflagstoRewriteRule,andwhenandwhyonemightusethem.

Rewriteconditions

DiscussionofRewriteCond,looping,andotherrelatedconcepts.

Rewritemaps

DiscussionofRewriteMap,includingsimple,butheavilyannotated,examples.

.htaccessfiles

Discussionofthedifferencesbetweenrewriterulesinhttpd.confandin.htaccessfiles.

Copyright2013TheApacheSoftwareFoundation.LicensedundertheApacheLicense,Version2.0.

Modules|Directives|FAQ|Glossary|Sitemap

EnvironmentVariables

Thismodulekeepstrackoftwoadditional(non-standard)CGI/SSIenvironmentvariablesnamedSCRIPT_URLandSCRIPT_URI.ThesecontainthelogicalWeb-viewtothecurrentresource,whilethestandardCGI/SSIvariablesSCRIPT_NAMEandSCRIPT_FILENAMEcontainthephysicalSystem-view.

Notice:ThesevariablesholdtheURI/URLastheywereinitiallyrequested,i.e.,beforeanyrewriting.ThisisimportantbecausetherewritingprocessisprimarilyusedtorewritelogicalURLstophysicalpathnames.

ExampleSCRIPT_NAME=/sw/lib/w3s/tree/global/u/rse/.www/index.html

SCRIPT_FILENAME=/u/rse/.www/index.html

SCRIPT_URL=/u/rse/

SCRIPT_URI=http://en1.engelschall.com/u/rse/

top related