1702
|||| Apache HTTP Server 2.2 Apache > HTTP Server >> 2.2 || | 200614 |

Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

  • Upload
    others

  • View
    30

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200614|

Page 2: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTPServerVersion2.2[2006321]

Page 3: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.1/2.2Apache2.02.02.2Apache

Page 4: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(MPM)

Page 5: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(DSO)

URL

SSL/TLSCGISuexecURL

Page 6: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.../

CGI.htaccess(SSI)(public_html)

Page 7: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MicrosoftWindowsNovellNetWareEBCDICPort

Page 8: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Page 9: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200617|

Page 10: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

1.32.0

Apache src/CHANGES

Page 11: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheautoconflibtoolApache1.3APACIApache2.0(MPM)

Page 12: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache1.3MPMApache1.3 preforkMPMMPMproxymoduleHTTP/1.1 <Proxy><Directoryproxy:>

PATH_INFO() PATH_INFO INCLUDESPHPPATH_INFO AcceptPathInfoPATH_INFO PATH_INFO

CacheNegotiatedDocsOnOffCacheNegotiatedDocsCacheNegotiatedDocson

ErrorDocument

ErrorDocument403"SomeMessage

ErrorDocument403"SomeMessage"

URLAccessConfig ResourceConfig Include

" Includeconf/access.conf"" Include

conf/srm.conf" httpd.confApache Include

httpd.conf srm.confaccess.conf

BindAddressPort Listen

Apache1.3PortURLApache2.0 ServerNameURLServerTypeMPMinetd()MPMmod_log_agentmod_log_referer CustomLog

mod_log_config

AddModuleClearModuleListApache2.0APIFancyIndexing IndexOptionsFancyIndexing

mod_negotiationMultiViews MultiviewsMatch(2.0.51)ErrorHeaderHeader

Headeralwayssetfoobar

Page 13: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 14: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache1.3mod_auth_digestApache1.3mod_mmap_staticmod_file_cachesrc

Page 15: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Apache2.0APIApache1.3 Apache2.0

Page 16: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200617|

Page 17: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

2.02.2

Apache src/CHANGES

2.02.21.3 1.32.0

Page 18: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

2.0 configure( build/config.nice)

mod_imap mod_imagemap

mod_authmod_auth_basicmod_authn_filemod_authz_usermod_authz_groupfile

mod_access mod_authz_host

mod_auth_ldap mod_authnz_ldap

APR1.0APIPCRE5.0

Page 19: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

2.02.2 LoadModule

2.2 conf/extra/ conf/original

apachectlstartsslSSL httpd.conf mod_ssl

apachectlstart mod_ssl conf/extra/httpd-

ssl.confUseCanonicalName Off UseCanonicalNameOn

UserDir mod_userdir" UserDir

public_html"

Page 20: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_cache2.0mod_disk_cache2.0mod_mem_cache2.0mod_charset_lite2.0mod_dumpio2.0

Page 21: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

2.02.2

Page 22: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200615|

Page 23: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.2

ApacheHTTPServer2.02.21.3 Apache2.0

Page 24: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

/(Authn/Authz)(authentication)(authorization) mod_authn_alias

mod_cachemod_disk_cachemod_mem_cache

htcachecleanmod_disk_cache

Apache

(Gracefulstop)preforkworkerevent(MPM)httpdgraceful-stopGracefulShutdownTimeout httpd

mod_proxy_balancermod_proxy mod_proxy_ajpApacheTomcatApacheJServProtocolversion1.3

5.0Perl(PCRE) httpd --with-pcrePCRE

mod_filterApache2.0

httpd32Unix2GB2G(requestbody)

EventMPMevent(MPM)(KeepAlive)httpd(worker)(/)

SQLmod_dbdapr_dbd(framework)MPM

WindowswindowsApacheWindows

Page 25: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

/(Authn/Authz)aaa(digestauthentication)mod_auth mod_auth_basic

mod_authn_filemod_auth_dbm mod_authn_dbm

mod_access mod_authz_hostmod_authn_alias

mod_authnz_ldap

2.0mod_auth_ldap2.2Authn/AuthzLDAP Require

mod_info

?configApache(requesthook) httpd-V

mod_ssl

RFC2817TLS

mod_imagemap

mod_imapmod_imagemap

Page 26: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httpd

-M -l mod_soDSO()

httxt2dbm

dbm RewriteMapdbm(map)

Page 27: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

APR1.0APIApache2.2APR1.0API APR APR-Util APR

/(Authn/Authz)

mod_auth_*->HTTPmod_authn_*->mod_authz_*->()mod_authnz_*->

ap_log_cerrorIP

(hook)test_config httpd -t

MPMThreadStackSizeMPM

ap_register_output_filter_protocol

ap_filter_protocolmod_filter

(Monitorhook)

APIpcreposix.hap_regex.hPOSIX.2 regex.hap_( ap_regex.h) regcomp,regexecap_regcomp,ap_regcomp

DBD(SQLAPI)1.x2.0SQLApache2.1 ap_dbdAPI(MPM)APR1.2 apr_dbdAPI

Page 28: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

API API

Page 29: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |2006321|

Page 30: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.0

Apache1.32.0

Page 31: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UnixPOSIXUnixApache()

autoconflibtoolApache

Apache mod_echo

UnixApache2.0BeOSOS/2WindowsUnix (MPM)Apache(APR)ApacheAPIPOSIXbug

ApacheAPI2.0API1.32.0per-hookApache

IPv6Apache(APRlibrary)IPv6ApacheIPv6

ListenNameVirtualHostVirtualHostIPv6(" Listen[2001:db8::1]:8080")

Apache mod_includeINCLUDESCGImod_ext_filterCGI

SSI

PortBindAddressIP Listen ServerName

WindowsNTUnicodeApache2.0WindowsNTutf-8UnicodeWindowsNT(Windows2000/XP/2003) Windows95/98/ME

Apache2.0Perl(PCRE)Perl5

Page 32: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_ssl

Apache2.0OpenSSLSSL/TLS

mod_dav

Apache2.0HTTPweb

mod_deflate

Apache2.0

mod_auth_ldap

Apache2.0.41LDAPHTTP mod_ldap

mod_auth_digest

mod_charset_lite

Apache2.0

mod_file_cache

Apache2.0Apache1.3 mod_mmap_static

mod_headers

Apache2.0 mod_proxy

mod_proxy

HTTP/1.1 <Proxy>() <Directory

"proxy:..."> proxy_connectproxy_ftpproxy_http

mod_negotiation

ForceLanguagePriority MultiViews

mod_autoindex

HTML

mod_include

SSISSI(Perl) mod_include $0..$9

mod_auth_dbm

AuthDBMTypeDBM

Page 33: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Page 34: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

||< >|???|

Page 35: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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"formshallmeananyformresultingfrommechanical

Page 36: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

transformationortranslationofaSourceform,includingbutnotlimitedtocompiledobjectcode,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"shallmeanLicensorandanyindividualorLegal

Page 37: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

EntityonbehalfofwhomaContributionhasbeenreceivedbyLicensorandsubsequentlyincorporatedwithintheWork.

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. Youmustcauseanymodifiedfilestocarryprominent

Page 38: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

noticesstatingthatYouchangedthefiles;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.UnlessYouexplicitlystate

Page 39: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

otherwise,anyContributionintentionallysubmittedforinclusionintheWorkbyYoutotheLicensorshallbeunderthetermsandconditionsofthisLicense,withoutanyadditionaltermsorconditions.Notwithstandingtheabove,nothinghereinshallsupersedeormodifythetermsofanyseparatelicenseagreementyoumayhaveexecutedwithLicensorregardingsuchContributions.

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,oranyandallothercommercialdamagesor

Page 40: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

losses),evenifsuchContributorhasbeenadvisedofthepossibilityofsuchdamages.

9. AcceptingWarrantyorAdditionalLiability.WhileredistributingtheWorkorDerivativeWorksthereof,Youmaychoosetooffer,andchargeafeefor,acceptanceofsupport,warranty,indemnity,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

Page 41: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Unlessrequiredbyapplicablelaworagreedtoinwriting,software

distributedundertheLicenseisdistributedonan"ASIS"BASIS,

WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.

SeetheLicenseforthespecificlanguagegoverningpermissionsand

limitationsundertheLicense.

Page 42: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200614|

Page 43: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheUnixUnixWindows MicrosoftWindowsApache

Apache libtoolautoconf

(2.2.54→2.2.55)

Page 44: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

$gzip-dhttpd-NN.tar.gz

$tarxvfhttpd-NN.tar

$cdhttpd-NN

$./configure--prefix=PREFIX

$make

$makeinstall

$viPREFIX/conf/httpd.conf

$PREFIX/bin/apachectl-kstart

NN PREFIX PREFIX/usr/local/apache2

Apachehttpd

Page 45: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

50MBApache10MB

ANSI-CANSI-C (FSF)GCCGCCANSI PATHmake

HTTP(NTP) ntpdatexntpdNTP NTP

Perl5[]Perl apxsdbmmanagePerl5(5.003)PerlPerl4Perl5 --with-perlconfigure configurePerl5Apachehttpd

apr/apr-util>=1.2aprapr-utilApachehttpd aprapr-util1.01.1apr/apr-util1.2httpd apr/apr-util

#apr1.2

cdsrclib/apr

./configure--prefix=/usr/local/apr-httpd/

make

makeinstall

#apr-util1.2

cd../apr-util

./configure--prefix=/usr/local/apr-util-

httpd/--with-apr=/usr/local/apr-httpd/

make

makeinstall

#httpd

cd../../

./configure--with-apr=/usr/local/apr-httpd/-

-with-apr-util=/usr/local/apr-util-httpd/

Page 46: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 48: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachehttpdtar

$gzip-dhttpd-NN.tar.gz

$tarxvfhttpd-NN.tar

cd

Page 49: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

configure(ApacheCVS autoconflibtoolbuildconf)

./configure configure

Apache --prefixApache

ApacheBaseApache --enable-module module" mod_" --enable-module=shared(DSO) --

disable-moduleBase configure

configure configure

Apache /sw/pkg/apache mod_rewritemod_speling

DSO

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

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

--enable-rewrite=shared\

--enable-speling=shared

configureMakefile

Page 50: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

$make

Page 51: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

PREFIX( --prefix)

$makeinstall

Page 52: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

PREFIX/conf/ApacheHTTP

$viPREFIX/conf/httpd.conf

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

Page 53: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTP

$PREFIX/bin/apachectl-kstart

http://localhost/ DocumentRoot PREFIX/htdocs/

$PREFIX/bin/apachectl-kstop

Page 54: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

(releaseannouncement)CHANGES(1.3→2.02.0→2.2)API

(2.2.55→2.2.57) makeinstall configure

API configure

buildconfig.nice configure config.nice

$./config.nice

$make

$makeinstall

$PREFIX/bin/apachectl-kgraceful-stop

$PREFIX/bin/apachectl-kstart

Apache --prefix Listen

Page 55: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200614|

Page 56: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

WindowsNT/2000/XP/2003ApacheWindows95/98/MEApacheApache

Unix httpd httpd

Page 57: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Listen80(1024)Apacheroot httpdroot

httpdapachectl httpd httpd apachectl httpd

apachectlapachectl HTTPDhttpd

httpdhttpd.conf -f

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

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

DocumentRoot

Page 58: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache ErrorLog" UnabletobindtoPort..."

rootApacheweb

Page 59: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

apachectl( rc.localrc.N)rootApache

apachectlSysV startrestartstop httpd apachectl

Page 60: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

httpdapachectlApache

Page 61: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200616|

Page 62: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UnixApacheWindowsNT/2000/XP/2003 ApacheWindows9x/ME Apache

Page 63: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApachehttpdUNIX kill httpd PidFilePIDTERMHUPUSR1

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

httpd -k stoprestartgracefulgraceful-stopapachectlhttpd

httpd

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

ServerRootPidFile

Page 64: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TERMapachectl-kstop

TERMstop

Page 65: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

USR1apachectl-kgraceful

USR1graceful()

MPM StartServers StartServers

StartServers

mod_statusUSR1 () scoreboard

mod_status" G"

USR1 USR11015

Apache("") -t(httpd)root httpdroot( httpd)

Page 66: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HUPapachectl-krestart

HUPrestartTERM

mod_statusHUP

Page 67: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

WINCHapachectl-kgraceful-stop

WINCHgraceful-stop() PidFile

GracefulShutdownTimeout TERM

"" TERM PidFile apachectlhttpd

graceful-stophttpdApache

LockfileScriptSockPIDCGI httpd

rotatelogs rotatelogs

Page 68: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Apache1.2b9 ""

ScoreBoardFileScoreBoard"bind:Addressalreadyinuse"(HUP)"longlostchildcamehome!"( USR1)ScoreBoardScoreBoard

HTTP(KeepAlive)1.220

Page 69: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200611|

Page 70: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Page 71: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_mime <IfDefine>

Include

TypesConfig

Apache httpd.conf -f IncludeApache

MIME TypesConfig mime.types

Page 72: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache"\"()

(argument)"#"

apachectlconfigtest -tApache

Page 73: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_so <IfModule>

LoadModule

Apache base DSO LoadModuleApache<IfModule>

-l

Page 74: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Directory>

<DirectoryMatch>

<Files>

<FilesMatch>

<Location>

<LocationMatch>

<VirtualHost>

<Directory><DirectoryMatch><Files><FilesMatch><Location>

URL

Apache <VirtualHost>()

Page 75: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

.htaccess

AccessFileName

AllowOverride

Apache .htaccessAccessFileName .htaccess

.htaccess .htaccess

.htaccess AllowOverride.htaccess

.htaccess .htaccess

Page 76: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200615|

Page 77: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

()

URL() .htaccess

Page 78: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

()

core

mod_version

mod_proxy

<Directory>

<DirectoryMatch>

<Files>

<FilesMatch>

<IfDefine>

<IfModule>

<IfVersion>

<Location>

<LocationMatch>

<Proxy>

<ProxyMatch>

<VirtualHost>

<IfDefine><IfModule><IfVersion>

<IfDefine>httpd httpd-DClosedForNow

<IfDefineClosedForNow>

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

</IfDefine>

<IfModule>() LoadModule

MimeMagicFilesmod_mime_magic

<IfModulemod_mime_magic.c>

MimeMagicFileconf/magic

</IfModule>

<IfVersion><IfDefine><IfModule>httpd

Page 79: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<IfVersion>=2.1>

#2.1.0

</IfVersion>

<IfDefine><IfModule><IfVersion>"!"

Page 80: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UnixApache /usr/local/apache2WindowsApache "C:/ProgramFiles/ApacheGroup/Apache2"(ApacheWindows)web/usr/local/apache2/htdocs/dir/

<Directory><Files>(<DirectoryMatch><FilesMatch>)<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>

Page 81: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Location>(<LocationMatch>)" /private"URLhttp://yoursite.example.com/privatehttp://yoursite.example.com/private123

" /private"URL

<Location/private>

OrderAllow,Deny

Denyfromall

</Location>

<Location>URLApache mod_statusserver-status

<Location/server-status>

SetHandlerserver-status

</Location>

<Directory><Files><Location>Cfnmatchshell"*""?""[ seq]" seq"/"

<DirectoryMatch><FilesMatch><LocationMatch>Perl

<Directory/home/*/public_html>

OptionsIndexes

</Directory>

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

Orderallow,deny

Page 82: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Denyfromall

</FilesMatch>

<Directory><Files> <Location>

<Location>

<Location/dir/>

Orderallow,deny

Denyfromall

</Location>

http://yoursite.example.com/dir/http://yoursite.example.com/DIR/ <Directory>

Unix()

<Location/>URLURL

Page 83: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<VirtualHost>

Page 84: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Proxy><ProxyMatch>mod_proxyURL cnn.com

<Proxyhttp://cnn.com/*>

Orderallow,deny

Denyfromall

</Proxy>

Page 85: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Directory>

<DirectoryMatch><Files><FilesMatch><Location><LocationMatch>

AllowOverride<Directory>

OptionsFollowSymLinksSymLinksIfOwnerMatch

<Directory>.htaccessOptions<Files><FilesMatch>

Page 86: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

<Directory>)

2. <DirectoryMatch>( <Directory~>)

3. <Files><FilesMatch>

4. <Location><LocationMatch>

<Directory> <Directory>(1) <Directory

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

<Directory> IncludeInclude

<VirtualHost>

mod_proxy <Proxy><Directory>

( AliasesDocumentRootsURL)<Location>/<LocationMatch>

A>B>C>D>E

<Location/>

E

</Location>

<Filesf.html>

Page 87: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

D

</Files>

<VirtualHost*>

<Directory/a/b>

B

</Directory>

</VirtualHost>

<DirectoryMatch"^.*b$">

C

</DirectoryMatch>

<Directory/a/b>

A

</Directory>

<Directory> <Location>

<Location/>

Orderdeny,allow

Allowfromall

</Location>

#<Directory>

<Directory/>

Orderallow,deny

Allowfromall

Denyfrombadguy.example.com

</Directory>

Page 88: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200611|

Page 89: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

m

od_cachemod_disk_cachemod_mem_cachemod_file_cache

htcachecleanApacheweb(proxy)

Page 90: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.2 mod_cachemod_file_cacheweb(originwebserver)(proxy)HTTP

mod_cachemod_mem_cachemod_disk_cacheHTTP(content)mod_cacheHTTP mod_cache

mod_file_cacheURL mod_file_cache(file-handle)(memory-mapping)Apache

mod_file_cache CacheFileMMapStatic mod_cache

HTTP URL

Page 91: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_cache

mod_mem_cache

mod_disk_cache

mod_file_cache

CacheEnable

CacheDisable

MMapStatic

CacheFile

CacheFile

UseCanonicalName

CacheNegotiatedDocs

mod_cache mod_cacheURLURL mod_cache

mod_proxymod_rewrite[]

URL mod_cacheApache

URL mod_cache(backend)(meta-information)

UseCanonicalName On(cachekey) On(canonicalhostname)

URLURL (ServerSideIncludes)

<!---->

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

<!---->

<!--#includefile="/path/to/footer.html"-->

(SSI) virtual

(ExpiryPeriods)

Page 92: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(3600) CacheDefaultExpire

ExpiresLast-Modified mod_cache

CacheLastModifiedFactor

mod_expires

CacheMaxExpire

(ConditionalRequest)(backend)(contentprovider)Apache(conditionalrequest)

HTTP(header)"Etag:""If-Match:""Last-Modified:""If-Modified-Since:"

"If-Modified-Since:""304NotModified"

()

stat()Apache——()

Apache mod_file_cacheApache

mod_cache(cachability)

1. URL CacheEnableCacheDisable

2. HTTP200,203,300,301,410

3. HTTPGET

4. "Authorization:"

5. "Authorization:""Cache-Control:""s-maxage""must-revalidate""public"

Page 93: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

6. URL(GETHTML)"Expires:"RFC261613.9

7. 200(OK) CacheIgnoreNoLastMod"Etag""Last-Modified""Expires"

8. "Cache-Control:""private" CacheStorePrivate

9. "Cache-Control:""no-store" CacheStoreNoStore

10. "Vary:""*"()

HTTP[Inshort,anycontentwhichishighlytime-sensitive,orwhichvariesdependingontheparticularsoftherequestthatarenotcoveredbyHTTPnegotiation,shouldnotbecached.]

IP5

HTTP"Vary"

/mod_cache"Vary" mod_cache"Vary"

"Vary"

Vary:negotiate,accept-language,accept-charset

mod_cacheaccept-languageaccept-charset

Page 94: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(Authorisation)(Access&Control)mod_cache(reverse-proxy)Apache

.htaccess() mod_cache(authorised) mod_cache

IP CacheDisablemod_expires mod_cacheIP

(Localexploits)ApacheApache

ApacheCGI mod_disk_cache

Apache mod_disk_cacheApache suEXECApacheCGI

(CachePoisoning)Apache""""

ApacheDNSDNSApacheHTTP(request-smuggling)

HTTP( google)web

Page 95: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(File-HandleCaching)

mod_file_cache

mod_mem_cache

CacheFile

CacheEnable

CacheDisable

ApacheApache

(CacheFile)Apachemod_file_cache(file-handle) CacheFile

CacheFileApache

CacheFile/usr/local/apache2/htdocs/index.html

CacheFileApacheApache

ApacheApacheApacheApache

CacheEnablefdmod_mem_cache CacheEnable

CacheEnablefd/

mod_cache

Page 96: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(In-MemoryCaching)

mod_mem_cache

mod_file_cache

CacheEnable

CacheDisable

MMapStatic

Apacheswap(/)

Linux

colm@coroebus:~$timecattestfile>/dev/null

real0m0.065s

user0m0.000s

sys0m0.001s

colm@coroebus:~$timecattestfile>/dev/null

real0m0.003s

user0m0.003s

sys0m0.000s

""Apache

ApacheApache

Apache

ApacheApacheApache

MMapStaticmod_file_cacheMMapStaticApache(mmap())Apache

Page 97: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MMapStatic/usr/local/apache2/htdocs/index.html

CacheFileApache

MMapStaticApache

mod_mem_cachemod_mem_cacheHTTP MMap mod_mem_cache

#

CacheEnablemem/

#1MB

MCacheSize1024

Page 98: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(Disk-basedCaching)

mod_disk_cache CacheEnable

CacheDisable

mod_disk_cachemod_cache mod_mem_cache

CacheRoot/var/cache/apache/

CacheEnabledisk/

CacheDirLevels2

CacheDirLength1

(Cache-Store)mod_disk_cacheURL22URLCGIURL

226422^64URL xyTGxSMO2b68mBCykqkp1wURLCacheDirLevelsCacheDirLength

CacheDirLevels CacheDirLength

/var/cache/apache/x/y/TGxSMO2b68mBCykqkp1w

CacheDirLength"1"64"2"64*64"1"CacheDirLength

CacheDirLevels"2"4096100245URL

URLURL(meta-information)".header"".data"URL

"Vary"URL".vary"".data"

Page 99: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

mod_disk_cache

Apache htcacheclean htcacheclean

htcachecleancron htcacheclean(G)cron

1:

mod_disk_cache htcacheclean""

Page 100: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200616|

Page 101: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(core)

Page 102: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerName

ServerAdmin

ServerSignature

ServerTokens

UseCanonicalName

UseCanonicalPhysicalPort

ServerAdminServerTokens() ServerTokensHTTP

ServerNameUseCanonicalNameUseCanonicalPhysicalPort

URL"/"Apache"/"

Page 103: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CoreDumpDirectory

DocumentRoot

ErrorLog

LockFile

PidFile

ScoreBoardFile

ServerRoot

Apache(/) ServerRootroot

Page 104: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

LimitRequestBody

LimitRequestFields

LimitRequestFieldsize

LimitRequestLine

RLimitCPU

RLimitMEM

RLimitNPROC

ThreadStackSize

LimitRequest*Apache(DOS)

RLimit*ApacheCGISSIexec

ThreadStackSize

Page 105: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200614|

Page 106: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

WebApacheHTTP

Page 107: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheApache(root)

Page 108: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(ErrorLog)

ErrorLog

LogLevel

ErrorLogApachehttpd

(unixerror_logWindowsOS/2error.log)unix syslog

[WedOct1114:32:522000][error][client

127.0.0.1]clientdeniedbyserverconfiguration:

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

LogLevelIPWeb

CGI stderr

(accesslog)403

unix

tail-ferror_log

Page 109: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(AccessLog)

mod_log_config

mod_setenvif

CustomLog

LogFormat

SetEnvIf

CustomLog LogFormat

Web OpenDirectoryYahoo

Apachehttpdmod_log_referer,mod_log_agent TransferLog

CustomLog

Cprintf() mod_log_config

(CommonLogFormat)

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

CustomLoglogs/access_logcommon

common"%"( ")" \n"" \t"

CustomLog ServerRoot

(CLF)Web

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 HostnameLookups OnIPIP logresolve

Page 110: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IPIPIP

-(%l)identdRFC1413(identity)"-" IdentityCheck

OnApache

frank(%u)HTTP(userid) REMOTE_USERCGI401" -"

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

[//:::]

=2

=3

=4

=2

=2

=2

=(+|-)4

%{format}t formatCstrftime()

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

%U%q%H"" %r"

200(%>s)(2)(3)(4)(5) HTTP(RFC261610)

2326(%b)" -"" 0" %B

(CombinedLogFormat)

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

{Referer}i\"\"%{User-agent}i\""combined

Page 111: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CustomLoglog/access_logcombined

%{header}i header

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" /apache_pb.gif

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

"User-Agent"

CustomLogCLF CustomLogReferLogAgentLog

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

CustomLoglogs/access_logcommon

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

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

CustomLog LogFormat

SetEnvIf CustomLog env=

#

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

#robots.txt

Page 112: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SetEnvIfRequest_URI"^/robots\.txt$"dontlog

#

CustomLoglogs/access_logcommonenv=!dontlog

SetEnvIfAccept-Language"en"english

CustomLoglogs/english_logcommonenv=english

CustomLoglogs/non_english_logcommonenv=!english

Page 113: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

100001MBApache

(graceful)

mvaccess_logaccess_log.old

mverror_logerror_log.old

apachectlgraceful

sleep600

gzipaccess_log.olderror_log.old

Page 114: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachehttpd" |"Apache("")

Apachehttpdroot

rotatelogs24

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

/var/log/access_log86400"common

cronolog

Page 115: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<VirtualHost>

CustomLogErrorLog<VirtualHost> <VirtualHost>

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

CustomLoglogs/access_logcomonvhost

%v split-logfile

Page 116: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

mod_logio

mod_log_forensic

mod_cgi

mod_rewrite

LogFormat

ForensicLog

PidFile

RewriteLog

RewriteLogLevel

ScriptLog

ScriptLogBuffer

ScriptLogLength

mod_logioLogFormat(%I%O)

(ForensicLogging)mod_log_forensic(forensiclog)(forensiclogger)

PIDApachehttpd logs/httpd.pidhttpdID(processid[PID])PidFilePIDWindows-k

ScriptLogCGI mod_cgi

mod_rewrite RewriteLog RewriteLogLevel

Page 117: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200617|

Page 118: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL

ApacheURL

Page 119: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_alias

mod_proxy

mod_rewrite

mod_userdir

mod_speling

mod_vhost_alias

Alias

AliasMatch

CheckSpelling

DocumentRoot

ErrorDocument

Options

ProxyPass

ProxyPassReverse

ProxyPassReverseCookieDomain

ProxyPassReverseCookiePath

Redirect

RedirectMatch

RewriteCond

RewriteMatch

ScriptAlias

ScriptAliasMatch

UserDir

Page 120: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DocumentRoot

ApacheURL(URL) DocumentRoot

Apache DocumentRoot mod_vhost_aliasIP

Page 121: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DocumentRoot

DocumentRootApacheUnix DocumentRoot

OptionsFollowSymLinksSymLinksIfOwnerMatch

Alias

Alias/docs/var/web

URLhttp://www.example.com/docs/dir/file.html/var/web/dir/file.htmlScriptAlias CGI

AliasMatchScriptAliasMatch

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.cgiCGI

Page 122: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Unix" user"" ~user/" mod_userdirURL

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

UserDir" Userdirpublic_html"URL/home/user/public_html/file.html/home/user//etc/passwd

/etc/passwd Userdir

"~"( %7e) mod_userdir AliasMatch

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

/home/user/public_html/file.htmlAliasMatch

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

/home/$1/public_html/$2

Page 123: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL

ApacheURLURL (redirection)RedirectDocumentRoot/foo//bar/

Redirectpermanent/foo/

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

/foo/URLwww.example.com/bar/

ApacheRedirectMatch

RedirectMatchpermanent^/$

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

RedirectMatchtemp.*

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

Page 124: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheWeb() (reverseproxying)

/foo/ internal.example.com/bar/

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

ProxyPassReverse/foo/

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

ProxyPassReverseCookieDomaininternal.example.com

public.example.comProxyPassReverseCookiePath

/foo//bar/

ProxyPass ProxyPassReverseinternal.example.com

ProxyPassReverseCookieDomain

ProxyPassReverseCookieDomaincookie

internal.example.com mod_proxy_htmlHTMLXHTML

Page 125: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL

mod_rewriteURLIP(aliases) URL

Page 126: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

FileNotFound

URL URL

HTMLURLApache mod_speling"FileNotFound"

mod_spelingURLunixURL""URL

Apache"404"() ErrorDocument

Page 127: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006110|

Page 128: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Page 129: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTPApacheApacheHTTP ApacheHTTPApache

WebApacheCGI

Page 130: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerRoot

Apacheroot Userroot ServerRootrootrootServerRoot/usr/local/apacheroot

mkdir/usr/local/apache

cd/usr/local/apache

mkdirbinconflogs

chown0.binconflogs

chgrp0.binconflogs

chmod755.binconflogs

"/""/usr""/usr/local"root httpd

cphttpd/usr/local/apache/bin

chown0/usr/local/apache/bin/httpd

chgrp0/usr/local/apache/bin/httpd

chmod511/usr/local/apache/bin/httpd

htdocs--root

rootroot httpd(root)(root)

Page 131: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(SSI)

ApacheSSISSI

SSICGI"execcmd"SSICGIhttpd.confApache

SSISSI

CGIsuexecSSI

.html.htmSSISSI.shtml

SSI Options IncludesNOEXECIncludes<--#includevirtual="..."--> ScriptAliasCGI

Page 132: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI

CGICGICGIweb

CGI()ABB suEXECApache1.2ApacheCGIWrap

Page 133: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI

CGI

Page 134: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI

CGICGICGI/

CGI

Page 135: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_php,mod_perl,mod_tcl,mod_pythonApache(User)Apache

Page 136: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.htaccess

<Directory/>

AllowOverrideNone

</Directory>

.htaccess

Page 137: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheURL

#cd/;ln-s/public_html

Accessinghttp://localhost/~root/

<Directory/>

OrderDeny,Allow

Denyfromall

</Directory>

Directory

<Directory/usr/users/*/public_html>

OrderDeny,Allow

Allowfromall

</Directory>

<Directory/usr/local/httpd>

OrderDeny,Allow

Allowfromall

</Directory>

LocationDirectory <Directory/> <Location/>

UserDir"./"1.3

UserDirdisabledroot

Page 138: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

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

access_log

grep"clientdenied"error_log|tail-n10

ApacheTomcatSource.JSPMalformedRequestInformationDisclosureVulnerability

[ThuJul1117:18:392002][error][client

foo.bar.com]clientdeniedbyserver

configuration:/usr/local/apache/htdocs/.htpasswd

.htpasswd

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

/.htpasswdHTTP/1.1"

<Files~"^\.ht">

Orderallow,deny

Denyfromall

</Files>

Page 139: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200612|

Page 140: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(DSO)

ApacheHTTP httpd httpd(DSO)DSOApache(apxs)

DSO

Page 141: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_so LoadModule

ApacheDSOApachemod_so coreDSOApache --enable-module=sharedDSO mod_foo.soDSO httpd.conf

mod_soLoadModule

apxs(APacheeXtenSion)ApacheDSOApacheDSOApacheconfigure makeinstallApacheC apxsApache

DSO

Page 142: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.0DSO

1. Apache mod_foo.cmod_foo.soDSO

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

enable-foo=shared

$makeinstall

2. mod_foo.cmod_foo.soDSO

$./configure--add-

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

--enable-foo=shared

$makeinstall

3. Apache

$./configure--enable-so

$makeinstall

4. apxsApache mod_foo.cmod_foo.soDSO

$cd/path/to/3rdparty

$apxs-cmod_foo.c

$apxs-i-a-nfoomod_foo.la

httpd.confLoadModuleApache

Page 143: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Unix(DSO)/

ld.soUnix dlopen()/dlsym()

DSO (sharedlibraries)DSO(DSOlibraries) libfoo.so

libfoo.so.1.2( /usr/lib) -lfoo -RLD_LIBRARY_PATHUnix /usr/liblibfoo.soDSO

DSO()DSOUnix( ld.so) libc.so

DSO (sharedobjects) DSO(DSOfiles)( foo.so)dlopen()DSODSOUnixDSODSO( libc.so)DSO

DSOAPI dlsym()DSO ()

DSODSO()DSO""DSO()DSODSO

DSO

1998DSOPerl5(XSDynaLoader)NetscapeServer1.3ApacheApache(dispatch-list-based)ApacheApacheDSO

Page 144: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DSO

httpd.confLoadModule Apache(&SSL&[mod_perlPHP])ApachePHPmod_perlmod_fastcgiApacheDSO apxsApache apxs-i apachectl

restartApache

DSO

DSOUnix20%(positonindependentcode[PIC])5%DSODSO(ld-lfoo)a.outELFDSODSOApacheC( libc)Apache( libfoo.a)Apachedlopen()

Page 145: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200612|

Page 146: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTP/1.1

mod_negotiation

Page 147: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(ContentNegotiation)

Accept-Language:fr

HTMLGIFJPEG

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"" AcceptAccept-LanguageAccept-

CharsetAccept-EncodingRFC2295RFC2296RFC""

(resource)URI(RFC2396)HTTPApache (representation)

Page 148: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

( *.var)"MultiViews"

type-map(Apache MIMEapplication/x-type-map)type-map

AddHandlertype-map.var

(entry)HTTP() foofoo.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 On"qs"jpeg,gif,ASCII-art

URI:foo

URI:foo.jpeg

Content-type:image/jpeg;qs=0.8

URI:foo.gif

Content-type:image/gif;qs=0.5

Page 149: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URI:foo.txt

Content-type:text/plain;qs=0.01

qs0.0001.0000.000qsqs1.0qs""jpegASCII-artjpegqs

mod_negotationHTTP

MultiviewsMultiViews httpd.conf.htaccess( AllowOverride)<Directory><Location><Files> Options Options

AllMultiViews

MultiViews /some/dir/foo /some/dir/foo

/some/dirMultiViewsfoo.*foo.*

MultiViews DirectoryIndex

DirectoryIndexindex

index.htmlindex.html3 index.cgi

mod_mime MultiViewsMatchMultiViews

Page 150: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache""Apache

1. Apache()Apache""(dimension)

2. RFC2295""ApacheRFC2296""

(Dimension)

Accept("qs")Accept-Language

Accept-Encoding

Accept-Charset

ApacheApache""

1. Accept* Accept*4

2. ""3

1. Accept

2.

3. Accept-Language() LanguagePriority()

4. ""(text/html)

5. Accept-CharsetISO-8859-1 text/*ISO-8859-1

6. ISO-8859-1

7.

8.

Page 151: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

9. ASCII

3. ""HTTP Vary()

4. ()406HTMLHTTP Vary

Page 152: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheApache Accept

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

Accept:image/*,*/*

"image/"("image/*")

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

image/jpeg,*/*

"*/*""*.*"()0.01

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

image/jpeg,*/*;q=0.01

1.0"*/*"0.01

Accept:qApache"*/*"q0.01"type/*"q0.02"*/*"Accept:q

Apache2.0

Accept-language"NoAcceptableVariant""MultipleChoices"Apache Accept-language

ForceLanguagePriority LanguagePriority

en-GBHTTP/1.1 en( Accept-Languageen-GBen

)"NoAcceptableVariants"LanguagePriorityApache"en-GB;q=0.9,fr;q=0.8"

Page 153: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

"fr"HTTP/1.1

(cookiesURL)2.0.47 mod_negotiationprefer-language

mod_negotiation

SetEnvIfCookie"language=(.+)"prefer-language=$1

Page 154: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache{encoding..}(RFC2295)RVSA/1.0(RFC2296)Accept-EncodingRVSA/1.0

Page 155: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

( mod_mime)

MIME( html)( gz)( en)

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)rsp. htmlshtmlcgi

MIME( foo.html)()MIME( foo.html.en)

Page 156: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL(representation)URLApacheHTTP/1.1ApacheHTTP/1.1

HTTP/1.0() CacheNegotiatedDocsHTTP/1.1

HTTP/1.1Apache Vary force-no-vary

Page 157: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AlanJ.Flavell LanguageNegotiationNotesApache2.0

Page 158: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200612|

Page 159: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

"500ServerError"URL()

Page 160: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache1.3

1.

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.059000/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_URLREDIRECT_QUERY_STRINGURL(URLcgicgi)ErrorDocument( http:)

Page 161: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ErrorDocument .htaccessAllowOverride

...

ErrorDocument500/cgi-bin/crash-recover

ErrorDocument500"Sorry,ourscriptcrashed.Oh

dear"

ErrorDocument500http://xxx/

ErrorDocument404/Lame_excuses/not_found.html

ErrorDocument401

/Subscription/how_to_subscribe.html

ErrorDocument<3><action>

<action>

1. (")

2. URL

3. URL

Page 162: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheURL/

CGI

" REDIRECT_" REDIRECT_*CGI" REDIRECT_"HTTP_USER_AGENTREDIRECT_HTTP_USER_AGENTApache

REDIRECT_URLREDIRECT_STATUSURLURL

ErrorDocumentCGI" Status:"Perl ErrorDocument

...

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

printf"Status:%s<>\n",$ENV{"REDIRECT_STATUS"};

...

404NotFound

" Location:"() " Status:"( 302Found)" Location:"

Page 163: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200611|

Page 164: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(Binding)

Apache

Page 165: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

core

mpm_common

<VirtualHost>

Listen

ApacheIP()

Listen(+) ListenIP+ Listen

808000

Listen80

Listen8000

+

Listen192.170.2.1:80

Listen192.170.2.5:8000

IPv6

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

Page 166: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IPv6

IPv6APRIPv6ApacheIPv6IPv6

ApacheIPv6IPv4IPv6IPv6IPv4IPv6IPv4(IPv4-mappedIPv6addresses)FreeBSDNetBSDOpenBSDApache

(LinuxTru64)IPv6IPv4 (mappedaddresses)ApacheIPv4IPv6IPv4IPv6 --enable-v4-mapped

FreeBSDNetBSDOpenBSD --enable-v4-mappedApache

ApacheIPv4APR ListenIPv4

Listen0.0.0.0:80

Listen192.170.2.1:80

IPv6IPv4ApacheIPv4IPv6() --disable-v4-mapped -

-disable-v4-mappedFreeBSDNetBSDOpenBSD

Page 167: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Listen(mainserver) <VirtualHost>

<VirtualHost> <VirtualHost>

<VirtualHost>

Page 168: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200615|

Page 169: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Page 170: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTPApache

Apache2.0web(MPM)

Apache mpm_winntApache1.3POSIXWindowsApacheMPM

workereventMPM prefork

MPMApacheMPMMPM

Page 171: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MPM

MPMMPMUnixMPMApacheApache

configure --with-mpm=NAMEMPM NAMEMPM

./httpd-lMPMMPM

Page 172: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

MPM

MPMMPM

BeOS beos

Netware mpm_netware

OS/2 mpmt_os2

Unix prefork

Windows mpm_winnt

Page 173: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200613|

Page 174: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

ApacheHTTP (environmentvariable)CGI

ApacheCGI(SSI)shell

Page 175: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_env

mod_rewrite

mod_setenvif

mod_unique_id

BrowserMatch

BrowserMatchNoCase

PassEnv

RewriteRule

SetEnv

SetEnvIf

SetEnvIfNoCase

UnsetEnv

Apache SetEnv PassEnvApacheshell

mod_setenvif(User-Agent)"Referer:"mod_rewriteRewriteRule [E=...]

mod_unique_idUNIQUE_ID""

CGIApacheshellCGISSI CGI

CGIsuexecCGICGI suexec.cCGISSI

Page 176: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_authz_host

mod_cgi

mod_ext_filter

mod_headers

mod_include

mod_log_config

mod_rewrite

Allow

CustomLog

Deny

ExtFilterDefine

Header

LogFormat

RewriteCond

RewriteRule

CGICGICGIApache CGI

SSImod_includeINCLUDES(Server-parsed[SSI])echoApacheCGISSI SSI

allowfromenv= denyfromenv= SetEnvIf

(User-Agent)

LogFormat" %e" CustomLog SetEnvIf gif

HeaderHTTP

Page 177: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_ext_filterExtFilterDefine disableenv=enableenv=

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

Page 178: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache BrowserMatchSetEnvPassEnv

downgrade-1.0HTTP/1.0

force-gzipDEFLATEaccept-encodinggzip

force-no-varyVary force-response-1.0

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

gzip-only-text/html"1" text/htmlmod_deflateDEFLATE

mod_negotiation(gzip"")

no-gzipmod_deflateDEFLATE mod_negotiation

nokeepaliveKeepAlive

prefer-languagemod_negotiation( enfrzh_cnx-) mod_negotiation

redirect-carefully

Page 179: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

WebFoldersDAV

suppress-error-charset2.0.54

Apache()ApacheISO-8859-1

Apache

force-proxy-request-1.0,proxy-nokeepalive,proxy-sendchunked,proxy-sendclmod_proxy mod_proxy

Page 180: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httpd.conf

#HTTP

#Netscape2.xkeepalive

#IE4.0HTTP/1.1301/302()keepalive

BrowserMatch"Mozilla/2"nokeepalive

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

#HTTP/1.0HTTP/1.1

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

""/web/images

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

#Referer

SetEnvIfReferer"^$"local_referal

<Directory/web/images>

OrderDeny,Allow

Denyfromall

Allowfromenv=local_referal

Page 182: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200614|

Page 183: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Apache

Page 184: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(Handler)

mod_actions

mod_asis

mod_cgi

mod_imagemap

mod_info

mod_mime

mod_negotiation

mod_status

Action

AddHandler

RemoveHandler

SetHandler

""Apache""

Apache1.1 ( )

Action

default-handlerdefault_handler()( core)send-as-isHTTP( mod_asis)cgi-scriptCGI( mod_cgi)imap-file( mod_imagemap)server-info( mod_info)server-status( mod_status)type-map( mod_negotiation)

Page 185: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGIhtmlCGI footer.pl

Actionadd-footer/cgi-bin/footer.pl

AddHandleradd-footer.html

CGI( PATH_TRANSLATED)

HTTPsend-as-isHTTP /web/htdocs/asis/ send-

as-is

<Directory/web/htdocs/asis>

SetHandlersend-as-is

</Directory>

Page 186: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheAPI ApacheAPI

char*handler

invoke_handler r->handler"-""/"

Page 187: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200613|

Page 188: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(Filter)

Apache

Page 189: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2

mod_filter

mod_deflate

mod_ext_filter

mod_include

mod_charset_lite

FilterChain

FilterDeclare

FilterProtocol

FilterProvider

AddInputFilter

AddOutputFilter

RemoveInputFilter

RemoveOutputFilter

ExtFilterDefine

ExtFilterOptions

SetInputFilter

SetOutputFilter

Apache2.0(post-process)

Page 190: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

mod_include

mod_sslSSL(https)mod_deflate/mod_charset_lite

mod_ext_filter

Apache(byte-rangehandling)

modules.apache.org

HTMLXMLXSLTXIncludesXMLHTML

PHP

Page 191: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.1mod_filterHTMLJPEG(filterharness)(provider)(provider)

HTMLtext/htmlapplication/xhtml+xml

Page 192: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

()

AddInputFilter,AddOutputFilter,RemoveInputFilter,RemoveOutputFilter

mod_filter FilterChain,FilterDeclare,FilterProvider

AddOutputFilterByType

Page 193: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200616|

Page 194: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

suEXEC

suEXECApachewebCGISSICGISSIweb

CGISSI setuidrootsuEXEC

Page 195: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

UNIX setuidsetgidsuEXEC

setuid/setgid

suEXECsuEXEC Apache

Apache suEXECsuEXECsuEXECsuEXECApachesuEXEC

suEXEC

Page 196: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

suEXEC

suEXECsuEXEC

suEXECsetuid""""ApachewebHTTP""CGISSIApacheUIDGIDsuEXEC

(wrapper)("""CGI/SSI")

1.

2.

ApachewebApachesuEXEC

3.

(Apache)

4. CGI/SSI

CGI/SSI"/"".."suEXEC( --with-

suexec-docroot=DIR)

5.

6.

7.

suEXECrootCGI/SSI

8. UIDUID

Page 197: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UIDCGI/SSIUID

9.

suEXECrootCGI/SSI

10. GIDGID

GIDCGI/SSIGID

11.

setuidsetgid

12.

13. Apache

suEXECsuEXEC( suEXEC)

14.

15. CGI/SSI

16. CGI/SSI

17. setuidsetgid

UID/GID

18.

Page 198: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

19.

suEXEC()()

20.

suEXEC

suEXECCGI/SSI

suEXEC

Page 199: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

suEXEC

...

suEXEC

--enable-suexec

suEXEC --with-suexec-xxxxxAPACIsuEXEC

--with-suexec-bin=PATH

suexec --with-suexec-bin=/usr/sbin/suexec

--with-suexec-caller=UID

ApacheUID

--with-suexec-userdir=DIR

suEXECsuEXEC"""" UserDir("*")UserDir"passwd"suEXEC"public_html" UserDir

"~userdir"cgi--with-suexec-docroot=DIR

ApacheDocumentRootUserDirsuEXEC --datadir"/htdocs"" --datadir=/home/apache""/home/apache/htdocs"suEXEC

--with-suexec-uidmin=UID

suEXECUID500100100

--with-suexec-gidmin=GID

suEXECGID100100

--with-suexec-logfile=FILE

suEXEC()"suexec_log"( --logfiledir)

--with-suexec-safepath=PATH

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

suEXEC --enable-suexecsuEXEC make(Apache) suexec

makeinstall suexec --sbindir"/usr/local/apache2/sbin/suexec"

Page 200: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

rootsuEXECUID root1()

suEXEC --with-suexec-callersuEXECApachesuEXEC

web-server

Userwww

Groupwebgroup

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

chgrpwebgroup/usr/local/apache2/bin/suexec

chmod4750/usr/local/apache2/bin/suexec

ApachesuEXEC

Page 201: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

suEXEC

Apache --sbindir("/usr/local/apache/sbin/suexec")suexecApachesuEXEC

[notice]suEXECmechanismenabled(wrapper:

/path/to/suexec)

setuidroot

ApachesuEXECApacheHUPUSR1

suEXEC suexecApache

Page 202: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

suEXEC

CGIsuEXEC SuexecUserGroup mod_userdir

suEXECVirtualHostSuexecUserGroupUIDCGI<VirtualHost>UserGroup <VirtualHost>UID

mod_userdirsuEXECUIDCGICGI --with-

suexec-userdir

Page 203: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

suEXEC

suEXEC --with-suexec-logfile

Page 204: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Jabberwock

Apache

suEXEC"bugs"

suEXEC

suEXEC4ApachesuEXEC()

suEXECPATH

suEXEC

Page 205: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006321|

Page 206: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.0webApache2.0

Apache1.32.0Apache2.0httpd

Page 207: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

webweb"""""" MaxClients

topApache

CPU""

TCP

sendfile()(LinuxLinux2.4Solaris8)sendfileApache2CPU

Page 208: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_dir

mpm_common

mod_status

AllowOverride

DirectoryIndex

HostnameLookups

EnableMMAP

EnableSendfile

KeepAliveTimeout

MaxSpareServers

MinSpareServers

Options

StartServers

HostnameLookupsDNSApache1.3 HostnameLookups OnDNSApache1.3Off logresolveDNS

web

" Allowfromdomain"" Denyfromdomain"( domainIP)DNS()(IP)

<Location/server-status>DNS .html.cgiDNS

HostnameLookupsoff

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

HostnameLookupson

</Files>

CGIDNS gethostbyname

FollowSymLinksSymLinksIfOwnerMatch

Page 209: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

OptionsFollowSymLinks Options

SymLinksIfOwnerMatchApache

DocumentRoot/www/htdocs

<Directory/>

OptionsSymLinksIfOwnerMatch

</Directory>

" /index.html"Apache" /www"" /www/htdocs"" /www/htdocs/index.html"lstat() lstat()

DocumentRoot/www/htdocs

<Directory/>

OptionsFollowSymLinks

</Directory>

<Directory/www/htdocs>

Options-FollowSymLinks+SymLinksIfOwnerMatch

</Directory>

DocumentRoot AliasRewriteRuleDocumentRoot

FollowSymLinks

AllowOverride( .htaccess)Apache .htaccess

DocumentRoot/www/htdocs

<Directory/>

AllowOverrideall

</Directory>

" /index.html"Apache" /.htaccess"" /www/.htaccess"" /www/htdocs/.htaccess"

Page 210: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

OptionsFollowSymLinks AllowOverrideNone

DirectoryIndexindex

DirectoryIndexindex.cgiindex.plindex.shtml

index.html

type-map" OptionsMultiViews" type-map

Apache2.0 mmap()

httpd

CPU mmapread()Solaris mmapApache2.0

NFSNFS

EnableMMAPoff

SendfileApache2.0() sendfile()Apachesendfile()

sendfilesendfilehttpd

Apachesendfilesendfile

Page 211: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

NFScache

" EnableSendfileoff"sendfile

Apache1.3 MinSpareServers,MaxSpareServers,StartServersApache"" StartServers

MinSpareServers100 StartServers59510

""Apache1.3""32MinSpareServers

MinSpareServers,MaxSpareServers,StartServers4ErrorLog mod_status

MaxRequestsPerChild" 0"30SunOSSolaris10000

KeepAliveTimeout5 60 mostofthebenefitsarelost

Page 212: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MPMApache2.x (MPM)ApacheMPMUNIXMPM beos,mpm_netware,mpmt_os2,mpm_winntUNIXMPMhttpd

workerMPMMPM preforkMPMpreforkMPM workerMPM workerMPM(php3/4/5) workerMPM

MPM

DSO LoadModule

ApacheApache

mod_mime,mod_dir,mod_log_configmod_log_config

mod_cacheworkerAPR(Apache)APIAPI

APROS/CPUCPU(compare-and-swap,CAS)APRAPICASCPUCPUApache

./buildconf

./configure--with-mpm=worker--enable-

nonportable-atomics=yes

--enable-nonportable-atomics

SPARCSolaris

Page 213: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

APR --enable-nonportable-atomics

SPARCv8plusCASUltraSPARCCPUx86LinuxAPRLinux --enable-nonportable-atomics

APR486CAS486CPU

mod_status"ExtendedStatusOn"Apachemod_status" ExtendedStatusOn"Apachegettimeofday()( times())(1.3) time()

" ExtendedStatusoff"()

socketaccept

Apache2.0

UnixsocketAPIweb ListenApache select()socketselect()socketApache()

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)

Page 214: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

{

if(FD_ISSET(i,&accept_fds)){

new_connection=accept(i,NULL,NULL);

if(new_connection!=-1)break;

}

}

if(new_connection!=-1)break;

}

processthenew_connection;

}

"" selectaccept() acceptsocket"" PR#467

socketCPU select109 accept select

socket selectCPU

Apache()

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

Page 215: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

new_connection=accept(i,NULL,NULL);

if(new_connection!=-1)break;

}

}

if(new_connection!=-1)break;

}

accept_mutex_off();

processthenew_connection;

}

accept_mutex_onaccept_mutex_off src/conf.h(1.3) src/include/ap_config.h(1.3) Listen

AcceptMutex

AcceptMutexflock

flock()( LockFile)

AcceptMutexfcntl

fcntl()( LockFile)

AcceptMutexsysvsem

(1.3)SysVSysVApache( ipcs()manpage)APIuidCGI(CGI

AcceptMutexpthread

(1.3)POSIXPOSIXSolaris2.5

AcceptMutexposixsem

(2.0)POSIXsegfault

APR(Apache)

Listen

Page 216: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

socketacceptsocketsocket accept()""TCPacceptsocket

socketLinux(2.0.30Pentiumpro166/128MRAM)socket3%100msLANsocketSINGLE_LISTEN_UNSERIALIZED_ACCEPTsocket

draft-ietf-http-connection-00.txtsection8HTTP (TCP)1.2Apache

UnixTCP FIN_WAIT_2Apache1.2 FIN_WAIT_2

TCP/IP(SunOS4--)

socket SO_LINGERTCP/IP(Linux2.0.31)

Apachelingering_close( http_main.c)

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

Page 217: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

break;

}

/*justtossawaywhateverishere*/

}

}

close(s);

}

HTTP/1.1 NO_LINGCLOSEHTTP/1.1lingering_close

ScoreboardApachescoreboard() src/main/conf.h

USE_MMAP_SCOREBOARDUSE_SHMGET_SCOREBOARD(HAVE_MMAPHAVE_SHMGET)()

LinuxApache1.2ApacheLinux

DYNAMIC_MODULE_LIMIT() -DDYNAMIC_MODULE_LIMIT=0

Page 218: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Solaris8MPMApache2.0.38

truss-l-phttpd_child_pid.

-ltrussLWP(lightweightprocess--Solaris)ID

strace,ktrace,par

httpd10KB()

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

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

LWP#67

accept()MPMaccept

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

/67:lwp_unpark(65,1)=0

LWP#65

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

Apachesocket( Listen)

/65:brk(0x002170E8)=0

/65:brk(0x002190E8)=0

brk()httpd( apr_poolapr_bucket_alloc)httpdmalloc()

Page 219: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

/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

setsockopt()getsockopt()Solarislibcsocketfcntl()

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

/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

httpd" OptionsFollowSymLinks"" AllowOverride

None" lstat().htaccess stat()

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

httpd sendfilev()HTTPSendfile sendfile()

write()writev()

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

write() time()Apache1.3Apache2.0gettimeofday()LinuxSolaris gettimeofday

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

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

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

Page 220: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

/65:close(9)=0

/65:close(10)=0

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

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

(MPM) accept()()

Page 221: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006321|

Page 222: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL

OriginallywrittenbyRalfS.Engelschall<[email protected]>December1997

mod_rewriteURLURL

Page 223: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_rewrite

Apachemod_rewriteURLURL mod_rewriteApachemod_rewrite mod_rewrite

Page 224: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL

mod_aliasmod_userdir[PT].htaccess

Page 225: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL

URL

webURLURLURLURL

URLHTTP/u/user/~user/u/user

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

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

www.example.comexample.com

#80

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]

#80

RewriteCond%{HTTP_HOST}!^fully\.qualified\.domain\.name[NC]

RewriteCond%{HTTP_HOST}!^$

RewriteRule^/(.*)http://fully.qualified.domain.name/$1[L,R]

DocumentRoot

web DocumentRootURL"/"Intranet/e/www/(WWW)/e/sww/(Intranet) DocumentRoot

/e/www/

Page 226: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL"/""/e/www/"mod_rewriteURLAliases(mod_alias)DocumentRootURLmod_rewrite

RewriteEngineon

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

RedirectMatch

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

/~quux/foo/~quux/foo/fooCGIURL

URL/~quux/foo/index.htmlimage.gif/~quux/image.gif

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo$foo/[R]

.htaccess

RewriteEngineon

RewriteBase/~quux/

RewriteCond%{REQUEST_FILENAME}-d

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

Page 227: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL

IntranetWWWURLURL()WWWURL

()

user1server_of_user1

user2server_of_user2

::

map.xxx-to-hostURLURL

/u/user/anypath

/g/group/anypath

/e/entity/anypath

http://physical-host/u/user/anypath

http://physical-host/g/group/anypath

http://physical-host/e/entity/anypath

(server0)

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}

Page 228: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

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

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

web

webwebweb

webURL"/~user/anypath"http://newserver/~user/anypath

RewriteEngineon

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

/~foo/anypath/home/ f/foo/.www/anypath/~bar/anypath/home/ b/bar/.www/anypath

~

RewriteEngineon

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

net.sw1992Unix

drwxrwxr-x2netswusers512Aug318:39Audio/

drwxrwxr-x2netswusers512Jul914:37Benchmark/

Page 229: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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/

19967Web""CGIFTPWebCGI

CGI/e/netsw/.www/

-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

"DATA"net.swrdistURLCGIURL"DATA"DocumentRootURL"/net.sw/""/e/netsw"

Page 230: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

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

/e/netsw/.www/.wwwacl

OptionsExecCGIFollowSymLinksIncludesMultiViews

RewriteEngineon

#"/net.sw/"

RewriteBase/net.sw/

#cgi

RewriteRule^$netsw-home.cgi[L]

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

#perdir

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

#

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]

#cgi

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

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

1. L()("-")

2. !()C()

Page 231: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

3.

NCSAmod_imap

NCSAwebApachewebNCSAApache mod_imagemap

/cgi-bin/imagemap/path/to/page.mapimagemapApache/path/to/page.map

RewriteEngineon

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

webMultiViews

RewriteEngineon

#custom/...

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

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

#pub/...

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

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

#AliasScriptAlias...

RewriteRule^(.+)-[PT]

Page 232: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL

CGIURL

XSSICGI"/foo/S=java/bar/"URL/foo/bar/STATUS"java"

RewriteEngineon

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

usernamewww.username.host.domain.comDNS

HTTP/1.0HTTP/1.1HTTPhttp://www.username.host.com/anypath/home/username/anypath

RewriteEngineon

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

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

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

ourdomain.comURLwebwww.somewhere.com

RewriteEngineon

Page 233: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

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

URLweb

URLwebABPerlCGI ErrorDocument

mod_rewrite ErrorDocumentCGI!

RewriteEngineon

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

RewriteRule^(.+)http://

DocumentRoot()

RewriteEngineon

RewriteCond%{REQUEST_URI}!-U

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

mod_rewrite""(look-ahead)URLwebwebCPU ErrorDocument

URL()ApacheURLuri_escape()(anchor)"url#anchor"URL mod_rewriteURL?

NPH-CGINPH(HTTP)()URL"xredirect:"

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

Page 234: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

"xredirect:"URLnph-xredirect.cgi

#!/path/to/perl

##

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

##

$|=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##

URL mod_rewrite"news:newsgroup"

RewriteRule^anyurlxredirect:news:newsgroup

[R][R,L]"xredirect:"""

Page 235: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

http://www.perl.com/CPANCPAN(Perl)CPANFTPFTPCPANCGI mod_rewrite

mod_rewrite3.0.0"ftp:" RewriteMap

RewriteEngineon

RewriteMapmultiplextxt:/path/to/map.cxan

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

RewriteRule^.+\.([a-zA-Z]+)::(.*)$${multiplex:

##

##map.cxan--MultiplexingMapforCxAN

##

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

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

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

:

##EOF##

CGI mod_rewrite

TIME_xxx"<STRING",">STRING""=STRING"

RewriteEngineon

RewriteCond%{TIME_HOUR}%{TIME_MIN}>0700

Page 236: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteCond%{TIME_HOUR}%{TIME_MIN}<1900

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

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

URLfoo.html07:00-19:00foo.day.htmlfoo.night.html...

YYYYXXXX

.html.phtml.YYYY.XXXXURL()

#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

Page 237: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL():

bar.htmlfoo.htmlURLURL

:URL

RewriteEngineon

RewriteBase/~quux/

RewriteRule^foo\.html$bar.html

URL():

bar.htmlfoo.htmlURLURL

:HTTP

RewriteEngineon

RewriteBase/~quux/

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

:NetscapeLynx

:HTTP"User-Agent"HTTP"User-Agent""Mozilla/3" foo.htmlfoo.NS.html"Lynx"12"Mozilla" foo.20.htmlfoo.32.html

Page 238: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteCond%{HTTP_USER_AGENT}^Mozilla/3.*

RewriteRule^foo\.html$foo.NS.html[

RewriteCond%{HTTP_USER_AGENT}^Lynx/.*[OR]

RewriteCond%{HTTP_USER_AGENT}^Mozilla/[12].*

RewriteRule^foo\.html$foo.20.html[

RewriteRule^foo\.html$foo.32.html[

:FTP mirrorwebHTTP webcopy

()

:( ProxyThroughput)(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

:...

:

RewriteEngineon

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

Page 239: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Intranet:

()Intranet( www2.quux-corp.dom)()Internetweb(www.quux-corp.dom)

:(packet-filtering)

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

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

mod_rewrite

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

RewriteCond%{REQUEST_FILENAME}!-f

RewriteCond%{REQUEST_FILENAME}!-d

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

:www.foo.comwww[0-5].foo.com(6)?

:“DNS” mod_rewrite:

1. DNS(DNSRound-Robin)BINDDNS www[0-9].foo.comDNSA()

www0INA1.2.3.1

www1INA1.2.3.2

Page 240: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

www2INA1.2.3.3

www3INA1.2.3.4

www4INA1.2.3.5

www5INA1.2.3.6

:

wwwINCNAMEwww0.foo.com.

INCNAMEwww1.foo.com.

INCNAMEwww2.foo.com.

INCNAMEwww3.foo.com.

INCNAMEwww4.foo.com.

INCNAMEwww5.foo.com.

INCNAMEwww6.foo.com.

BIND www.foo.com BINDwww0-

www6/DNS www.foo.comwwwN.foo.com

www.foo.com

2. DNSDNShttp://www.stanford.edu/~schemers/docs/lbnamed/lbnamed.htmllbnamedPerl5DNS

3. (ProxyThroughputRound-Robin)mod_rewriteDNS www0.foo.comwww.foo.com

wwwINCNAMEwww0.foo.com.

www0.foo.comURL5( www1-www5)URLlb.pl

RewriteEngineon

Page 241: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteMaplbprg:/path/to/lb.pl

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

lb.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##

www0.foo.comSSICGIePerl

4. /TCPCiscoLocalDirectorTCP/IP

:

Page 242: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

...

:

##

##apache-rproxy.conf--ApacheconfigurationforReverseProxyUsage

##

#servertype

ServerTypestandalone

Listen8000

MinSpareServers16

StartServers16

MaxSpareServers16

MaxClients16

MaxRequestsPerChild100

#serveroperationparameters

KeepAliveon

MaxKeepAliveRequests100

KeepAliveTimeout15

Timeout400

IdentityCheckoff

HostnameLookupsoff

#pathstoruntimefiles

PidFile/path/to/apache-rproxy.pid

LockFile/path/to/apache-rproxy.lock

ErrorLog/path/to/apache-rproxy.elog

CustomLog/path/to/apache-rproxy.dlog"%{%v/%T}t%h->%{SERVER}eURL:%U"

#unusedpaths

ServerRoot/tmp

DocumentRoot/tmp

CacheRoot/tmp

RewriteLog/dev/null

TransferLog/dev/null

Page 243: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TypesConfig/dev/null

AccessConfig/dev/null

ResourceConfig/dev/null

#speedupandsecureprocessing

<Directory/>

Options-FollowSymLinks-SymLinksIfOwnerMatch

AllowOverrideNone

</Directory>

#thestatuspageformonitoringthereverseproxy

<Location/apache-rproxy-status>

SetHandlerserver-status

</Location>

#enabletheURLrewritingengine

RewriteEngineon

RewriteLogLevel0

#definearewritingmapwithvalue-listswhere

#mod_rewriterandomlychoosesaparticularvalue

RewriteMapserverrnd:/path/to/apache-rproxy.conf-servers

#makesurethestatuspageishandledlocally

#andmakesurenooneusesourproxyexceptourself

RewriteRule^/apache-rproxy-status.*-[L]

RewriteRule^(http|ftp)://.*-[F]

#nowchoosethepossibleserversforparticularURLtypes

RewriteRule^/(.*\.(cgi|shtml))$to://${server:dynamic}/$1[S=1]

RewriteRule^/(.*)$to://${server:static}/$1

#anddelegatethegeneratedURLbypassingit

#throughtheproxymodule

RewriteRule^to://([^/]+)/(.*)http://$1/$2[E=SERVER:$1,P,L]

Page 244: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

#andmakereallysureallotherstuffisforbidden

#whenitshouldsurvivetheaboverules...

RewriteRule.*-[F]

#enabletheProxymodulewithoutcaching

ProxyRequestson

NoCache*

#setupURLreversemappingforredirectreponses

ProxyPassReverse/http://www1.foo.dom/

ProxyPassReverse/http://www2.foo.dom/

ProxyPassReverse/http://www3.foo.dom/

ProxyPassReverse/http://www4.foo.dom/

ProxyPassReverse/http://www5.foo.dom/

ProxyPassReverse/http://www6.foo.dom/

##

##apache-rproxy.conf-servers--Apache/mod_rewriteselectiontable

##

#listofbackendserverswhichservestatic

#pages(HTMLfilesandImages,etc.)

staticwww1.foo.dom|www2.foo.dom|www3.foo.dom|www4.foo.dom

#listofbackendserverswhichservedynamically

#generatedpage(CGIprogramsormod_perlscripts)

dynamicwww5.foo.dom|www6.foo.dom

MIME:

CGIApacheMEMECGIURL( PATH_INFO

QUERY_STRINGS) .scgi(CGI) cgiwrapURL()URL /u/user/foo/bar.scgicgiwrap/~user/foo/bar.scgi/

Page 245: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

.../internal/cgi/user/cgiwrap/~$1/$2.scgi$3[NS,

wwwlog( access.logURL) wwwidx(URLGlimpse)URL /u/user/foo/swwidx

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

CGI

:URLCGI

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

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

/u/user/foo/

HREF="*"

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

" :log"CGI

:foo.htmlfoo.cgi/

:URLCGI-scriptCGI-scriptMIME /~quux/foo.html

/~quux/foo.cgi

Page 246: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteEngineon

RewriteBase/~quux/

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

:()CGI(cronjob)

:

RewriteCond%{REQUEST_FILENAME}!-s

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

page.htmlnullpage.htmlpage.cgi page.cgi

page.html( STDOUT)CGI page.html page.html

(cronjob)

:

:!MIMEwebNPH mod_rewriteURLURLURL" :refresh"

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

URL

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

Page 247: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URL

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

NPH-CGI""

#!/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);

}

Page 248: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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;

Page 249: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

&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##

Page 250: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

:Apache<VirtualHost>ISP

:(ProxyThroughput)(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

Page 251: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

#viaahugeandcomplicatedsinglerule:

#

#1.makesurewedon'tmapforcommonlocations

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

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

:

RewriteCond%{REQUEST_URL}!^/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}}]

:

Page 252: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Robots:

robot /robots.txt"robot"robot

:/~quux/foo/arc/()robotrobotHTTPUser-Agent

RewriteCond%{HTTP_USER_AGENT}^NameOfBadRobot.*

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

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

:http://www.quux-corp.de/~quux/

:100%HTTPReferer

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]

:

Page 253: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

:

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]

:Apache

:Apacheweb mod_rewritemod_proxy mod_proxy

...

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

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

...user@host-dependent:

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

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

:( mod_authz_host)

:

RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}!^[email protected]\.com$

RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}!^friend2

Page 254: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}!^friend3

RewriteRule^/~quux/only-for-friends/-[F]

(Referer):

HTTP"Referer"?

:...

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]

...:

##

##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/

(" -")(URL)URL

Page 255: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

:mod_rewriteFOO/BAR/QUUX/

:RewriteMapRewriteMapApache STDINURL()URL() STDOUT

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$_;

}

URL /~quux/foo/... /~quux/bar/...

Page 256: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006118|

Page 257: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 258: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP

IPIPIPHTTPIP

DNSIPApacheHTTPIPIPIP

"Host"HTTP/1.1HTTP/1.0SSLSSLIP

Page 259: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

core DocumentRoot

NameVirtualHost

ServerAlias

ServerName

ServerPath

<VirtualHost>

IP() NameVirtualHostIP" *" NameVirtualHost

(SSL)" *:80" NameVirtualHost

IP

<VirtualHost> <VirtualHost>NameVirtualHost(IP" *") <VirtualHost> ServerNameDocumentRoot

(Mainhost)

web <VirtualHost> ServerNameDocumentRoot

ServerNameDocumentRoot

www.domain.tldIP 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

Page 260: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DocumentRoot/www/otherdomain

</VirtualHost>

IP NameVirtualHost<VirtualHost>" *"IPIPIP

ServerAlias<VirtualHost> <VirtualHost>

ServerAliasweb

ServerAliasdomain.tld*.domain.tld

domain.tldwww.domain.tld" *"" ?" ServerName

ServerAliasDNSIP

<VirtualHost> <VirtualHost> (mainserver)(<VirtualHost>)

NameVirtualHostIPIP <VirtualHost>

ServerNameServerAliasIP

IP NameVirtualHost DocumentRoot

<VirtualHost>

Page 261: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

IP( )

Host

ServerPath

NameVirtualHost111.22.33.44

<VirtualHost111.22.33.44>

ServerNamewww.domain.tld

ServerPath/domain

DocumentRoot/web/domain

</VirtualHost>

" /domain"URI www.domain.tld

http://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

Page 262: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006118|

Page 263: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP

Page 264: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

" IP" IPIP("IP""ifconfig")

Page 265: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

apache httpd

web User,Group,Listen,ServerRootIP Listen""( httpdN-1)

httpd

Page 266: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httpd ListenIP()

Listenwww.smallco.com:80

IP( DNSApache)

Page 267: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

httpd VirtualHostServerAdmin,ServerName,DocumentRoot,ErrorLog,TransferLog,CustomLog

<VirtualHostwww.smallco.com>

[email protected]

DocumentRoot/groups/smallco/www

ServerNamewww.smallco.com

ErrorLog/groups/smallco/logs/error_log

TransferLog/groups/smallco/logs/access_log

</VirtualHost>

<VirtualHostwww.baygroup.org>

[email protected]

DocumentRoot/groups/baygroup/www

ServerNamewww.baygroup.org

ErrorLog/groups/baygroup/logs/error_log

TransferLog/groups/baygroup/logs/access_log

</VirtualHost>

IP( DNSApache)

<VirtualHost> <VirtualHost>

suEXECSuexecUserGroup<VirtualHost>

Page 268: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006118|

Page 269: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Page 270: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httpd.conf<VirtualHost>

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>

#

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

<VirtualHost>

1. Apache

2. DNSApache

()

Page 271: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IPHTTP" Host:" mod_vhost_aliasApache1.3.6 mod_rewriteApache

""Apache(ServerName)(self-referential)URLServerName SERVER_NAMECGI UseCanonicalName

UseCanonicalNameOff(ServerName)" Host:"UseCanonicalNameDNSDNSIPIPApache" Host:"DNSApache ServerName

""( DocumentRootDOCUMENT_ROOTCGI)(core)URI(core)URI( mod_vhost_alias

DOCUMENT_ROOTCGISSI DOCUMENT_ROOT

Page 272: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httpd.conf mod_vhost_alias

#"Host:"

UseCanonicalNameOff

#

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

CustomLoglogs/access_logvcommon

#

VirtualDocumentRoot/www/hosts/%0/docs

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

UseCanonicalNameOff UseCanonicalNameDNSIPIP

Page 273: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ISP(ServerName) www.user.isp.com

/home/user/ cgi-bin

#

VirtualDocumentRoot/www/hosts/%2/docs

#cgi-bin

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

VirtualDocumentRoot mod_vhost_alias

Page 274: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache <VirtualHost>IP <VirtualHost>

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>

Page 275: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP

IPDNSIPIPApache(ServerName)DNS

#IP

UseCanonicalNameDNS

#IP

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

CustomLoglogs/access_logvcommon

#IP

VirtualDocumentRootIP/www/hosts/%0/docs

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

Page 276: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

mod_vhost_alias1.3.6 mod_rewrite"Host:"

Apache1.3.6" %V"1.3.0-1.3.3" %v"" %V"1.3.4UseCanonicalName.htaccess" %{Host}i"

" Host:"" :port"" %V"

Page 277: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_rewrite

httpd.conf mod_rewrite mod_rewrite

mod_rewriteURI(mod_alias) mod_rewrite

ScriptAlias

#"Host:"

UseCanonicalNameOff

#

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

vcommon

CustomLoglogs/access_logvcommon

<Directory/www/hosts>

#ExecCGICGIScriptAlias

OptionsFollowSymLinksExecCGI

</Directory>

#

RewriteEngineOn

#"Host:"ServerName

RewriteMaplowercaseint:tolower

##

#/icons/

RewriteCond%{REQUEST_URI}!^/icons/

#CGI

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

#""

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

{SERVER_NAME}}/docs/$1

##CGI(MIME)

Page 278: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteCond%{REQUEST_URI}^/cgi-bin/

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

{SERVER_NAME}}/cgi-bin/$1[T=application/x-httpd-

cgi]

#ok

Page 279: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_rewrite

RewriteEngineon

RewriteMaplowercaseint:tolower

#CGI

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

#hostnameRewriteRule

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

z-]+\.isp\.com$

#URI

#[C]rewrite

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

[C]

#

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

/home/$1/$2

#CGI

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

Page 280: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

mod_rewrite

vhost.map

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

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

#...

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

http.conf

RewriteEngineon

RewriteMaplowercaseint:tolower

#

RewriteMapvhosttxt:/www/conf/vhost.map

#

RewriteCond%{REQUEST_URI}!^/icons/

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

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

#

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

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

RewriteCond%{REQUEST_URI}^/cgi-bin/

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

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

RewriteRule^/(.*)$%1/cgi-bin/$1

Page 281: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006117|

Page 282: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IPweb

Page 283: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IPweb

IPDNS(CNAMES) www.example.comwww.example.org

ApacheDNS DNSIPweb hosts hosts

#Apache80

Listen80

#IP

NameVirtualHost*:80

<VirtualHost*:80>

DocumentRoot/www/example1

ServerNamewww.example.com

#

</VirtualHost>

<VirtualHost*:80>

DocumentRoot/www/example2

ServerNamewww.example.org

#

</VirtualHost>

IP www.example.com ServerName

<VirtualHost>

IP" *" VirtualHostNameVirtualHost

Page 284: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

NameVirtualHost172.20.30.40

<VirtualHost172.20.30.40>

#...

IP" *"ISPIP" *"IPIP

IP

Page 285: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP

IP

IP( 172.20.30.40)server.domain.com(172.20.30.50)

Listen80

#""172.20.30.40

ServerNameserver.domain.com

DocumentRoot/www/mainserver

#IP

NameVirtualHost172.20.30.50

<VirtualHost172.20.30.50>

DocumentRoot/www/example1

ServerNamewww.example.com

#...

</VirtualHost>

<VirtualHost172.20.30.50>

DocumentRoot/www/example2

ServerNamewww.example.org

#...

</VirtualHost>

172.20.30.50 172.20.30.50" Host:"www.example.com

Page 286: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 287: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP()

IP(192.168.1.1172.20.30.40)()()server.example.com(172.20.30.40)( 192.168.1.1)

<VirtualHost>

NameVirtualHost192.168.1.1

NameVirtualHost172.20.30.40

<VirtualHost192.168.1.1172.20.30.40>

DocumentRoot/www/server1

ServerNameserver.example.com

ServerAliasserver

</VirtualHost>

<VirtualHost>

serverserver.example.com

" *"IP

Page 288: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP NameVirtualHost" name:port" <VirtualHost

name:port>Listen

Listen80

Listen8080

NameVirtualHost172.20.30.40:80

NameVirtualHost172.20.30.40:8080

<VirtualHost172.20.30.40:80>

ServerNamewww.example.com

DocumentRoot/www/domain-80

</VirtualHost>

<VirtualHost172.20.30.40:8080>

ServerNamewww.example.com

DocumentRoot/www/domain-8080

</VirtualHost>

<VirtualHost172.20.30.40:80>

ServerNamewww.example.org

DocumentRoot/www/otherdomain-80

</VirtualHost>

<VirtualHost172.20.30.40:8080>

ServerNamewww.example.org

DocumentRoot/www/otherdomain-8080

</VirtualHost>

Page 289: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP

IP(172.20.30.40172.20.30.50)www.example.comwww.example.org

Listen80

<VirtualHost172.20.30.40>

DocumentRoot/www/example1

ServerNamewww.example.com

</VirtualHost>

<VirtualHost172.20.30.50>

DocumentRoot/www/example2

ServerNamewww.example.org

</VirtualHost>

<VirtualHost>( localhost)

Page 290: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP

IP(172.20.30.40172.20.30.50)www.example.comwww.example.org808080

Listen172.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.example.com

</VirtualHost>

<VirtualHost172.20.30.40:8080>

DocumentRoot/www/example1-8080

ServerNamewww.example.com

</VirtualHost>

<VirtualHost172.20.30.50:80>

DocumentRoot/www/example2-80

ServerNamewww.example.org

</VirtualHost>

<VirtualHost172.20.30.50:8080>

DocumentRoot/www/example2-8080

ServerNamewww.example.org

</VirtualHost>

Page 291: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP

IP

Listen80

NameVirtualHost172.20.30.40

<VirtualHost172.20.30.40>

DocumentRoot/www/example1

ServerNamewww.example.com

</VirtualHost>

<VirtualHost172.20.30.40>

DocumentRoot/www/example2

ServerNamewww.example.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>

Page 292: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Virtual_host>mod_proxy

192.168.111.2 ProxyPreserveHostOn

<VirtualHost*:*>

ProxyPreserveHostOn

ProxyPass/http://192.168.111.2

ProxyPassReverse/http://192.168.111.2/

ServerNamehostname.example.com

</VirtualHost>

Page 293: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

" _default_"

" _default_"IP/

<VirtualHost_default_:*>

DocumentRoot/www/default

</VirtualHost>

/" _default_"/" Host:"(/)

AliasMatchRewriteRule()

" _default_"" _default_"80

<VirtualHost_default_:80>

DocumentRoot/www/default80

#...

</VirtualHost>

<VirtualHost_default_:*>

DocumentRoot/www/default

#...

</VirtualHost>

80" _default_"( )IP

" _default_"

Page 294: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

80" _default_"

<VirtualHost_default_:80>

DocumentRoot/www/default

...

</VirtualHost>

80

Page 295: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP

www.example.org( )IPIP

( 172.20.30.50)VirtualHost

Listen80

ServerNamewww.example.com

DocumentRoot/www/example1

NameVirtualHost172.20.30.40

<VirtualHost172.20.30.40172.20.30.50>

DocumentRoot/www/example2

ServerNamewww.example.org

#...

</VirtualHost>

<VirtualHost172.20.30.40>

DocumentRoot/www/example3

ServerNamewww.example.net

ServerAlias*.example.net

#...

</VirtualHost>

(IP)()

Page 296: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerPath

" Host:"HTTP/1.0Apache()URL

NameVirtualHost172.20.30.40

<VirtualHost172.20.30.40>

#

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>

ServerPath http://www.sub1.domain.tld/sub1/sub1-vhost" Host:" http://www.sub1.domain.tld/sub1-vhost

Page 297: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

" Host:"

" Host:" http://www.sub2.domain.tld/sub1/sub1-vhost

RewriteRule" Host:"URLURL

Page 298: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006117|

Page 299: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache1.3Apache NameVirtualHost1.3

Page 300: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<VirtualHost>(main_server) <VirtualHost>(vhost)

Listen,ServerName,ServerPath,ServerAlias()

Listen80 ServerPathServerAlias ServerNameIP

ListenApacheURI

Apache

VirtualHost Listen" *"(DNS A) (addressset)

IPNameVirtualHostIPIP" *"

NameVirtualHostIP NameVirtualHost(CNAME)IP

NameVirtualHostNameVirtualHost"IP:port"NameVirtualHost

NameVirtualHostVirtualHost IPVirtualHost

NameVirtualHost

111.22.33.44

<VirtualHost

111.22.33.44>

#serverA

...

</VirtualHost>

<VirtualHost

111.22.33.44>

#serverB

...

</VirtualHost>

NameVirtualHost

<VirtualHost

111.22.33.44>

#serverA

</VirtualHost>

<VirtualHost

111.22.33.55>

#serverC

...

</VirtualHost>

<VirtualHost

111.22.33.44>

#serverB

...

</VirtualHost>

Page 301: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

111.22.33.55

<VirtualHost

111.22.33.55>

#serverC

...

</VirtualHost>

<VirtualHost

111.22.33.55>

#serverD

...

</VirtualHost>

<VirtualHost

111.22.33.55>

#serverD

...

</VirtualHost>

NameVirtualHost

111.22.33.44

NameVirtualHost

111.22.33.55

()

VirtualHost VirtualHostListen

VirtualHostServerAlias( ServerAlias) Listen

IPIP NameVirtualHostIPIP NameVirtualHost

IP

IPIP

1. ServerAdmin,ResourceConfig,AccessConfig,Timeout,KeepAliveTimeout,KeepAlive,MaxKeepAliveRequests,ReceiveBufferSize,SendBufferSize()

2. ()

3.

——

ServerNamehttpdDNS ServerNameIP(main_serveraddressset)

Page 302: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerName VirtualHost

" _default_" ServerName

Page 303: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IPIP

(IP)" _default_"" _default_"

IP" NameVirtualHost*"

(IP)IP

IPIP

VirtualHost

(IP)" Host:"

" Host:" ServerNameServerAlias" Host:"Apache

" Host:"HTTP/1.0 ServerPathURI

IP()

IPTCP/IP(KeepAlive)

URIURIURI //URIURI

Page 304: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IPIPIP NameVirtualHost

IPServerAliasServerPathIP" _default_" NameVirtualHost

" Host:"ApacheServerPathServerPath(" Host:")IPIP" _default_" " _default_"( Listen)(" _default_:*")" NameVirtualHost*"IP(" _default_")IP(" _default_")() NameVirtualHost" Host:" " _default_"VirtualHostDNSDNSServerNameDNS

Page 305: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DNS

VirtualHost()NameVirtualHostVirtualHost

ServerPathsServerPaths""("ServerPath/abc/def""ServerPath/abc")

Page 306: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006117|

Page 307: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache( )Apache1020Unix64(hard-limit)

Apache

1. setrlimit()

2. setrlimit(RLIMIT_NOFILE)(Solaris2.3)

3.

4. stdio256(Solaris2)

<VirtualHost>( )12Apache

#!/bin/sh

ulimit-S-n100

exechttpd

Page 308: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

LogFormat" %v"

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

CustomLoglogs/multiple_vhost_logvhost

( ServerName)( )

() split-logfileApache support

split-logfile</logs/multiple_vhost_log

" .log "

Page 309: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200612|

Page 310: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DNSApache

ApacheDNSApacheDNS()()()

Page 311: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<VirtualHostwww.abc.dom>

[email protected]

DocumentRoot/www/abc

</VirtualHost>

Apache ServerNameIPIPApacheDNS www.abc.dom

DNS (Apache1.2)

www.abc.domIP10.0.0.1

<VirtualHost10.0.0.1>

[email protected]

DocumentRoot/www/abc

</VirtualHost>

ApacheDNSServerName(Apache1.2)IPApacheURLURL

<VirtualHost10.0.0.1>

ServerNamewww.abc.dom

[email protected]

DocumentRoot/www/abc

</VirtualHost>

Page 312: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

()Apache1.2DNSDNS abc.dom

DNS www.abc.dom1.2Apache

<VirtualHostwww.abc.dom>

[email protected]

DocumentRoot/www/abc

</VirtualHost>

<VirtualHostwww.def.dom>

[email protected]

DocumentRoot/www/def

</VirtualHost>

www.abc.dom10.0.0.1 www.def.dom10.0.0.2 def.domDNSdef.domabc.dom www.def.dom10.0.0.1DNS

www.def.domIP

10.0.0.1( http://www.abc.dom/whateverURL)def.domApache

Page 313: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

""

Apache1.1 ApachehttpdIP ServerName()Cgethostname("hostname")DNS

DNS /etc/hosts()DNS /etc/hosts/etc/resolv.conf/etc/nsswitch.conf

DNS HOSTRESORDER"local"Apache mod_envCGImanFAQ

Page 314: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

VirtualHostIPListenIPServerName

<VirtualHost_default_:*>

Page 315: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DNSApache1.2DNSInternetIP

DNSDNS(FTPTCP""DNS)

IPDNS

HTTP/1.1HostIPwebDNS19973web

Page 316: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS

|| |2006116|

Page 317: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL/TLS

--A.Tanenbaum,"IntroductiontoComputerNetworks"

WebHTTPApacheSSL mod_ssl

IntroducingSSLandCertificatesusingSSLeayFrederickJ.HirschOpenGroupResearchInstitute1997 WebSecurity:AMatterofTrust,WorldWideWebJournal,Volume2,Issue3,Summer1997 FrederickHirsch() RalfS.Engelschall(mod_ssl)

Page 318: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL()([ AC96)

Alice

Alice

()()

Alice()

AliceAlice

Alice

AliceAlice

()

()Alice

Page 319: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AliceAlice

(CertificateAuthority)

1([DistinguishedName])

1:CertificateInformation

Subject DistinguishedName,PublicKeyIssuer DistinguishedName,SignaturePeriodofValidity NotBeforeDate,NotAfterDateAdministrativeInformation

Version,SerialNumber

ExtendedInformation BasicConstraints,NetscapeFlags,etc.

X.509[ X509]( 2)

2:DistinguishedNameInformation

DNField Abbrev. Description ExampleCommonName CN Namebeingcertified CN=Joe

AverageOrganizationorCompany

O Nameisassociatedwiththisorganization

O=SnakeOil,Ltd.

OrganizationalUnit

OU Nameisassociatedwiththisorganizationunit,suchasadepartment

OU=ResearchInstitute

City/Locality L NameislocatedinthisCity

L=SnakeCity

Page 320: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

State/Province ST NameislocatedinthisState/Province

ST=Desert

Country C NameislocatedinthisCountry(ISOcode)

C=XZ

NetscapeCommonName *.snakeoil.com

ASN.1[X208][PKCS](BasicEncodingRules[BER])(DistinguishedEncodingRules[DER])Base64[PEM("PrivacyEnhancedMail")

ExampleofaPEM-encodedcertificate(snakeoil.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-----

AliceAlice

Page 321: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Alice""

CA""--

ThawteVeriSign

InternetIntranet

([CertificateRevocationListsCRL])AliceAlice()

Page 322: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(SSL)

(TCP/IP)(HTTP)SSL

4:VersionsoftheSSLprotocolVersion Source Description BrowserSupportSSLv2.0

VendorStandard(fromNetscapeCorp.)[SSL2]

FirstSSLprotocolforwhichimplementationsexists

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

SSLv3.0

ExpiredInternetDraft(fromNetscapeCorp.)[SSL3]

Revisionstopreventspecificsecurityattacks,addnon-RSAciphers,andsupportforcertificatechains

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

TLSv1.0

ProposedInternetStandard(fromIETF)[TLS1]

RevisionofSSL3.0toupdatetheMAClayertoHMAC,addblockpaddingforblockciphers,messageorderstandardizationandmorealertmessages.

-Lynx/2.8+OpenSSL

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

SSL Figure1SSL

Page 323: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLSSL()

Figure1:SimplifiedSSLHandshakeSequence

1.

2.

3.

4.

SSL3.031

(MessageAuthenticationCode[MAC])

Page 324: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL2.0RSASSL3.0RSA-Diffie-Hellman

()[ AC96,p516]

SSL()

NoencryptionStreamCiphers

RC4with40-bitkeysRC4with128-bitkeys

CBCBlockCiphersRC2with40bitkeyDESwith40bitkeyDESwith56bitkeyTriple-DESwith168bitkeyIdea(128bitkey)Fortezza(96bitkey)

"CBC"CipherBlockChaining"DES"DataEncryptionStandard[AC96,ch12](DES403DES_EDE)"Idea""RC2"RSADSI[AC96,ch13]

SSL

Nodigest(Nullchoice)MD5,a128-bithashSecureHashAlgorithm(SHA-1),a160-bithash

(MAC)

Page 325: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLHandshakeProtocolSSLChangeCipherSpecProtocolSSLAlertProtocolSSL

SSLRecordProtocol Figure2

Figure2:SSLProtocolStack

SSLNull

SSL Figure3SSL(SSL)

Page 326: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Figure3:SSLRecordProtocol

HTTPSSLHTTPHTTPHTTPSSL(HTTPS)URL httpshttp(443) mod_sslApache...

Page 327: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

References

[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.

[TLS1]TimDierks,ChristopherAllen,"TheTLSProtocolVersion1.0",

Page 328: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

1999.Seehttp://ietf.org/rfc/rfc2246.txt.

Page 329: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS

|| |2006116|

Page 330: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL/TLS

PC--

SSLmod_sslApacheSSLBenLauriemod_ssl)RedHat SecureWebServer(mod_ssl)CovalentRavenSSLModule(mod_ssl)C2Net Stronghold(Stringhold2.xSiouxStronghold3.xmod_ssl)

mod_sslmod_ssl

Page 331: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL 1Apache-SSL1.xmod_ssl2.0.xSioux1.xStronghold2.xmod_ssl

1:mod_ssl

Apache-SSL1.x&mod_ssl2.0.x: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.x:SSLExportClientCertificates SSLOptions

+ExportCertData

SSLCacheServerRunDirdir -Sioux1.x:SSL_CertFilefile SSLCertificateFilefileSSL_KeyFilefile SSLCertificateKeyFile

fileSSL_CipherSuitearg SSLCipherSuitearg

SSLCACertificatePath

Page 332: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL_X509VerifyDirarg arg

SSL_Logfile SSLLogFilefileSSL_Connectflag SSLEngineflagSSL_ClientAutharg SSLVerifyClientargSSL_X509VerifyDeptharg SSLVerifyDepthargSSL_FetchKeyPhraseFromarg -

SSLPassPhraseDialogSSL_SessionDirdir -

SSLSessionCacheSSL_Requireexpr - SSLRequireSSL_CertFileTypearg -SSL_KeyFileTypearg -SSL_X509VerifyPolicyarg -SSL_LogX509Attributesarg -Stronghold2.x:StrongholdAcceleratordir -StrongholdKeydir -StrongholdLicenseFiledir -SSLFlagflag SSLEngineflagSSLSessionLockFilefile SSLMutexfileSSLCipherListspec SSLCipherSuitespecRequireSSL SSLRequireSSL

SSLErrorFilefile -SSLRootdir -SSL_CertificateLogDirdir -AuthCertDirdir -SSL_Groupname -SSLProxyMachineCertPathdir -

Page 333: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyMachineCertFilefile -SSLProxyCACertificatePath

dir-

SSLProxyCACertificateFile

file-

SSLProxyVerifyDepthnumber -SSLProxyCipherListspec -

Page 334: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

" SSLOptions+CompatEnvVars"mod_ssl 2

2:mod_ssl

SSL_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

Page 335: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 336: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL_STRONG_CRYPTO - mod_sslSSL_SERVER_KEY_EXP - mod_sslSSL_SERVER_KEY_ALGORITHM - mod_sslSSL_SERVER_KEY_SIZE - mod_sslSSL_SERVER_SESSIONDIR - mod_sslSSL_SERVER_CERTIFICATELOGDIR - mod_sslSSL_SERVER_CERTFILE - mod_sslSSL_SERVER_KEYFILE - mod_sslSSL_SERVER_KEYFILETYPE - mod_sslSSL_CLIENT_KEY_EXP - mod_sslSSL_CLIENT_KEY_ALGORITHM - mod_sslSSL_CLIENT_KEY_SIZE - mod_ssl

Page 337: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

mod_sslApache(DSO)" %{name}c" 3

3:FunctionCall%...{version}c SSL%...{cipher}c SSL%...{subjectdn}c SubjectDistinguishedName%...{issuerdn}c IssuerDistinguishedName%...{errcode}c ()%...{errstr}c ()

Page 338: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS

|| |2006116|

Page 339: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL/TLS...?

--

SSLHTTPApacheSSLweb

Page 340: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLv2

SSLv2SSLv2

httpd.confSSLProtocol-all+SSLv2

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

SSL

httpd.confSSLProtocolall

SSLCipherSuiteHIGH:MEDIUM

SSL(ServerGatedCryptography[SGC])mod_ssl README.GlobalID

VerisignCAIDHTTP

httpd.conf#SGC

SSLCipherSuite

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

<Directory/usr/local/apache2/htdocs>

Page 341: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

#

SSLRequire%{SSL_CIPHER_USEKEYSIZE}>=128

</Directory>

SSLURLSSLCipherSuitemod_sslSSL

#

SSLCipherSuite

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

<Location/strong/area>

#https://hostname/strong/area/

SSLCipherSuiteHIGH:MEDIUM

</Location>

Page 342: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

intranetinternet

()IntranetCA ca.crt

httpd.conf#requireaclientcertificatewhichhastobe

directly

#signedbyourCAcertificateinca.crt

SSLVerifyClientrequire

SSLVerifyDepth1

SSLCACertificateFileconf/ssl.crt/ca.crt

URLmod_ssl

httpd.confSSLVerifyClientnone

SSLCACertificateFileconf/ssl.crt/ca.crt

<Location/secure/area>

SSLVerifyClientrequire

SSLVerifyDepth1

</Location>

URLDistinguishedName(DN) mod_auth_basicSSLRequire

DN

Page 343: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

AuthBasicProviderfile

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

requirevalid-user

</Directory>

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

httpd.confSSLVerifyClientnone

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

SSLVerifyClientrequire

SSLVerifyDepth5

SSLCACertificateFileconf/ssl.crt/ca.crt

SSLCACertificatePathconf/ssl.crt

Page 344: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLOptions+FakeBasicAuth

SSLRequireSSL

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

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

</Directory>

InternetHTTPSIntranetIntranetHTTPIntranetIP192.160.1.0/24IntranetURL /subareaHTTPS(HTTPSHTTP)

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

<Directory/usr/local/apache2/htdocs>

#subareaIntranet

Orderdeny,allow

Denyfromall

Allowfrom192.168.1.0/24

</Directory>

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

#subareaIntranet

#InternetHTTPS+Strong-Cipher+Password

#HTTPS+Strong-Cipher+Client-Certificate

#HTTPS

#

SSLVerifyClientoptional

SSLVerifyDepth1

SSLOptions+FakeBasicAuth+StrictRequire

SSLRequire%{SSL_CIPHER_USEKEYSIZE}>=128

#InternetHTTPS

RewriteEngineon

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

Page 345: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

RewriteCond%{HTTPS}!=on

RewriteRule.*-[F]

#

Satisfyany

#

Orderdeny,allow

Denyfromall

Allow192.168.1.0/24

#HTTP

AuthTypebasic

AuthName"ProtectedIntranetArea"

AuthBasicProviderfile

AuthUserFileconf/protected.passwd

Requirevalid-user

</Directory>

Page 346: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS

||< >|???|

Page 347: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL/TLSStrongEncryption:FAQ

Thewisemandoesn'tgivetherightanswers,heposestherightquestions.

--ClaudeLevi-Strauss

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

Pleasereadthischapteratleastoncewheninstallingmod_ssloratleastsearchforyourproblemherebeforesubmittingaproblemreporttotheauthor.

Page 348: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AboutTheModule

Whatisthehistoryofmod_ssl?mod_sslandYear2000?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,theWassenaar

Page 349: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Arrangementalsoprovidesanexemptionfromexportcontrolsformass-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.

Page 350: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Installation

WhydoIgetpermissionerrorsrelatedtoSSLMutexwhenIstartApache?Whydoesmod_sslstopwiththeerror"Failedtogeneratetemporary512bitRSAprivatekey",whenIstartApache?

WhydoIgetpermissionerrorsrelatedtoSSLMutexwhenIstartApache?Errorssuchas"mod_ssl:ChildcouldnotopenSSLMutexlockfile/opt/apache/logs/ssl_mutex.18332(System

errorfollows)[...]System:Permissiondenied

(errno:13)"areusuallycausedbyoverlyrestrictivepermissionsontheparentdirectories.Makesurethatallparentdirectories(here/opt,/opt/apache/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.ThiscanbedoneviatheSSLRandomSeeddirectives.

Page 351: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 352: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Configuration

IsitpossibletoprovideHTTPandHTTPSfromthesameserver?WhichportdoesHTTPSuse?HowdoIspeakHTTPSmanuallyfortestingpurposes?WhydoestheconnectionhangwhenIconnecttomySSL-awareApacheserverWhydoIget"ConnectionRefused"errors,whentryingtoaccessmynewlyinstalledApache+mod_sslserverviaHTTPS?WhyaretheSSL_XXXvariablesnotavailabletomyCGI&SSIscripts?HowcanIswitchbetweenHTTPandHTTPSinrelativehyperlinks?

IsitpossibletoprovideHTTPandHTTPSfromthesameserver?Yes.HTTPandHTTPSusedifferentserverports(HTTPbindstoport80,HTTPStoport443),sothereisnodirectconflictbetweenthem.Youcaneitherruntwoseparateserverinstancesboundtotheseports,oruseApache'selegantvirtualhostingfacilitytocreatetwovirtualserversoveroneinstanceofApache-onerespondingtorequestsonport80andspeakingHTTPandtheotherrespondingtorequestsonport443speakingHTTPS.

WhichportdoesHTTPSuse?YoucanrunHTTPSonanyport,butthestandardsspecifyport443,whichiswhereanyHTTPScompliantbrowserwilllookbydefault.YoucanforceyourbrowsertolookonadifferentportbyspecifyingitintheURLlikethis(forport666):https://secure.server.dom:666/

HowdoIspeakHTTPSmanuallyfortestingpurposes?Whileyouusuallyjustuse

Page 353: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

$telnetlocalhost80

GET/HTTP/1.0

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

$openssls_client-connectlocalhost:443-state-

debug

GET/HTTP/1.0

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

$curlhttp://localhost/

$curlhttps://localhost/

WhydoestheconnectionhangwhenIconnecttomySSL-awareApacheserver?BecauseyouconnectedwithHTTPtotheHTTPSport,i.e.youusedanURLoftheform"http://"insteadof"https://".ThisalsohappenstheotherwayroundwhenyouconnectviaHTTPStoaHTTPport,i.e.whenyoutrytouse"https://"onaserverthatdoesn'tsupportSSL(onthisport).MakesureyouareconnectingtoavirtualserverthatsupportsSSL,whichisprobablytheIPassociatedwithyourhostname,notlocalhost(127.0.0.1).

Page 354: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

WhydoIget"ConnectionRefused"messages,whentryingtoaccessmynewlyinstalledApache+mod_sslserverviaHTTPS?Thiscanhappenforvariousreasons.ThemostcommonmistakesincludestartingApachewithjustapachectlstart(orhttpd)insteadofapachectlstartssl(orhttpd-DSSL).Yourconfigurationmayalsobeincorrect.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.

Page 355: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 356: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Certificates

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

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

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

Page 357: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

SeethechapterforageneraldescriptionoftheSSLprotocol.

IsthereadifferenceonstartupbetweentheoriginalApacheandanSSL-awareApache?Yes.Ingeneral,startingApachewithmod_sslbuilt-inisjustlikestartingApachewithoutit.However,ifyouhaveapassphraseonyourSSLprivatekeyfile,astartupdialogwillpopupwhichasksyoutoenterthepassphrase.

Havingtomanuallyenterthepassphrasewhenstartingtheservercanbeproblematic-forexample,whenstartingtheserverfromthesystembootscripts.Inthiscase,youcanfollowthestepsbelowtoremovethepassphrasefromyourprivatekey.

HowdoIcreateaself-signedSSLCertificatefortestingpurposes?1. MakesureOpenSSLisinstalledandinyourPATH.

2. Runthefollowingcommand,tocreateserver.keyserver.crtfiles:$opensslreq-new-x509-nodes-outserver.crt

-keyoutserver.key

Thesecanbeusedasfollowsinyourhttpd.conffile:

SSLCertificateFile/path/to/this/server.crt

SSLCertificateKeyFile/path/to/this/server.key

Page 358: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 359: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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. Thawtehttp://www.thawte.com/

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

4. IKSGmbH

Page 360: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

http://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.keyserver.crt.Thesecanbeusedasfollowsinyourhttpd.conffile:

SSLCertificateFile/path/to/this/server.crt

SSLCertificateKeyFile/path/to/this/server.key

Theserver.csrfileisnolongerneeded.

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

1. CreateaRSAprivatekeyforyourserver(willbeTriple-DESencryptedandPEMformatted):

$opensslgenrsa-des3-outserver.key1024

Pleasebackupthishost.keyfileandthepass-phraseyou

Page 361: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

enteredinasecurelocation.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-days365

-keyserver.key-outserver.crt

ThissignstheserverCSRandresultsinaserver.crtfile.YoucanseethedetailsofthisCertificateusing:

$opensslx509-noout-text-inserver.crt

HowcanIchangethepass-phraseonmyprivatekeyfile?Yousimplyhavetoreaditwiththeoldpass-phraseandwriteitagain,specifyingthenewpass-phrase.Youcanaccomplishthiswiththefollowingcommands:

$opensslrsa-des3-inserver.key-out

server.key.new

$mvserver.key.newserver.key

Thefirsttimeyou'reaskedforaPEMpass-phrase,youshouldentertheoldpass-phrase.Afterthat,you'llbeaskedagaintoenterapass-

Page 362: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

phrase-thistime,usethenewpass-phrase.Ifyouareaskedtoverifythepass-phrase,you'llneedtoenterthenewpass-phraseasecondtime.

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

1. RemovetheencryptionfromtheRSAprivatekey(whilekeepingabackupcopyoftheoriginalfile):

$cpserver.keyserver.key.org

$opensslrsa-inserver.key.org-outserver.key

2. Makesuretheserver.keyfileisonlyreadablebyroot:

$chmod400server.key

Nowserver.keycontainsanunencryptedcopyofthekey.Ifyoupointyourserveratthisfile,itwillnotpromptyouforapass-phrase.HOWEVER,ifanyonegetsthiskeytheywillbeabletoimpersonateyouonthenet.PLEASEmakesurethatthepermissionsonthisfilearesuchthatonlyrootorthewebserverusercanreadit(preferablygetyourwebservertostartasrootbutrunasanotheruser,andhavethekeyreadableonlybyroot).

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

Page 363: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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"

Page 364: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

error?ErrorssuchasOpenSSL:error:14094412:SSLroutines:SSL3_READ_BYTES:sslv3alertbad

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

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

WhyisclientauthenticationbrokenafterupgradingfromSSLeayversion0.8to0.9?TheCAcertificatesunderthepathyouconfiguredwithSSLCACertificatePatharefoundbySSLeaythroughhashsymlinks.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:$

Page 365: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

opensslx509-incert.pem-outcert.der-outform

DER

Whycan'tIfindthegetcagetverisignprogramsmentionedbyVerisign,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.

Page 366: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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,butthemainoneisproblemswiththeSSLsessionCachespecifiedbytheSSLSessionCachedirective.TheDBMsessioncacheisthemostlikelysourceoftheproblem,sousingtheSHMsessioncache(orno

Page 367: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

cacheatall)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,youshouldrunthe

Page 368: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

following:

$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)is

Page 369: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

establishedApache/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.

Page 370: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.Doesthismeantheusername/passwordisbeingsentunencrypted?No,theusername/passwordistransmittedencrypted.TheiconinNetscapebrowsersisnotactuallysynchronizedwiththeSSL/TLSlayer.Itonlytogglestothelockedstatewhenthefirstpartoftheactualwebpagedataistransferred,whichmayconfusepeople.TheBasicAuthenticationfacilityispartoftheHTTPlayer,whichisabovetheSSL/TLSlayerinHTTPS.BeforeanyHTTPdatacommunication

Page 371: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

takesplaceinHTTPS,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.Beforeyoudecidetodothis,makesureyourclientsreallyhaveproblems.Ifnot,donotmakethesechanges-theywillaffectallyourclients,MSIEorotherwise.

Thenextproblemisthat56bitexportversionsofMSIE5.xbrowsershaveabrokenSSLv3implementation,whichinteractsbadlywithOpenSSLversionsgreaterthan0.9.4.Youcanacceptthisandrequireyourclientstoupgradetheirbrowsers,youcandowngradeto

Page 372: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

OpenSSL0.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).ConnectingwiththoseMSIEversionsonlyworkifaSSLsessioncacheisused.So,asawork-around,makesureyouareusingasessioncache(seetheSSLSessionCachedirective).

WhydoIgetI/Oerrors,orthemessage"Netscapehasencounteredbaddatafromtheserver",whenconnectingviaHTTPStoanApache+mod_sslserverwithNetscapeNavigator?

Page 373: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Thisusuallyoccurswhenyouhavecreatedanewservercertificateforagivendomain,buthadpreviouslytoldyourbrowsertoalwaysaccepttheoldservercertificate.Onceyoucleartheentryfortheoldcertificatefromyourbrowser,everythingshouldbefine.Netscape'sSSLimplementationiscorrect,sowhenyouencounterI/OerrorswithNetscapeNavigatoritisusuallycausedbytheconfiguredcertificates.

Page 374: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.2/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-usersSupportMailingList

Page 375: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

modssl-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

Page 376: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Forthisyoucanprovidealogfileofyourterminalsessionwhichshowstheconfigurationandinstallsteps.Ifthisisnotpossible,youshouldatleastprovidetheconfigurecommandlineyouused.

IncaseofcoredumpspleaseincludeaBacktraceIfyourApache+mod_ssl+OpenSSLdumpsitscore,pleaseattachastack-frame"backtrace"(seebelowforinformationonhowtogetthis).Withoutthisinformation,thereasonforyourcoredumpcannotbefound

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,atleastinApache.OnplatformswhereyouuseGCC/GDB,youwillhavetobuildApache+mod_sslwith"OPTIM="-g-ggdb3""togetthis.Onotherplatformsatleast"OPTIM="-g""isneeded.

Page 377: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

2. Starttheserverandtrytoreproducethecore-dump.Forthisyoumaywanttouseadirectivelike"CoreDumpDirectory/tmp"tomakesurethatthecore-dumpfilecanbewritten.Thisshouldresultina/tmp/core/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.

Page 378: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../

|| |200618|

Page 379: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(Authentication)(Authorization)

Page 380: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

( AuthType)mod_auth_basic

mod_auth_digest

mod_authn_alias

mod_authn_anon

mod_authn_dbd

mod_authn_dbm

mod_authn_default

mod_authn_file

mod_authnz_ldap

( Require)mod_authnz_ldap

mod_authz_dbm

mod_authz_default

mod_authz_groupfile

mod_authz_owner

mod_authz_user

mod_authnz_ldap mod_authn_alias

mod_authz_hostIP

Page 381: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

""

Page 382: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

( <Directory>)( .htaccess)

.htaccess AllowOverride

AllowOverride

AllowOverrideAuthConfig

Page 383: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

/usr/local/apache/htdocs

/usr/local/apache/passwd

Apachebinhtpasswd

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

rbowen

htpasswd

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

rbowen

Newpassword:mypassword

Re-typenewpassword:mypassword

Addingpasswordforuserrbowen

htpasswd /usr/local/apache/bin/htpasswd

httpd.conf.htaccess

/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

AuthType mod_auth_basicBasicBasicApache" AuthTypeDigest" mod_auth_digest

AuthName(Realm)

Page 384: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

"RestrictedFiles" "RestrictedFiles"

AuthUserFile htpasswdApachemod_authn_dbmAuthDBMUserFile dbmmanage Apache

Require Require

Page 385: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

( rbowen) AuthGroupFile

GroupName:rbowendpittssungorshersey

htpasswd/usr/local/apache/passwd/passwordsdpitts

( -c)

.htaccess

AuthTypeBasic

AuthName"ByInvitationOnly"

AuthUserFile/usr/local/apache/passwd/passwords

AuthGroupFile/usr/local/apache/passwd/groups

RequiregroupGroupName

GroupNamepassword

Requirevalid-user

RequireuserrbowenApache()AuthUserFile

Page 386: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Basic

Page 387: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AllowDeny OrderApache

Allowfromaddress

addressIP(IP)()IP

Denyfrom205.252.46.165

IP

Denyfromhost.example.com

Denyfrom192.101.205

Denyfromcyberthugs.commoreidiots.com

Denyfromke

OrderDenyAllow

Orderdeny,allow

Denyfromall

Allowfromdev.example.com

Allow

Page 388: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

mod_auth_basicmod_authz_host mod_authn_alias

Page 389: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../

|| |200618|

Page 390: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI

Page 391: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_alias

mod_cgi

AddHandler

Options

ScriptAlias

CGI()webCGICGIApachewebCGICGI

Page 392: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheCGI

CGIApacheCGI

ScriptAliasScriptAliasApacheCGIApacheCGI

ScriptAlias

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

Apache httpd.conf ScriptAliasAliasURLDocumentRoot ScriptAliasURLCGIApache /cgi-

bin//usr/local/apache2/cgi-bin/CGI

URL http://www.example.com/cgi-bin/test.pl

Apache /usr/local/apache2/cgi-bin/test.pl

Apache

ScriptAliasCGICGI ScriptAliasCGICGI UserDir

CGI cgi-binCGI

CGI AddHandlerSetHandlercgi-script Options

ExecCGI

OptionsCGIOptionsCGI

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

Options+ExecCGI

</Directory>

ApacheCGICGI AddHandlercgiplCGI

Page 393: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddHandlercgi-script.cgi.pl

.htaccess

.htaccesshttpd.confCGI

" .cgi"CGI

<Directory/home/*/public_html>

Options+ExecCGI

AddHandlercgi-script.cgi

</Directory>

cgi-binCGI

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

OptionsExecCGI

SetHandlercgi-script

</Directory>

Page 394: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI

CGI""

CGIHTTP MIME

Content-type:text/html

HTMLHTMLgifHTML

CGI

CGICGI first.pl cgi-bin

#!/usr/bin/perl

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

print"Hello,World.";

PerlApache /usr/bin/perl(shell)HTTP"Hello,World."

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

Hello,World.

Page 395: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI

CGICGI Content-Type

CGI"POSTMethodNotAllowed"ApacheCGI Apache

"Forbidden"Apache

"InternalServerError"ApacheCGI"Prematureendofscriptheaders"HTTP

( nobodywww) nobody

chmoda+xfirst.pl

shell PATHshell

CGIweb PATHCGI( sendmail)shellCGI

CGI( perl)

#!/usr/bin/perl

CGI Apache

Page 396: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGICGI

cd/usr/local/apache2/cgi-bin

./first.pl

( perlshellApache )

HTTP Content-TypeApache Prematureendof

scriptheaders CGI

SuexecsuexecCGIsuexecCGI Prematureendofscript

headers

suexec apachectl-VSUEXEC_BINApache suexec

suexec

suexec() SUEXEC_BINsuexec suexec suexec

-Vsuexec

Page 397: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

?

CGI()"Hello,World"

() env

CGI(NetscapeIELynx)(ApacheIISWebSite)CGI

CGI- http://hoohoo.ncsa.uiuc.edu/cgi/env.html

CGIApache cgi-binApache

#!/usr/bin/perl

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

foreach$key(keys%ENV){

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

}

STDINSTDOUT(STDIN)(STDOUT) STDIN STDOUT

POSTCGI STDINCGI

""(=)(&)"&""="

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

URL QUERY_STRINGGETHTML FORMMETHOD GETPOST

CGI

Page 398: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI/

CGI

PerlCGI CPANCGI.pmCGI::Lite

CCGI CGIC http://www.boutell.com/cgic/

Page 399: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

CGIUsenet comp.infosystems.www.authoring.cgiCGIHTMLWritersGuild http://www.hwg.org/lists/hwg-servers/

CGICGI NCSACommonGatewayInterfaceRFCproject

CGICGI

CGIApachebugApache

Page 400: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../

|| |200619|

Page 401: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HTML

Page 402: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_include

mod_cgi

mod_expires

Options

XBitHack

AddType

SetOutputFilter

BrowserMatchNoCase

(SSI)SSIHTMLSSI

SSISSI

Page 403: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSI?

SSIHTMLHTMLCGI

SSISSI

Page 404: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSI

SSIhttpd.conf.htaccess

Options+Includes

SSI OptionsSSI Options

SSIApacheApache .shtml

AddTypetext/html.shtml

AddOutputFilterINCLUDES.shtml

.shtmlSSI

XBitHack

XBitHackon

XBitHackApacheSSI chmodSSI

chmod+xpagename.html

.shtmlApache .htmlSSI XBitHackApacheSSI

Windows

ApacheSSIHTTP

1. XBitHackFullApache

2. mod_expires

Page 405: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSI

SSI

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

->

HTMLSSIHTMLSSI

SSI

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

echoCGI set

configtimefmt

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

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

Thisdocumentlastmodified<!--#flastmod

file="index.html"-->

timefmt

CGISSICGI""

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

Page 406: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 407: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HTMLSSI

?SSIHTMLSSI

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

Thisfilelastmodified<!--#flastmod

file="ssi.shtml"-->

ssi.shtml LAST_MODIFIED

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

Thisfilelastmodified<!--#echo

var="LAST_MODIFIED"-->

timefmt googlestrftime

/ include includefilevirtual file("/")"../" virtualURL"/"

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

SSI LAST_MODIFIEDSSI include

Page 408: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

config

SSI

[anerroroccurredwhileprocessingthis

directive]

configerrmsg

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

knowhowtouseSSI]"-->

configsizefmt bytesKbMb (abbrev)

Page 409: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGISSI execSSIshell( /bin/shWin32DOSshell)

<pre>

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

</pre>

Windows

<pre>

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

</pre>

Windows dir"< dir>"

exec"" OptionsIncludesNOEXEC exec

SSI

Page 410: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSI

ApacheSSI

Apache1.2Apache1.2

set

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

( LAST_MODIFIED)"$"

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

"$""\$"

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

()

<!--#setvar="date"

value="${DATE_LOCAL}_${DATE_GMT}"-->

SSI mod_includeif,elif,else,endif

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

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

<!--#else-->

Page 411: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<!--#endif-->

test_condition""() mod_include

BrowserMatchNoCasemacintoshMac

BrowserMatchNoCaseMSIEInternetExplorer

MacintoshInternetExplorer"Mac""InternetExplorer"

SSI

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

Apologetictextgoeshere

<!--#else-->

CoolJavaScriptcodegoeshere

<!--#endif-->

MacIEMacIEJavaScript

()Apache SetEnvIfCGI

Page 412: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

SSICGI

Page 413: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../

|| |200618|

Page 414: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.htaccess

.htaccess

Page 415: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.htaccess

core

mod_authn_file

mod_authz_groupfile

mod_cgi

mod_include

mod_mime

AccessFileName

AllowOverride

Options

AddHandler

SetHandler

AuthType

AuthName

AuthUserFile

AuthGroupFile

Require

Page 416: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.htaccess("")

.htaccess AccessFileName .config

AccessFileName.config

.htaccess AllowOverride.htaccess .htaccess

AllowOverride

AddDefaultCharset.htaccess("") FileInfo.htaccess AllowOverrideFileInfo

serverconfig,virtualhost,directory,.htaccessFileInfo

.htaccess""".htaccess"

Page 417: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

().htaccess

.htaccess .htaccess

.htaccessroot .htaccessISP

.htaccess .htaccess <Directory>

.htaccess

AllowOverride.htaccessApache .htaccess

.htaccess .htaccess

Apache .htaccess( ) /www/htdocs/example

Apache

/.htaccess

/www/.htaccess

/www/htdocs/.htaccess

/www/htdocs/example/.htaccess

4(" /" .htaccess)

AllowOverride

/www/htdocs/example.htaccess <Directory

/www/htdocs/example>

/www/htdocs/example.htaccess

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

httpd.conf

<Directory/www/htdocs/example>

Page 418: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddTypetext/example.exm

</Directory>

Apache

AllowOverridenone.htaccess

AllowOverrideNone

Page 419: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.htaccess.htaccess .htaccess .htaccess

.htaccess

/www/htdocs/example1.htaccess

Options+ExecCGI

(" AllowOverrideOptions" .htaccess" Options")

/www/htdocs/example1/example2.htaccess

OptionsIncludes

.htaccess /www/htdocs/example1/example2CGIOptionsIncludes

.htaccess() .htaccess<Directory> AllowOverride

.htaccess

<Directory/>

AllowoverrideAll

</Directory>

<Location/>

Options+IncludesNoExec-ExecCGI

</Location>

Page 420: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.htaccess <Directory> .htaccess

.htaccess

.htaccess

.htaccess

AuthTypeBasic

AuthName"PasswordRequired"

AuthUserFile/www/passwords/password.file

AuthGroupFile/www/passwords/group.file

RequireGroupadmins

AllowOverrideAuthConfig

Page 421: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(SSI)

.htaccess(SSI) .htaccess

Options+Includes

AddTypetext/htmlshtml

AddHandlerserver-parsedshtml

AllowOverrideOptions AllowOverrideFileInfo

SSI

Page 422: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI

.htaccessCGI

Options+ExecCGI

AddHandlercgi-scriptcgipl

CGI

Options+ExecCGI

SetHandlercgi-script

AllowOverrideOptions AllowOverrideFileInfo

CGI CGI

Page 423: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

.htaccess

AllowOverride AllowOverrideNone .htaccess

AllowOverrideNone

Apache .htaccess

Page 424: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../

|| |200619|

Page 425: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UserDirURL http://example.com/~username/" username" UserDir

Page 426: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_userdir UserDir

DirectoryMatch

AllowOverride

Page 427: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 428: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UserDir

UserDirenabled

UserDirdisabledrootjrofish

disabled

UserDirdisabled

UserDirenabledrbowenkrietz

UserDir

Page 429: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

cgi

<Directory>"cgi" cgi-bin

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

OptionsExecCGI

SetHandlercgi-script

</Directory>

"" UserDirpublic_htmlCGIexample.cgiURL

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

Page 430: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

.htaccess AllowOverride .htaccess

Page 431: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006112|

Page 432: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MicrosoftWindowsApache

MicrosoftWindowsApache2.0bug bug

ApacheWindowsApache(bugs) WindowsApache

Windows

WindowsNT:NTMicrosoftWindowsWindowsNT,Windows2000,WindowsXP,Windows.NETServer2003Windows9x:MicrosoftWindowsWindows95,Windows98,WindowsME

Page 433: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.0WindowsNTx86IntelAMDApacheWindows9x

TCP/IPWindows95"Winsock2""Winsock2"forWindows95

NT4.0ServicePack6ServicePack4TCP/IPWinsockServicePack

Page 434: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheforWindows

Apachehttp://httpd.apache.org/download.cgialphabetawebftp

.msiApacheforWindowsMicrosoftInstallerApache

.zipMicrosoftVisualC++(VisualStudio)

Page 435: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheforWindows

ApacheMicrosoftInstaller1.2Windows9x MicrosoftInstaller2.0WindowsNT4.020002.0 WindowsXP/2003

Apache2.01.3 2.0Apache2.0 Apache

Apache.msi

1. NetworkDomainDNSDNS server.mydomain.netmydomain.net

2. ServerNameDNS server.mydomain.net

3. Administrator'sEmailAddressemail

4. ForwhomtoinstallApacheApache80(Apache)" forAllUsers,onPort80,asaService-

Recommended"Apache80WWW" onlyforthe

CurrentUser,onPort8080,whenstarted

Manually"

5. TheinstallationtypeTypical Custom13MB

6. WheretoinstallApache C:\ProgramFiles\Apache

GroupApache2

Apache conf .defaultconf\httpd.conf conf\httpd.conf

conf\httpd.conf.default .default

htdocs\index.html( index.html.default)Apache()

Apache confApache htdocs

Page 436: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheforWindows

UnixApache confWindows

ApacheforWindows

ApacheforWindowsUnixApache

MaxRequestsPerChildUnixUnixMaxRequestsPerChild0

httpd.conf

ThreadsPerChild ThreadsPerChild50

WindowsUnixApacheUnixApache

ApacheforWindowsApach \Apache2\modulesLoadModule( access.conf)

LoadModulestatus_modulemodules/mod_status.so

ApacheISAPI(InternetServerApplicationsProgrammingInterface)MicrosoftIISWindows Apache

CGIApache ScriptInterpreterSource

Windows.htaccess AccessFilename

WindowsNTApacheWindows(eventlog)Apache error.log

""MMCWindows

Page 437: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Windows9x

Page 438: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheforWindows

ApacheWindowsNT

Apache"forallusers"Apache"onlyfortheCurrentUser"ApacheAdministrators

ApacheServiceMonitorApacheApacheApache

ApachebinApacheWindowsNT

apache-kinstall

Apache

apache-kinstall-n""

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

-kinstall Apache2conf\httpd.conf

Apache

apache-kuninstall

Apache

apache-kuninstall-n""

ApacheApacheServiceMonitor NETSTART

Apache2 NETSTOPApache2WindowsApache

apache-n""-t

Page 439: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheApache

apache-kstart

Apache

apache-kstop

apache-kshutdown

Apache

apache-krestart

Apache( LocalSystem) LocalSystemWindowsDCOMsecureRPC

LocalSystemApacheApache

ApacheApache

1.

2. Windows2000/XP/2003""""MMC

3. Users

4. (RX)( htdocscgi-bin)

5. Apachelogs//(RWD)

6. Apache.exe(RX)

Page 440: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache(RX)Apache2 logs//(RWD)

webApacheApache

2186""

ApacheWindowsApache

CouldnotstarttheApache2serviceon\\COMPUTER

Error1067;Theprocessterminatedunexpectedly.

Apache Apache

ApacheWindows9xWindowsNT Apache

""

Apache

Apache-n""-kstart

Apache httpd.conf

Windows9xNETSTARTNETSTOPApache

ApacheWindows9xApacheWindows9xApacheWindows9xhttpdwebApacheintranet

Page 441: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

ApacheWindows9xApache

Apache

apache

ApacheCtl+C

-->-->ApacheHTTPServer2.2.xx-->

ControlApacheServerApacheApacheApacheCtl+CApacheApache

Apache

apache-kshutdown

Ctl+CApache

ApacheApache

apache-krestart

UnixApacheUnix kill-TERMpid kill-USR1pid-kUnix kill

ApacheApachebin apache error.logApache

c:

cd"\ProgramFiles\ApacheGroup\Apache2\bin"

apache

ApacheCtl+C

Page 442: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

cd..\logs

more<error.log

Apache

-f

apache-f"c:\myserver

files\anotherconfig.conf"

apache-ffiles\anotherconfig.conf

-nApache

apache-n""

ServerRoot

-f -nApache conf\httpd.conf -VApache SERVER_CONFIG_FILE

apache-V

ApacheServerRoot

1. -CServerRoot

2. -d

3.

4.

5. /apache apache-VHTTPD_ROOT

Page 443: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

"forallusers" HKEY_LOCAL_MACHINE

HKEY_LOCAL_MACHINE\SOFTWARE\Apache

Group\Apache\2.0.43

"forthecurrentuseronly" HKEY_CURRENT_USER

HKEY_CURRENT_USER\SOFTWARE\Apache

Group\Apache\2.0.43

Apache

confServerRootApache httpd.conf ServerRoot

ApacheApache

Page 444: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Apache()80( ListenURL

http://localhost/

Apache logs error.logDNSURL

http://127.0.0.1/

Apache80(8080)URL

http://127.0.0.1:8080/

confApacheNTApacheApache

ApacheTCP/IP()webBlackIceApacheApacheTCP/IP

Page 445: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006112|

Page 446: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MicrosoftWindowsApache

Apache MicrosoftWindowsApache

Page 447: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

50MBApache10MB

MicrosoftVisualC++5.0

VisualStudioApache PATH,INCLUDE,LIBvcvars32

"c:\Program

Files\DevStudio\VC\Bin\vcvars32.bat"

WindowsPlatformSDK

VisualC++5.0MicrosoftWindowsPlatformSDKApachesetenv

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

VisualC++6.0PlatformSDK

WindowsPlatformSDKApache mod_isapiSDKMSVC++5.0Apache mod_isapi

http://msdn.microsoft.com/downloads/sdks/platform/platform.aspMicrosoftWinodwsPlatformSDK

awk(awk,gawk)

Apacheawk.exeawk(PerlWSH/VB)BrianKernighan http://cm.bell-labs.com/cm/cs/who/bwk/Win32http://cm.bell-labs.com/cm/cs/who/bwk/awk95.exeawk.exeawk95.exe

Page 448: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DeveloperStudioTools-OptionsDirectories awk.exe(DeveloperStudio7.0theProjects-VC++Directories)awk.exe PATH

Cygwin(http://www.cygwin.com/)awk gawk.exeawk.exe

gawk.exeWindowscygwin awk.exegawk.exe

awk.exe

[]OpenSSL( mod_sslab.exessl)

OpenSSLOpenSSLApacheOpenSSL

mod_sslabs(ab.exeSSL)OpenSSL srclibopenssl

openSSL http://www.openssl.org/source/ releasedebug

0.9.7

perlConfigureVC-WIN32

perlutil\mkfiles.pl>MINFO

perlutil\mk1mf.pldllno-asmno-mdc2no-rc5

no-ideaVC-WIN32>makefile

perlutil\mk1mf.pldlldebugno-asmno-mdc2

no-rc5no-ideaVC-WIN32>makefile.dbg

perlutil\mkdef.pl32libeayno-asmno-mdc2

no-rc5no-idea>ms\libeay32.def

perlutil\mkdef.pl32ssleayno-asmno-mdc2

no-rc5no-idea>ms\ssleay32.def

nmake

nmake-fmakefile.dbg

[]zlib( mod_deflate)

Zlibsrclibzlib mod_deflateZlibhttp://www.gzip.org/zlib/-- mod_deflate1.1.4

Page 449: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 450: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache cd

ApachemakeMakefile.winWindowsNTApache release

debug

nmake/fMakefile.win_apacher

nmake/fMakefile.win_apached

Apachebugs

Page 451: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DeveloperStudio

ApacheVC++VisualStudioVisualStudio Apache.dswApache .dsp

Apache.dsw InstallBin( ReleaseDebug)InstallBin Makefile.win

GeneralBuildCommandline INSTDIR /Apache2

BuildBin

.dspVisualC++6.0VisualC++5.0(97)VisualC++Apache.dsw.dsp Apache.sln.msproj .dsp

VC++7.0 Apache.dsw

VisualC++7.0(.net)Build ConfigurationManagerabsmod_deflate DebugRelease srclibopensslzlibnmakeBinBuild

.mak VisualC++5.0 mod_sslabs(SSLab) VC++7.0(.net) nmake binenv VC++5.06.0Project-Exportmake

perlsrclib\apr\build\fixwin32mak.pl

httpd .mak .dep .dsp

VisualStudio6.0 VC++5.07.0

Page 452: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache.dswmakefile.winnmakeApache.dsp

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

modules\

support\Apache Apache

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

Page 453: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache \Apache2

dirnmake

nmake/fMakefile.wininstallrINSTDIR=dir

nmake/fMakefile.wininstalldINSTDIR=dir

INSTDIRdir \Apache2

dir\bin\Apache.exe-Apachedir\bin\ApacheMonitor.exe-dir\bin\htdigest.exe-(Digestauth passwordfileutility)dir\bin\htdbm.exe-SDBM(SDBMauth databasepasswordfileutility)dir\bin\htpasswd.exe-(Basicauth passwordfileutility)dir\bin\logresolve.exe-dnsdir\bin\rotatelogs.exe-dir\bin\wintty.exe-dir\bin\libapr.dll-Apachedir\bin\libaprutil.dll-Apachedir\bin\libhttpd.dll-Apachedir\modules\mod_*.so-Apachedir\conf-dir\logs-dir\include-Cdir\lib-

Apache

.dsp .mak

Page 454: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DeveloperStudio

makeBuildBin( _apacher _apached

.mak .mak( .dep)PlatformSDKDevStudio\SharedIDE\bin\(VC5)DevStudio\Common\MSDev98\bin\(VC6) sysincl.dat

VC++ (srclib/apr/build/fixwin32mak.pl.mak

Page 455: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 456: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UsingApacheWithNovellNetWare

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

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

MostofthisdocumentassumesthatyouareinstallingApachefromabinarydistribution.IfyouwanttocompileApacheyourself(possiblytohelpwithdevelopment,ortotrackdownbugs),seethesectiononCompilingApacheforNetWarebelow.

Page 457: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Requirements

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

NetWareservicepacksareavailablehere.

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

Page 458: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DownloadingApacheforNetWare

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

Page 459: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

InstallingApacheforNetWare

ThereisnoApacheinstallprogramforNetWarecurrently.IfyouarebuildingApache2.0forNetWarefromsource,youwillneedtocopythefilesovertotheservermanually.

FollowthesestepstoinstallApacheonNetWarefromthebinarydownload(assumingyouwillinstalltosys:/apache2):

UnzipthebinarydownloadfiletotherootoftheSYS:volume(maybeinstalledtoanyvolume)Editthehttpd.conffilesettingServerRootServerNamealongwithanyfilepathvaluestoreflectyourcorrectserversettingsAddSYS:/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.CONVMAGICfilestoSYS:/APACHE2/CONFdirectoryCopyallfilesandsubdirectoriesin\HTTPD-2.0\DOCS\ICONStoSYS:/APACHE2/ICONSCopyallfilesandsubdirectoriesin\HTTPD-2.0\DOCS\MANUALtoSYS:/APACHE2/MANUAL

Page 460: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Copyallfilesandsubdirectoriesin\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).

Page 461: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RunningApacheforNetWare

TostartApachejusttypeapacheattheconsole.ThiswillloadapacheintheOSaddressspace.IfyouprefertoloadApacheinaprotectedaddressspaceyoumayspecifytheaddressspacewiththeloadstatementasfollows:

loadaddressspace=apache2apache2

ThiswillloadApacheintoanaddressspacecalledapache2.RunningmultipleinstancesofApacheconcurrentlyonNetWareispossiblebyloadingeachinstanceintoitsownprotectedaddressspace.

AfterstartingApache,itwillbelisteningtoport80(unlessyouchangedtheListendirectiveintheconfigurationfiles).Toconnecttotheserverandaccessthedefaultpage,launchabrowserandentertheserver'snameoraddress.Thisshouldrespondwithawelcomepage,andalinktotheApachemanual.Ifnothinghappensoryougetanerror,lookintheerror_logfileinthelogsdirectory.

Onceyourbasicinstallationisworking,youshouldconfigureitproperlybyeditingthefilesintheconfdirectory.

TounloadApacherunningintheOSaddressspacejusttypethefollowingattheconsole:

unloadapache2

apache2shutdown

Ifapacheisrunninginaprotectedaddressspacespecifytheaddressspaceintheunloadstatement:

Page 462: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.ThesedirectivesareonlyavailablewhileApacheisrunning.Eachofthesedirectivesmustbeprecededbythe

Page 463: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

keywordAPACHE2.

RESTARTInstructsApachetoterminateallrunningworkerthreadsastheybecomeidle,rereadtheconfigurationfileandrestarteachworkerthreadbasedonthenewconfiguration.

VERSIONDisplaysversioninformationaboutthecurrentlyrunninginstanceofApache.

MODULESDisplaysalistofloadedmodulesbothbuilt-inandexternal.

DIRECTIVESDisplaysalistofallavailabledirectives.

SETTINGSEnablesordisablesthethreadstatusdisplayontheconsole.Whenenabled,thestateofeachrunningthreadsisdisplayedontheApacheconsolescreen.

SHUTDOWNTerminatestherunninginstanceoftheApachewebserver.

HELPDescribeseachoftheruntimedirectives.

BydefaultthesedirectivesareissuedagainsttheinstanceofApacherunningintheOSaddressspace.Toissueadirectiveagainstaspecificinstancerunninginaprotectedaddressspace,includethe-pparameteralongwiththenameoftheaddressspace.Formoreinformationtype"apache2Help"onthecommandline.

Page 464: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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-Thisdirectiveinstructstheservertobeginterminatingworkerthreadsifthenumberofidlethreadsever

Page 465: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

exceedsthisvalue.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.

Page 466: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

NWSSLTrustedCerts-Addstrustedcertificatesthatareusedtocreatesecureconnectionstoproxiedservers.

NWSSLUpgradeable-Allowaconnectioncreatedonthespecifiedaddress/porttobeupgradedtoanSSLconnection.

Page 467: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CompilingApacheforNetWare

CompilingApacherequiresMetroWerksCodeWarrior6.xorhigher.OnceApachehasbeenbuilt,itcanbeinstalledtotherootofanyNetWarevolume.Thedefaultisthesys:/Apache2directory.

Beforerunningtheserveryoumustfillouttheconfdirectory.CopythefileHTTPD-STD.CONFfromthedistributionconfdirectoryandrenameittoHTTPD.CONF.EdittheHTTPD.CONFfilesearchingforall@@Value@@markersandreplacingthemwiththeappropriatesetting.Copyovertheconf/magicconf/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:

Page 468: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SetNOVELLLIBC=c:\novell\ndk\libc

SettheenvironmentvariableMETROWERKStothelocationwhereyouinstalledtheMetrowerksCodeWarriorcompiler,forexample:

SetMETROWERKS=C:\Program

Files\Metrowerks\CodeWarrior

IfyouinstalledtothedefaultlocationC:\ProgramFiles\Metrowerks\CodeWarrior,youdon'tneedtosetthis.SettheenvironmentvariableLDAPSDKtothelocationwhereyouinstalledtheLDAPLibrariesforC,forexample:

Set

LDAPSDK=c:\Novell\NDK\cldapsdk\NetWare\libc

SettheenvironmentvariableZLIBSDKtothelocationwhereyouinstalledthesourcecodefortheZLibLibrary,forexample:

SetZLIBSDK=D:\NOVELL\zlib

SettheenvironmentvariableAP_WORKtothefullpathofthehttpdsourcecodedirectory.

SetAP_WORK=D:\httpd-2.0.x

SettheenvironmentvariableAPR_WORKtothefullpathoftheaprsourcecodedirectory.Typically\httpd\srclib\aprbuttheAPRprojectcanbeoutsideofthehttpddirectorystructure.

SetAPR_WORK=D:\apr-1.x.x

Page 469: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SettheenvironmentvariableAPU_WORKtothefullpathoftheapr-utilsourcecodedirectory.Typically\httpd\srclib\apr-utilbuttheAPR-UTILprojectcanbeoutsideofthehttpddirectorystructure.

SetAPU_WORK=D:\apr-util-1.x.x

MakesurethatthepathtotheAWKutilityandtheGNUmakeutility(gmake.exe)havebeenincludedinthesystem'sPATHenvironmentvariable.Downloadthesourcecodeandunziptoanappropriatedirectoryonyourworkstation.Changedirectoryto\httpd-2.0andbuildtheprebuildutilitiesbyrunning"gmake-fnwgnumakefileprebuild".Thistargetwillcreatethedirectory\httpd-2.0\nwprebuildandcopyeachoftheutilitiestothislocationthatarenecessarytocompletethefollowingbuildsteps.Copythefiles\httpd-2.0\nwprebuild\GENCHARS.nlm\httpd-2.0\nwprebuild\DFTABLES.nlmtotheSYS:volumeofaNetWareserverandrunthemusingthefollowingcommands:

SYS:\genchars>sys:\test_char.h

SYS:\dftablessys:\chartables.c

Copythefilestest_char.hchartables.ctothedirectory\httpd-2.0\os\netwareonthebuildmachine.Changedirectoryto\httpd-2.0andbuildApachebyrunning"gmake-fnwgnumakefile".Youcancreateadistributiondirectorybyaddinganinstallparametertothecommand,forexample:

gmake-fnwgnumakefileinstall

Page 470: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Additionalmakeoptionsgmake-fnwgnumakefile

Buildsreleaseversionsofallofthebinariesandcopiesthemtoa\releasedestinationdirectory.

gmake-fnwgnumakefileDEBUG=1

Buildsdebugversionsofallofthebinariesandcopiesthemtoa\debugdestinationdirectory.

gmake-fnwgnumakefileinstall

CreatesacompleteApachedistributionwithbinaries,docsandadditionalsupportfilesina\dist\Apache2directory.

gmake-fnwgnumakefileprebuild

Buildsalloftheprebuildutilitiesandcopiesthemtothe\nwprebuilddirectory.

gmake-fnwgnumakefileinstalldev

Sameasinstallbutalsocreatesa\lib\includedirectoryinthedestinationdirectoryandcopiesheadersandimportfiles.

gmake-fnwgnumakefileclean

Cleansallobjectfilesandbinariesfromthe\release.o\debug.obuildareasdependingonwhetherDEBUGhasbeendefined.

gmake-fnwgnumakefileclobber_all

Sameascleanandalsodeletesthedistributiondirectoryifitexists.

AdditionalenvironmentvariableoptionsTobuildalloftheexperimentalmodules,settheenvironmentvariableEXPERIMENTAL:

Page 471: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SetEXPERIMENTAL=1

TobuildApacheusingstandardBSDstylesocketsratherthanWinsock,settheenvironmentvariableUSE_STDSOCKETS:

SetUSE_STDSOCKETS=1

Buildingmod_sslfortheNetWareplatformBydefaultApacheforNetWareusesthebuilt-inmodulemod_nw_ssltoprovideSSLservices.ThismodulesimplyenablesthenativeSSLservicesimplementedinNetWareOStohandleallencryptionforagivenport.Alternatively,mod_sslcanalsobeusedinthesamemannerasonotherplatforms.

Beforemod_sslcanbebuiltfortheNetWareplatform,theOpenSSLlibrariesmustbeprovided.Thiscanbedonethroughthefollowingsteps:

DownloadthelatestNetWarepatchforOpenSSLfromtheOpenSSLContributionpage.DownloadthecorrespondingOpenSSLsourcecodefromtheOpenSSLSourcepage.AttherootoftheOpenSSLsourcedirectory,applytheNetWarepatchusingthe"patch"utility,forexample:

patch-p1-inetwarepatch-0.9.7g.diff

EditthefileNetWare/set_env.batandmodifyanytoolsandutilitiespathssothattheycorrespondtoyourbuildenvironment.FromtherootoftheOpenSSLsourcedirectory,runthefollowingscripts:

Netware/set_envnetware-libc

Page 472: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Netware/buildnetware-libc

BeforebuildingApache,settheenvironmentvariableOSSLSDKtothefullpathtotherootoftheopensslsourcecodedirectory.

SetOSSLSDK=d:\openssl-0.9.7x

Page 473: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 474: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RunningaHigh-PerformanceWebServeronHPUX

Date:Wed,05Nov199716:59:34-0800

From:RickJones<[email protected]>

Reply-To:[email protected]

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.

Page 475: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 476: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Page 477: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 478: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TheApacheEBCDICPort

Warning:Thisdocumenthasnotbeenupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.

Page 479: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

OverviewoftheApacheEBCDICPort

Version1.3oftheApacheHTTPServeristhefirstversionwhichincludesaporttoa(non-ASCII)mainframemachinewhichusestheEBCDICcharactersetasitsnativecodeset.

(ItistheSIEMENSfamilyofmainframesrunningtheBS2000/OSDoperatingsystem.ThismainframeOSnowadaysfeaturesaSVR4-derivedPOSIXsubsystem).

Theportwasstartedinitiallyto

provethefeasibilityofportingtheApacheHTTPservertothisplatformfinda"worthyandcapable"successorforthevenerableCERN-3.0daemon(whichwasportedacoupleofyearsago),andtoprovethatApache'spreforkingprocessmodelcanonthisplatformeasilyoutperformtheaccept-fork-servemodelusedbyCERNbyafactorof5ormore.

Thisdocumentservesasarationaletodescribesomeofthedesigndecisionsoftheporttothismachine.

Page 480: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DesignGoals

OneobjectiveoftheEBCDICportwastomaintainenoughbackwardscompatibilitywiththe(EBCDIC)CERNservertomakethetransitiontothenewserverattractiveandeasy.ThisrequiredtheadditionofaconfigurablemethodtodefinewhetheraHTMLdocumentwasstoredinASCII(theonlyformatacceptedbytheoldserver)orinEBCDIC(thenativedocumentformatinthePOSIXsubsystem,andthereforetheonlyrealisticformatinwhichtheotherPOSIXtoolslikegrepsedcouldoperateonthedocuments).Thecurrentsolutiontothisisa"pseudo-MIME-format"whichisinterceptedandinterpretedbytheApacheserver(seebelow).Futureversionsmightsolvetheproblembydefiningan"ebcdic-handler"foralldocumentswhichmustbeconverted.

Page 481: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TechnicalSolution

SinceallApacheinputandoutputisbasedupontheBUFFdatatypeanditsmethods,theeasiestsolutionwastoaddtheconversiontotheBUFFhandlingroutines.Theconversionmustbesettableatanytime,soaBUFFflagwasaddedwhichdefineswhetheraBUFFobjecthascurrentlyenabledconversionornot.ThisflagismodifiedatseveralpointsintheHTTPprotocol:

setbeforearequestisreceived(becausetherequestandtherequestheaderlinesarealwaysinASCIIformat)set/unsetwhentherequestbodyisreceived-dependingonthecontenttypeoftherequestbody(becausetherequestbodymaycontainASCIItextorabinaryfile)setbeforeareplyheaderissent(becausetheresponseheaderlinesarealwaysinASCIIformat)set/unsetwhentheresponsebodyissent-dependingonthecontenttypeoftheresponsebody(becausetheresponsebodymaycontaintextorabinaryfile)

Page 482: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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()rvputs()forstrings,andfunctionslikebwrite()forbinarydata.Aglobaltranslationofeverythingwouldthereforebeinadequate.

(Inthecaseoftextfilesofcourse,provisionsmustbemadesothatEBCDICdocumentsarealwaysservedinASCII)

3. Thisportthereforefeaturesabuilt-inprotocollevelconversionfor

Page 483: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

theserver-internalstrings(whichthecompilertranslatedtoEBCDICstrings)andthusforallserver-generateddocuments.ThehardcodedASCIIescapes\012\015whichareubiquitousintheservercodeareanexception:theyarealreadythebinaryencodingoftheASCII\n\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:

Page 484: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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,.GIF/ZIP/AUfiletypes.Thisofcourserequirestheusertocopythemtothemainframehostusingthe"rcp-b"binaryswitch.

7. Serverparsedfilesarealwaysassumedtobeinnative(i.e.,EBCDIC)formatasusedonthemachine,andareconvertedafterprocessing.

8. ForCGIoutput,theCGIscriptdetermineswhetheraconversionisneededornot:bysettingtheappropriateContent-Type,textfilescanbeconverted,orGIFoutputcanbepassedthroughunmodified.Anexampleforthelattercaseisthewwwcountprogramwhichweportedaswell.

Page 485: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.

Page 486: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheModules'Status

Module Status Notescore +mod_authz_host +mod_actions +mod_alias +mod_asis +mod_auth_basic +mod_authn_file +mod_authn_anon +mod_authn_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_imagemap +mod_include +mod_info +mod_log_agent +mod_log_config +mod_mime +mod_mime_magic ? notportedyetmod_negotiation +

Page 487: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_proxy +mod_rewrite + untestedmod_setenvif +mod_speling +mod_status +mod_unique_id +mod_userdir +mod_usertrack ? untested

Page 488: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ThirdPartyModules'Status

Module Status Notesmod_jserv - JAVAstillbeingported.mod_php3 + mod_php3runsfine,withLDAPandGDand

FreeTypelibraries.mod_put ? untestedmod_session - untested

Page 489: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006114|

Page 490: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httpd-Apache

httpdApache(HTTP)

httpdUnix apachectl WindowsNT/2000/XP/2003Windows95/98/ME .

Page 491: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httpd[-dserverroot][-fconfig][-C

directive][-cdirective][-Dparameter][-e

level][-Efile][-k

start|restart|graceful|stop|graceful-stop][-R

directory][-h][-l][-L][-S][-t][-v

][-V][-X][-M]

Windows

httpd[-kinstall|config|uninstall][-nname][

-w]

Page 492: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-dserverroot

ServerRootserverrootServerRoot /usr/local/apache2

-fconfig

config config"/" ServerRoot conf/httpd.conf

-kstart|restart|graceful|stop|graceful-stop

httpd Apache

-Cdirective

directive

-cdirective

directive

-Dparameter

parameter<IfDefine>

-elevel

LogLevellevel

-Efile

file

-Rdirectory

SHARED_CORE directory

-h

-l

LoadModule

-L

-M

DSO

-S

()

Page 493: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

-t

"0"(OK)0(Error)"-D DUMP_VHOSTS"

-v

httpd

-V

httpd

-X

httpd

Windows

-kinstall|config|uninstall

ApacheWindowsNTApacheApache

-nname

Apachename

-w

Page 494: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006113|

Page 495: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ab-ApacheHTTP

abApache(HTTP)ApacheApache

Page 496: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ab[-Aauth-username:password][-cconcurrency]

[-Ccookie-name=value][-d][-ecsv-file][-

ggnuplot-file][-h][-Hcustom-header][-i]

[-k][-nrequests][-pPOST-file][-Pproxy-

auth-username:password][-q][-s][-S][-t

timelimit][-Tcontent-type][-vverbosity][-

V][-w][-x<table>-attributes][-X

proxy[:port]][-y<tr>-attributes][-z<td>-

attributes][http://]hostname[:port]/path

Page 497: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-Aauth-username:password

" :"base64(401)

-cconcurrency

-Ccookie-name=value

" Cookie:" name=value

-d

"percentageservedwithinXX[ms]table"()

-ecsv-file

(CSV)(1%100%)()"""gnuplot"

-ggnuplot-file

"gnuplot"TSV(Tab)Gnuplot,IDL,Mathematica,Excel

-h

-Hcustom-header

( "Accept-Encoding:zip/zop;8bit")

-i

HEAD GET

-k

KeepAliveHTTPKeepAlive

-nrequests

-pPOST-file

POST

-Pproxy-auth-username:password

" :"base64(407)

-q

150 ab10%100 stderr -q

Page 498: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-s

(ab-h)SSL httpshttp

-S

12//()

-ttimelimit

" -n50000"

-Tcontent-type

POST"Content-type"

-vverbosity

4 3(404200) 2

-V

-w

HTML

-x<table>-attributes

<table> <table>

-Xproxy[:port]

-y<tr>-attributes

<tr>

-z<td>-attributes

<td>

Page 499: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Bugs

HTTP/1.x"" strstr() ab

Page 500: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006113|

Page 501: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

apachectl-ApacheHTTP

apachectlApacheHTTPApache

apachectl httpd httpdSysVstart,restart,stophttpd

Apache apachectlhttpd httpd

apachectl0>0

Page 502: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

apachectlhttpd

apachectl[httpd-argument]

SysV apachectl

apachectlcommand

Page 503: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

SysV httpd

start

Apachehttpd apachectl-kstart

stop

Apachehttpd apachectl-kstop

restart

Apachehttpd configtestApacheapachectl-krestart

fullstatus

mod_status mod_status lynxSTATUSURLURL

status

fullstatus

graceful

ApachehttpdconfigtestApache apachectl-kgraceful

graceful-stop

Apachehttpdstop

configtest

SyntaxOk apachectl-t

startssl

SSLhttpdSSL apachectlstart

Page 504: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006113|

Page 505: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

apxs-Apache

apxsApacheHTTP mod_soLoadModuleApache

DSOApache httpdmod_so apxs

$httpd-l

mod_so apxsDSOApache

$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:httpd

notrunning,tryingtostart

[TueMar3111:27:551998][debug]

mod_so.c(303):loadedmodulefoo_module

/path/to/apache/sbin/apachectlrestart:httpd

started

$_

filesC(.c)(.o)(.a) apxsC(PIC)GCC -fpic

C apxs

ApacheDSO mod_so

src/modules/standard/mod_so.c

Page 506: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 507: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

apxs-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...

Page 508: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-nmodname

-i() -g() -g -i apxs()

-q

apxs query CC,CFLAGS,CFLAGS_SHLIB,INCLUDEDIR,LD_SHLIB,LDFLAGS_SHLIB,LIBEXECDIR,LIBS_SHLIB,SBINDIR,SYSCONFDIR,TARGETApacheCMakefile

INC=-I`apxs-qINCLUDEDIR`

-Sname=value

apxs

-g

name( -n) mod_name.capxs Makefile

DSO-c

C(.c) files(.o) files(.o.a) dsofile -o filesmod_name.so

-odsofile

files mod_unknown.so

-Dname=value

Page 509: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-Iincdir

-Llibdir

-llibname

-Wc,compiler-flags

libtool--mode=compilecompiler-flags

-Wl,linker-flags

libtool--mode=linklinker-flags

DSO-i

modules

-a

LoadModulehttpd.conf

-A

-a LoadModule(#)

-e

-a -A -iApache httpd.conf

Page 510: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_foo.cCApache

$apxs-cmod_foo.c

/path/to/libtool--mode=compilegcc...-c

mod_foo.c

/path/to/libtool--mode=linkgcc...-omod_foo.la

mod_foo.slo

$_

Apache LoadModule apxs"modules"httpd.conf

$apxs-i-amod_foo.la

/path/to/instdso.shmod_foo.la

/path/to/apache/modules

/path/to/libtool--mode=installcpmod_foo.la

/path/to/apache/modules...chmod755

/path/to/apache/modules/mod_foo.so

[activatingmodule'foo'in

/path/to/apache/conf/httpd.conf]

$_

LoadModulefoo_modulemodules/mod_foo.so

-A

$apxs-i-Amod_foo.c

apxsApacheMakefile

$apxs-g-nfoo

Page 511: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Creating[DIR]foo

Creating[FILE]foo/Makefile

Creating[FILE]foo/modules.mk

Creating[FILE]foo/mod_foo.c

Creating[FILE]foo/.deps

$_

Apache

$cdfoo

$makeallreload

apxs-cmod_foo.c

/path/to/libtool--mode=compilegcc...-c

mod_foo.c

/path/to/libtool--mode=linkgcc...-omod_foo.la

mod_foo.slo

apxs-i-a-n"foo"mod_foo.la

/path/to/instdso.shmod_foo.la

/path/to/apache/modules

/path/to/libtool--mode=installcpmod_foo.la

/path/to/apache/modules...chmod755

/path/to/apache/modules/mod_foo.so

[activatingmodule'foo'in

/path/to/apache/conf/httpd.conf]

apachectlrestart

/path/to/apache/sbin/apachectlrestart:httpdnot

running,tryingtostart

[TueMar3111:27:551998][debug]mod_so.c(303):

loadedmodulefoo_module

/path/to/apache/sbin/apachectlrestart:httpd

started

$_

Page 512: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006115|

Page 513: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

configure-

configureApacheApache

Unix

Page 514: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

configure

./configure[OPTION]...[VAR=VALUE]...

( CC,CFLAGS...) VAR=VALUE

Page 515: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

apr-config

configure"[]"

-C

--config-cache

--cache-file=config.cache

--cache-file=FILE

FILE()

-h

--help[short|recursive]

shortApache recursive

-n

--no-create

configure

-q

--quiet

" checking..."

--srcdir=DIR

DIR[configure]

--silent

Page 516: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

--quiet

-V

--version

"[]"

--prefix=PREFIX

PREFIXApache[ /usr/local/apache2]

--exec-prefix=EPREFIX

EPREFIX[ PREFIX]

makeinstall/usr/local/apache2/bin,/usr/local/apache2/lib --prefix/usr/local/apache2 --prefix=$HOME

--enable-layout=LAYOUT

LAYOUTApache config.layout <Layout

FOO>...</Layout> FOO Apache

autoconf"[]"

--bindir=DIR

DIRhtpasswd,dbmmanage[EPREFIX/bin]

--datadir=DIR

WebDIRautoconfApache[PREFIX/share]

--includedir=DIR

Page 517: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheCDIR[EPREFIX/include]

--infodir=DIR

DIRautoconfApache[PREFIX/info]

--libdir=DIR

DIR[EPREFIX/lib]

--libexecdir=DIR

DIR[EPREFIX/libexec]

--localstatedir=DIR

DIRautoconfApache[PREFIX/var]

--mandir=DIR

DIR[EPREFIX/man]

--oldincludedir=DIR

gccCDIRautoconfApache[/usr/include]

--sbindir=DIR

DIRHTTPhttpd,apachectl,suexec[EPREFIX/sbin]

--sharedstatedir=DIR

DIRautoconfApache[PREFIX/com]

--sysconfdir=DIR

DIRhttpd.confmime.types[PREFIX/etc]

Page 518: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTPApacheHTTP"[]"

--build=BUILD

BUILD[config.guess]

--host=HOST

ApacheHTTPHOST[BUILD]

--target=TARGET

configureforbuildingcompilersforTARGET autoconf

Apache[HOST]

DSODSOmod_soDSODSO"--enable-so=static"

--disable-MODULE

MODULE()

--enable-MODULE=shared

MODULEDSO()

--enable-MODULE=static

MODULE()

--enable-mods-shared=MODULE-LIST

MODULE-LISTDSO()

--enable-modules=MODULE-LIST

MODULE-LIST()

MODULE-LIST

Page 519: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(1)

--enable-mods-shared='headersrewritedav'

(2)"most"()(3)" all"()

--enable-mods-shared=most

configureMODULEMODULE-LIST MODULEMODULE-LIST" mod_NAME"" mod_"" _"" -"" mod_log_config"" log-config"

(B)(E)/(X)

mod_actions (B) CGImod_alias (B) URLmod_asis (B) HTTPmod_auth_basic (B)mod_authn_default (B)mod_authn_file (B)mod_authz_default (B)mod_authz_groupfile (B)mod_authz_host (B) IPmod_authz_user (B)mod_autoindex (B) "ls""dir"mod_cgi (B) MPM(prefork)CGImod_cgid (B) MPM(worker)CGICGI

Page 520: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_dir (B) ""mod_env (B) ApacheCGISSImod_filter (B)mod_imagemap (B)mod_include (B) (SSI)mod_isapi (B) WindowsISAPImod_log_config (B)mod_mime (B) (/)(MIME///)mod_negotiation (B)mod_nw_ssl (B) NetWareSSLmod_setenvif (B)mod_status (B) Webmod_userdir (B) ("/~username")mod_auth_digest (X) MD5()mod_authn_alias (E)mod_authn_anon (E)mod_authn_dbd (E) SQLmod_authn_dbm (E) DBMmod_authnz_ldap (E) LDAPmod_authz_dbm (E) DBMmod_authz_owner (E)mod_cache (E) URI()mod_cern_meta (E) ApacheCERNhttpdmod_charset_lite (X)mod_dav (E) ApacheDAVmod_dav_fs (E) mod_davmod_dav_lock (E) mod_davmod_dbd (E) SQLmod_deflate (E)

Page 521: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_disk_cache (E)

mod_dumpio (E) I/Omod_echo (X)mod_example (X) ApacheAPImod_expires (E) HTTP" Expires:"" Cache-

Control:"mod_ext_filter (E)mod_file_cache (X) Apachemod_headers (E) HTTPmod_ident (E) RFC1413identmod_info (E) ApacheWebmod_ldap (E) LDAPLDAPmod_log_forensic (E) ""mod_logio (E) /HTTPmod_mem_cache (E)mod_mime_magic (E) MIMEmod_proxy (E) HTTP/1.1/mod_proxy_ajp (E) mod_proxyApacheJServ

Protocolmod_proxy_balancer (E) mod_proxymod_proxy_connect (E) mod_proxyHTTP CONNECT

mod_proxy_ftp (E) mod_proxyFTPmod_proxy_http (E) mod_proxyHTTPmod_rewrite (E) URLmod_so (E) DSOmod_speling (E) URLmod_ssl (E) (SSL)(TLS)mod_suexec (E) webCGISSImod_unique_id (E)

Page 522: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_usertrack (E) Session(Cookie)

mod_version (E)mod_vhost_alias (E)

(MPM)MPM

--with-mpm=MPM

MPM MPMMPM beos,mpmt_os2,prefork,worker

--with-module=module-type:module-file[,module-

type:module-file]

module-fileApahe" modules/module-type"configuremodule-file" modules/module-type"" modules/module-type" configure

" modules/module-type" Makefile.in

1.

2. DSO

apxs(Apache)

--enable-nonportable-atomics

486CPUApache

--enable-v4-mapped

IPv4IPv6FreeBSDNetBSDOpenBSD

--disable-v4-mapped

Page 523: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IPv4IPv6FreeBSDNetBSDOpenBSD

--enable-maintainer-mode

--enable-exception-hook

EnableExceptionHook

--with-port=PORT

httpd[ 80] httpd.conf

--with-program-name=NAME

[ httpd]" NAME.conf"

apr-config

--disable-threads

MPM

--disable-ipv6

IPv6

--disable-dso

DSO

--with-apr=DIR|FILE

Apache(APR)httpdhttpdAPR apr-configAPR( apr-

config" bin")

--with-apr-util=DIR|FILE

Apache(APU)httpdhttpdAPU apu-configAPU( apu-

config" bin")

--with-ssl=DIR

mod_sslconfigureOpenSSLSSL/TLS

Page 524: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

--with-z=DIR

( mod_deflate) configurezlib

--with-perl=DIR

Perl apxsdbmmanagePerl5(5.003)PerlPerl4Perl5Perl5Apachehttpd

--with-pcre=DIR

5.0Perl(PCRE)PCRE

--with-ldap=DIR

Apache mod_ldapmod_authnz_ldapAPULDAP()LDAP

Apache mod_authn_dbmmod_rewriteDBMAPUSDBM

--with-gdbm[=path]

GNUDBMSDBM pathconfigureGNUDBM pathconfigurepath/libpath/includeGNUDBM" inc-path:lib-path"GNUDBM

--with-ndbm[=path]

NewDBMSDBM pathconfigureNewDBM pathconfigurepath/libpath/includeNewDBM" inc-path:lib-path"NewDBM

--with-berkeley-db[=path]

BerkeleyDBSDBM pathconfigureBerkeleyDB pathconfigurepath/libpath/includeBerkeleyDB" inc-path:lib-path"BerkeleyDB

DBMAPUAPU --with-apr-utilAPUDBM

Page 525: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

--enable-static-support

()

--enable-static-ab

ab

--enable-static-checkgid

checkgid

--enable-static-htdbm

htdbm

--enable-static-htdigest

htdigest

--enable-static-htpasswd

htpasswd

--enable-static-logresolve

logresolve

--enable-static-rotatelogs

rotatelogs

suexec--enable-suexec

suexecCGIuidgidsuexec

suexec"[]" suEXEC

--with-suexec-bin

suexec[--sbindir]

--with-suexec-caller

suexec httpd

--with-suexec-docroot

suexec[--datadir/htdocs]

--with-suexec-gidmin

suexecGID[100]

Page 526: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

--with-suexec-logfile

suexec[ suexec_log--logfiledir]

--with-suexec-safepath

suexec"" PATH[/usr/local/bin:/usr/bin:/bin]

--with-suexec-userdir

suexec suexec( mod_userdir)[ public_html]

--with-suexec-uidmin

suexecUID[100]

--with-suexec-umask

suexecumask[]

Page 527: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

configure configure/

CC

C

CFLAGS

Cflags

CPP

C

CPPFLAGS

C/C++flags" -Iincludedir" includedir

LDFLAGS

flags"-L -Llibdir" libdir

Page 528: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006113|

Page 529: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

dbmmanage-DBM

dbmmanageDBM mod_authn_dbmHTTPApacheHTTPdbmmanageDBM htpasswd

Page 530: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

dbmmanage[encoding]filename

add|adduser|check|delete|updateusername[

encpasswd[group[,group...][comment]]]

dbmmanagefilenameview[username]

dbmmanagefilenameimport

Page 531: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

filename

DBM .db,.pag,.dir

username

username(:)

encpasswd

updateadd( -) update( .)

group

( :)( -) comment update( .)

comment

-d

crypt(WindowsNetware)

-m

MD5(WindowsNetware)

-s

SHA1

-p

()

add

filenameusernameencpasswd

dbmmanagepasswords.dataddrbowen

foKntnEF3KSXA

adduser

filenameusername

Page 532: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

dbmmanagepasswords.datadduserkrietz

check

filenameusername

dbmmanagepasswords.datcheckrbowen

delete

filenameusername

dbmmanagepasswords.datdeleterbowen

import

STDIN username:password() filename

update

adduser usernamefilename

dbmmanagepasswords.datupdaterbowen

view

DBM username

dbmmanagepasswords.datview

Page 533: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Bugs

DBMSDBM,NDBM,GDBM,BerkeleyDB2filenamedbmmanage dbmmanageDBMnothingDBMDBM

dbmmanageDBM @AnyDBM::ISABerkeleyDB2dbmmanageBerkeleyDB2,NDBM,GDBM,SDBM

dbmmanageDBMperl @AnyDBM::ISADBMC

Unix fileDBM

Page 534: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006113|

Page 535: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htcacheclean-

htcachecleanmod_disk_cacheTERMINT

Page 536: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htcacheclean[-D][-v][-t][-r][-n]-

ppath-llimit

htcacheclean-b[-n][-t][-i]-dinterval-

ppath-llimit

Page 537: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-dinterval

interval -D,-v,-r SIGTERMSIGINT

-D

"" -d

-v

-d

-r

Apacheweb() -d -t

-n

htcacheclean(a)IO(b)

-t

inode

-ppath

path CacheRoot

-llimit

limit xxBxx xxKxx xxMxx

-i

-d

Page 538: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

htcacheclean" 0"" 1"

Page 539: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006321|

Page 540: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htdbm-DBM

htdbmmod_authn_dbmHTTPDBM dbmmanageDBM

Page 541: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htdbm[-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]

Page 542: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-b

-c

passwdfile passwdfile -n

-n

passwdfile() -c

-m

MD5Windows,Netware,TPF

-d

crypt()Windows,Netware,TPF htdbmWindows,Netware,TPF httpd

-s

SHALDAPNetscapeserver

-p

() htdbm httpdWindows,Netware,TPF

-l

-t

"Comment"

-v

"3"

-x

filename

DBM .db,.pag,.dir -cDBM

username

passwdfile username

password

-b

Page 543: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-TDBTYPE

DBM(SDBM,GDBM,DB,"default")

Page 544: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Bugs

DBMSDBM,NDBM,GNUGDBM,Berkeley/SleepycatDB2/3/4filenamehtdbm htdbm

DBM

Unix fileDBM

Page 545: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htdbm" 0"" 1"" 2"" 3"" 4"(username,filename,password,)" 5"( )" 6"" 7"

Page 546: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htdbm/usr/local/etc/apache/.htdbm-usersjsmith

jsmithWindowsApacheMD5 crypt() htdbm

htdbm-c/home/doe/public_html/.htdbmjane

jane htdbm

htdbm-mb/usr/web/.htdbm-alljonesPwd4Steve

(Pwd4Steve)MD5

Page 547: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Web( htdbm)

-b

Page 548: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

WindowsMPE htdbm255

htdbmMD5ApacheApacheWeb

255( :)

Page 549: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006114|

Page 550: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htdigest-

htdigest// htdigest

mod_auth_digest

Page 551: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htdigest[-c]passwdfilerealmusername

Page 552: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

-c

passwdfilepasswdfile

passwdfile

// -c

realm

username

passwdfile username

Page 553: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006114|

Page 554: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htpasswd-

htpasswd/ htpasswd

htpasswdDBM dbmmanage

htpasswdApacheMD5crypt() htpasswdMD5crypt()

mod_auth_basic

Page 555: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htpasswd[-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

Page 556: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-b

-c

passwdfile passwdfile -n

-n

Apache passwdfile() -c

-m

MD5Windows,Netware,TPF

-d

crypt()Windows,Netware,TPF htpasswdWindows,Netware,TPF httpd

-s

SHALDAPNetscapeserver

-p

() htpasswd httpdWindows,Netware,TPF

-D

usernamepasswdfile

passwdfile

-c

username

passwdfile username

password

-b

Page 557: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htpasswdpasswdfile" 0"" 1"" 2"" 3"" 4"(username,filename,password,)" 5"( )" 6"" 7"

Page 558: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

htpasswd/usr/local/etc/apache/.htpasswd-users

jsmith

jsmithWindowsApacheMD5 crypt()

htpasswd

htpasswd-c/home/doe/public_html/.htpasswdjane

jane htpasswd

htpasswd-mb/usr/web/.htpasswd-alljones

Pwd4Steve

(Pwd4Steve)MD5

Page 559: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Web( htpasswd)

-b

Page 560: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

WindowsMPE htdbm255

htdbmMD5ApacheApacheWeb

255( :)

Page 561: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006114|

Page 562: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

logresolve-ApacheIP

logresolveApacheIPIP

ApacheIP

Page 563: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

logresolve[-sfilename][-c]<access_log>

access_log.new

Page 564: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

-sfilename

-c

logresolveDNSIPIP

Page 565: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006114|

Page 566: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

rotatelogs-Apache

rotatelogsApache

CustomLog"|bin/rotatelogs/var/logs/logfile

86400"common

"/var/logs/logfile.nnnn"nnnn(cron)(24)

CustomLog"|bin/rotatelogs/var/logs/logfile

5M"common

5

ErrorLog"|bin/rotatelogs

/var/logs/errorlog.%Y-%m-%d-%H_%M_%S5M"

5 errorlog.YYYY-mm-dd-HH_MM_SS

Page 567: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

rotatelogs[-l]logfile[rotationtime[offset

]]|[filesizeM]

Page 568: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-l

GMTGMT() -l

logfile

logfile"%" strftime()" .nnnnnnnnnn"

rotationtime

offset

UTC"0"UTCUTC"-5"" -300"

filesizeM

filesizeM

Page 569: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

strftime() strftime()

%A ()%a 3()%B ()%b 3()%c ()%d 2%H 2(24)%I 2(12)%j 3%M 2%m 2%p am/pm12()%S 2%U 2()%W 2()%w 1()%X ()%x ()%Y 4%y 2%Z

%% "%"

Page 570: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006114|

Page 571: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache" support"

Page 572: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

log_server_status

perlcron

Page 573: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

split-logfile

perlweb(" %v")+" .log"

webstdin

Page 574: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |200619|

Page 575: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Apache

http://purl.org/NET/http-errata-HTTP/1.1http://www.rfc-editor.org/errata.html-RFChttp://ftp.ics.uci.edu/pub/ietf/http/#RFC-HTTPRFC

Page 576: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HTTP

ApachewebIETF

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.

Page 577: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HTML

(HTML)ApacheIETFW3C

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.

Page 578: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheIETF

RFC2617(Draftstandard)"HTTP/1.0",includesthespecificationforaBasicAccessAuthenticationscheme.

Page 579: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

/

ISO/

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.

Page 580: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006121|

Page 581: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 582: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 583: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(Status)

(Status)Apache

MPMMPM

Base

ExtensionApache

ExperimentalApache

ExternalApache("")

Page 584: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<IfModule>

Page 585: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LoadModule

Page 586: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Apache2.0

Page 587: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006121|

Page 588: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Page 589: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 590: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

()"|" "..."

URLhttp://www.example.com/path/to/file.html

URL-pathURL" /path/to/file.html"()

file-path" /usr/local/apache/htdocs/path/to/file.html"(/) ServerRoot

directory-path/usr/local/apache/htdocs/path/to/

filenamefile.html

regexPerl regex

extensionfilename"."Apache extensionfilename"."".""." extension" file.html.en" extension.htmlApache extension"."

MIME-typetext/html

env-variableApache

Page 591: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(Apache)" None"httpd.conf

Page 592: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

serverconfig(httpd.conf) <VirtualHost><Directory>.htaccess

virtualhost<VirtualHost>

directory<Directory>,<Location>,<Files>,<Proxy>

.htaccess.htaccess overrides

" serverconfig,.htaccess" httpd.conf

.htaccess<Directory><VirtualHost>

Page 593: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.htaccess .htaccess

AllowOverride() AllowOverride

Page 594: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

CoreApache

MPMMPM

BaseApache

ExtensionApache

Experimental

Page 595: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 596: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Apache2

Page 597: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006120|

Page 598: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache(Core)

ApacheHTTP(C)

Page 599: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AcceptFilter

SocketAcceptFilterprotocolaccept_filter

serverconfig(C)coreApache2.1.5

socketHTTPsocket FreeBSD(AcceptFilter)Linux(moreprimitive)TCP_DEFER_ACCEPT

FreeBSD

AcceptFilterhttphttpready

AcceptFilterhttpsdataready

httpready(AcceptFilter)HTTP accf_http(9)HTTPSaccf_data(9)

Linux

AcceptFilterhttpdata

AcceptFilterhttpsdata

LinuxTCP_DEFER_ACCEPThttp noneTCP_DEFER_ACCEPTtcp(7)

none(acceptfilter) nntp

AcceptFilternttpnone

Page 600: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AcceptPathInfo

AcceptPathInfoOn|Off|Default

AcceptPathInfoDefault

serverconfig,virtualhost,directory,.htaccessFileInfo(C)coreApache2.0.30

() PATH_INFO

/test/ here.html/test/here.html/more/test/nothere.html/morePATH_INFO" /more"

AcceptPathInfo

Off

/test/here.html/more"404NOTFOUND"

On

/test/here.html /test/here.html/more

Default

PATH_INFO cgi-scriptisapi-isaPATH_INFO

AcceptPathInfoPATH_INFO INCLUDESPATH_INFO

<Files"mypaths.shtml">

Options+Includes

SetOutputFilterINCLUDES

AcceptPathInfoOn

</Files>

Page 601: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 602: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AccessFileName

AccessFileNamefilename

AccessFileName.htaccess

serverconfig,virtualhost(C)core

AccessFileName.acl

/usr/local/web/index.html /.acl/usr/.acl/usr/local/.acl/usr/local/web/.acl

<Directory/>

AllowOverrideNone

</Directory>

AllowOverride

.htaccess

Page 603: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddDefaultCharset

text/plaintext/htmlHTTPAddDefaultCharsetOn|Off|charset

AddDefaultCharsetOff

serverconfig,virtualhost,directory,.htaccessFileInfo(C)core

text/plaintext/htmlHTTP <meta>

AddDefaultCharsetOff AddDefaultCharsetOnApache iso-8859-1IANAcharset

AddDefaultCharsetutf-8

AddDefaultCharset(CGI)

AddCharset

Page 604: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddOutputFilterByType

MIMEAddOutputFilterByTypefilter[;filter...]MIME-type

[MIME-type]...

serverconfig,virtualhost,directory,.htaccessFileInfo(C)coreApache2.0.33Apache2.1

MIME mod_filter

mod_deflateDEFLATE text/htmltext/plain()

AddOutputFilterByTypeDEFLATEtext/htmltext/plain

(;) AddOutputFilterByType

text/htmlINCLUDESDEFLATE

<Location/cgi-bin/>

OptionsIncludes

AddOutputFilterByTypeINCLUDES;DEFLATE

text/html

</Location>

AddOutputFilterByType MIME DefaultType

DefaultType

AddTypeForceType(non-nph)CGI

Page 605: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddOutputFilter

SetOutputFilter

Page 606: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AllowEncodedSlashes

URLAllowEncodedSlashesOn|Off

AllowEncodedSlashesOff

serverconfig,virtualhost(C)coreApache2.0.46

AllowEncodedSlashesURL("%2F"→"/"" %5C"→"\")URL"404"()

AllowEncodedSlashesOnPATH_INFO

() %2F%5C()URL

AcceptPathInfo

Page 607: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AllowOverride

.htaccess

AllowOverrideAll|None|directive-type[directive-

type]...

AllowOverrideAll

directory(C)core

.htaccess( AccessFileName)

<Directory>AllowOverride<Directory> <Location>,<DirectoryMatch>,<Files>

None.htaccess .htaccess

All".htaccess" .htaccess

directive-type

AuthConfig(AuthDBMGroupFile,AuthDBMUserFile,AuthGroupFile,AuthName,AuthType,AuthUserFile,Require,)

FileInfo(DefaultType,ErrorDocument,ForceType,LanguagePriority,SetHandler,SetInputFilter,SetOutputFilter,mod_mimeAdd*Remove*)(Header,RequestHeader,SetEnvIf,SetEnvIfNoCase,BrowserMatch,CookieExpires,CookieDomain,CookieStyle,CookieTracking,CookieName) mod_rewrite(RewriteEngine,RewriteOptions,RewriteBase,RewriteCond,

Page 608: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteRule)mod_actionsAction

Indexes(AddDescription,AddIcon,AddIconByEncoding,AddIconByType,DefaultIcon,DirectoryIndex,FancyIndexing,HeaderName,IndexIgnore,IndexOptions,ReadmeName,)

Limit(Allow,Deny,Order)

Options[=Option,...](OptionsXBitHack)() Options Options

.htaccessAuthConfigIndexes

AllowOverrideAuthConfigIndexes

AccessFileName

.htaccess

Page 609: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthName

HTTPAuthNameauth-domain

directory,.htaccessAuthConfig(C)core

AuthName AuthTypeRequireAuthUserFile

AuthGroupFile

AuthName"TopSecret"

AuthName

Page 610: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthType

AuthTypeBasic|Digest

directory,.htaccessAuthConfig(C)core

Basic(mod_auth_basic)Digest(mod_auth_digest)

AuthNameRequire( mod_authn_file)(mod_authz_user)

Page 611: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGIMapExtension

CGICGIMapExtensioncgi-path.extension

directory,.htaccessFileInfo(C)coreNetWareonly

ApacheCGI" CGIMapExtensionsys:\foo.nlm.foo".fooCGIFOO

Page 612: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ContentDigest

Content-MD5

ContentDigestOn|Off

ContentDigestOff

serverconfig,virtualhost,directory,.htaccessOptions(C)core

RFC1854RFC2068Content-MD5

MD5""("")

Content-MD5

Content-MD5:AuLb7Dp1rqtRtxz2m9kRpA==

()

Content-MD5ApacheSSICGI

Page 613: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DefaultType

MIMEDefaultTypeMIME-type

DefaultTypetext/plain

serverconfig,virtualhost,directory,.htaccessFileInfo(C)core

MIME

DefaultType

DefaultTypeimage/gif

gif.gif

ForceTypemimemime

Page 614: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Directory>

<Directorydirectory-path>...</Directory>

serverconfig,virtualhost(C)core

<Directory></Directory>"directory" Directory-pathUnixshell" ?"" *""/*/public_html>/home/user/public_html<Directory/home/*/public_html>

<Directory/usr/local/httpd/htdocs>

OptionsIndexesFollowSymLinks

</Directory>

directory-pathApache <Directory>

" ~"

<Directory~"^/www/(.+/)*[0-9]{3}">

/www/3

() <Directory>() .htaccess

<Directory/>

AllowOverrideNone

</Directory>

<Directory/home/>

AllowOverrideFileInfo

</Directory>

Page 615: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

/home/web/dir/doc.html

AllowOverrideNone( .htaccess)AllowOverrideFileInfo( /home)/home/.htaccess/home/web/.htaccess/home/web/dir/.htaccessFileInfo

<Directory~abc$>

#......

</Directory>

<Directory>.htaccess /home/abc/public_html/abc

Apache <Directory/>" AllowfromAll"ApacheURL

<Directory/>

OrderDeny,Allow

DenyfromAll

</Directory>

<Directory>httpd.conf <Directory> <Limit>

<LimitExcept>

<Directory><Location><Files>

Page 616: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<DirectoryMatch>

<DirectoryMatchregex>...</DirectoryMatch>

serverconfig,virtualhost(C)core

<DirectoryMatch></DirectoryMatch> <Directory>

<DirectoryMatch"^/www/(.+/)*[0-9]{3}">

/www/3

<Directory><Directory>

<Directory><Location><Files>

Page 617: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DocumentRoot

DocumentRootdirectory-path

DocumentRoot/usr/local/apache2/htdocs

serverconfig,virtualhost(C)core

httpd AliasURL DocumentRoot

DocumentRoot/usr/web

http://www.my.host.com/index.html

/usr/web/index.htmldirectory-path ServerRoot

DocumentRoot"/"

URL

Page 618: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

EnableMMAP

(memory-mapping)EnableMMAPOn|Off

EnableMMAPOn

serverconfig,virtualhost,directory,.htaccessFileInfo(C)core

httpd mod_includeApache

httpd

NFSDocumentRoot httpd

EnableMMAPOff

NFS

<Directory"/path-to-nfs-files">

EnableMMAPOff

</Directory>

Page 619: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

EnableSendfile

sendfileEnableSendfileOn|Off

EnableSendfileOn

serverconfig,virtualhost,directory,.htaccessFileInfo(C)coreApache2.0.44

httpdsendfile()Apachesendfile

sendfile

sendfilesendfileLinuxIPv6sendfileTCPbugLinuxItaniumsendfile2GBNFSDocumentRoot(NFSSMB)

sendfile

EnableSendfileOff

NFSSMB

<Directory"/path-to-nfs-files">

EnableSendfileOff

</Directory>

Page 620: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ErrorDocument

ErrorDocumenterror-codedocument

serverconfig,virtualhost,directory,.htaccessFileInfo(C)coreApache2.0

Apache

1.

2.

3. URL-path()

4. URL()

12-4 ErrorDocumentHTTPURLApache/

URL(/)URL( DocumentRoot)URL

ErrorDocument500http://foo.example.com/cgi-

bin/tester

ErrorDocument404/cgi-bin/bad_urls.pl

ErrorDocument401/subscription_info.html

ErrorDocument403"Sorrycan'tallowyouaccess

today"

" default"Apache" default"ApacheErrorDocument

ErrorDocument404/cgi-bin/bad_urls.pl

<Directory/web/docs>

Page 621: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ErrorDocument404default

</Directory>

ErrorDocumentURL(" http")ApacheURLweb"" ErrorDocument401"

MicrosoftInternetExplorer(MSIE)""""512byteMSIE Q294807

ErrorDocument""

2.0

Page 622: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ErrorLog

ErrorLogfile-path|syslog[:facility]

ErrorLoglogs/error_log(Unix)ErrorLog

logs/error.log(WindowsOS/2)

serverconfig,virtualhost(C)core

ErrorLog file-path(/) ServerRoot

ErrorLog/var/log/httpd/error_log

file-path(|)

ErrorLog"|/usr/local/bin/httpd_errors"

" syslog"syslogd(8) local7" syslog:facility"facilitysyslog(1)

ErrorLogsyslog:user

Unix(/)(\)

Page 623: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LogLevel

Apache

Page 624: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FileETag

ETagFileETagcomponent...

FileETagINodeMTimeSize

serverconfig,virtualhost,directory,.htaccessFileInfo(C)core

FileETagETag()( ETag)Apache1.3.22 ETaginode()FileETag()

INode(inode)

MTime

Size

All

FileETagINodeMTimeSize

NoneETag

INode,MTime,Size" +"" -"

" FileETagINodeMTimeSize"" FileETag-INode"()" FileETagMTimeSize"

Page 625: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Files>

<Filesfilename>...</Files>

serverconfig,virtualhost,directory,.htaccessAll(C)core

<Files> <Directory><Location> </Files>()<Files> <Directory>.htaccess <Location>

<Files><Directory>

filename" ?"" *"" ~"

<Files~"\.(gif|jpe?g|png)$">

Apache1.3 <FilesMatch>

<Directory><Location> <Files>.htaccess

<Directory><Location><Files>

Page 626: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<FilesMatch>

<FilesMatchregex>...</FilesMatch>

serverconfig,virtualhost,directory,.htaccessAll(C)core

<FilesMatch><Files>

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

internet

<Directory><Location><Files>

Page 627: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ForceType

MIMEForceTypeMIME-type|None

directory,.htaccessFileInfo(C)coreApache2.0

.htaccess<Directory><Location><Files> MIME-typeContent-TypeGIF"

ForceTypeimage/gif

DefaultTypemime

" None" ForceType

#image/gif:

<Location/images>

ForceTypeimage/gif

</Location>

#mime:

<Location/images/mixed>

ForceTypeNone

</Location>

Page 628: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HostnameLookups

IPDNSHostnameLookupsOn|Off|Double

HostnameLookupsOff

serverconfig,virtualhost,directory(C)core

DNS( REMOTE_HOSTCGI/SSI) DoubleDNSip("tcpwrappers" PARANOID)

mod_authz_host" HostnameLookupsDouble"" HostnameLookupsOn"CGI REMOTE_HOST

Off OffDNS binlogresolveIP

Page 629: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<IfDefine>

<IfDefine[!]parameter-name>...</IfDefine>

serverconfig,virtualhost,directory,.htaccessAll(C)core

<IfDefinetest>...</IfDefine> <IfDefine>test test

<IfDefine>test

parameter-name!parameter-name

parameter-name parameter-name

parameter-name httpd -Dparameter

<IfDefine>

httpd-DReverseProxy...

#httpd.conf

<IfDefineReverseProxy>

LoadModulerewrite_module

modules/mod_rewrite.so

LoadModuleproxy_modulemodules/libproxy.so

</IfDefine>

Page 630: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<IfModule>

<IfModule[!]module-file|module-identifier>...

</IfModule>

serverconfig,virtualhost,directory,.htaccessAll(C)coremodule-identifierApache2.1

<IfModuletest>...</IfModule> <IfModule>test test

<IfModule>test

module!module

module LoadModule module

module rewrite_module mod_rewrite.c

STANDARD20_MODULE_STUFF

<IfModule>

<IfModule>

Page 631: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Include

Includefile-path|directory-path

serverconfig,virtualhost,directory(C)coreApache2.0.41

Shell(fnmatch()) IncludeApache httpd

()

Include/usr/local/apache2/conf/ssl.conf

Include/usr/local/apache2/conf/vhosts/*.conf

ServerRoot

Includeconf/ssl.conf

Includeconf/vhosts/*.conf

Apache 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

Page 632: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

apachectl

Page 633: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

KeepAlive

HTTPKeepAliveOn|Off

KeepAliveOn

serverconfig,virtualhost(C)core

Keep-AliveHTTP/1.0HTTP/1.1HTTPTCPHTML50%Apache1.2 KeepAliveOn

HTTP/1.0HTTP/1.0CGISSIHTTP/1.0HTTP/1.1

MaxKeepAliveRequests

Page 634: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

KeepAliveTimeout

KeepAliveTimeoutseconds

KeepAliveTimeout5

serverconfig,virtualhost(C)core

Apache Timeout

KeepAliveTimeout

Page 635: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Limit>

HTTP<Limitmethod[method]...>...</Limit>

serverconfig,virtualhost,directory,.htaccessAll(C)core

<Limit>

<Limit>HTTP <Limit>POST,PUT,DELETE

<LimitPOSTPUTDELETE>

Requirevalid-user

</Limit>

GET,POST,PUT,DELETE,CONNECT,OPTIONS,PATCH,PROPFIND,PROPPATCH,MKCOL,COPY,MOVE,LOCK,UNLOCKGETHEAD TRACE

<LimitExcept> <Limit> <LimitExcept>HTTP

Page 636: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<LimitExcept>

HTTP<LimitExceptmethod[method]...>...

</LimitExcept>

serverconfig,virtualhost,directory,.htaccessAll(C)core

<LimitExcept></LimitExcept> HTTP <Limit>

<LimitExceptPOSTGET>

Requirevalid-user

</LimitExcept>

Page 637: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LimitInternalRecursion

LimitInternalRecursionnumber[number]

LimitInternalRecursion10

serverconfig,virtualhost(C)coreApache2.0.47

ActionCGIApacheURI mod_dirDirectoryIndex

LimitInternalRecursion

number() number number

LimitInternalRecursion5

Page 638: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LimitRequestBody

HTTPLimitRequestBodybytes

LimitRequestBody0

serverconfig,virtualhost,directory,.htaccessAll(C)core

bytes0()2147483647(2GB)

LimitRequestBody()HTTPCGI PUT

100K

LimitRequestBody102400

Page 639: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LimitRequestFields

HTTPLimitRequestFieldsnumber

LimitRequestFields100

serverconfig(C)core

Number0()32767 DEFAULT_LIMIT_REQUEST_FIELDS(100)

LimitRequestFieldsHTTP20HTTP

LimitRequestFields50

Page 640: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LimitRequestFieldSize

LimitRequestFieldsizebytes

LimitRequestFieldsize8190

serverconfig(C)core

bytesHTTP

LimitRequestFieldSizeHTTPSPNEGO12392

LimitRequestFieldSize4094

Page 641: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LimitRequestLine

HTTPLimitRequestLinebytes

LimitRequestLine8190

serverconfig(C)core

bytesHTTP

LimitRequestLineHTTPHTTPURILimitRequestLineURI GET

LimitRequestLine4094

Page 642: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LimitXMLRequestBody

XMLLimitXMLRequestBodybytes

LimitXMLRequestBody1000000

serverconfig,virtualhost,directory,.htaccessAll(C)core

XML" 0"

LimitXMLRequestBody0

Page 643: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Location>

URL<LocationURL-path|URL>...</Location>

serverconfig,virtualhost(C)core

<Location>URL <Directory> </Location>

<Location><Directory>,.htaccess,<Files>

<Location> <Location>URL

<Location>

<Location> <Directory><Files> <Location/>URL

()URL" /path/"URLURL" scheme://servername/path"

URL" ?"" *"

" ~"

<Location~"/(extra|special)/data">

" /extra/data"" /special/data"URLApache1.3<LocationMatch> <Location>

<Location>SetHandler foo.com

<Location/status>

SetHandlerserver-status

OrderDeny,Allow

Page 644: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Denyfromall

Allowfrom.foo.com

</Location>

"/"()

URL(" /home///foo"" /home/foo")URL<LocationMatch><Location> <LocationMatch

^/abc>" /abc"" //abc" <Location> <Location>

<Location/abc/def>" /abc//def"

<Directory><Location><Files>

Page 645: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<LocationMatch>

URL<LocationMatchregex>...</LocationMatch>

serverconfig,virtualhost(C)core

<LocationMatch><Location>URL

<LocationMatch"/(extra|special)/data">

" /extra/data"" /special/data"URL

<Directory><Location><Files>

Page 646: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LogLevel

LogLevellevel

LogLevelwarn

serverconfig,virtualhost(C)core

LogLevel( ErrorLog) level

Levelemerg (

)"Childcannotopenlockfile.Exiting"

alert "getpwuid:couldn'tdetermineusernamefromuid"crit "socket:Failedtogetasocket,exitingchild"error "Prematureendofscriptheaders"warn "childprocess1234didnotexit,sendinganother

SIGHUP"notice "httpd:caughtSIGBUS,attemptingtodumpcorein..."info "Serverseemsbusy,(youmayneedtoincrease

StartServers,orMin/MaxSpareServers)..."debug "Openingconfigfile..."

LogLevelinfonoticewarn

crit

LogLevelnotice

Page 647: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

notice syslog

Page 648: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MaxKeepAliveRequests

MaxKeepAliveRequestsnumber

MaxKeepAliveRequests100

serverconfig,virtualhost(C)core

MaxKeepAliveRequestsKeepAlive" 0"

MaxKeepAliveRequests500

Page 649: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

NameVirtualHost

IP()NameVirtualHostaddr[:port]

serverconfig(C)core

NameVirtualHost

addrIP

NameVirtualHost111.22.33.44

NameVirtualHostIPIPIP

""" _default_" NameVirtualHostIP(NameVirtualHostVirtualHost)

NameVirtualHost111.22.33.44:8080

IPv6

NameVirtualHost

[2001:db8::a00:20ff:fea7:ccea]:8080

" *"

NameVirtualHost*

Page 650: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<VirtualHost>

<VirtualHost>NameVirtualHost

NameVirtualHost1.2.3.4

<VirtualHost1.2.3.4>

#...

</VirtualHost>

Page 651: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Options

Options[+|-]option[[+|-]option]...

OptionsAll

serverconfig,virtualhost,directory,.htaccessOptions(C)core

Options

optionNone

All

MultiViews

ExecCGI

mod_cgiCGI

FollowSymLinks

<Directory>

<Location>

Includes

mod_include

IncludesNOEXEC

" #execcmd"" #execcgi" ScriptAlias" #include

virtual"CGI

Indexes

URL DirectoryIndex( index.html)mod_autoindex

Page 652: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MultiViews

mod_negotiation""(MultiViews)

SymLinksIfOwnerMatch

uid

<Location>

Options()( ) Options" +"" -"" +"" -"

" +"" -"

<Directory/web/docs>

OptionsIndexesFollowSymLinks

</Directory>

<Directory/web/docs/spec>

OptionsIncludes

</Directory>

Includes/web/docs/spec Options" +"" -"

<Directory/web/docs>

OptionsIndexesFollowSymLinks

</Directory>

<Directory/web/docs/spec>

Options+Includes-Indexes

</Directory>

FollowSymLinksIncludes/web/docs/spec

Page 653: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-IncludesNOEXEC -Includes

All

Page 654: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Require

Requireentity-name[entity-name]...

directory,.htaccessAuthConfig(C)core

Requireuseruserid[userid]...

Requiregroupgroup-name[group-name]...

Requirevalid-user

Require mod_authz_user,mod_authz_groupfile,mod_authnz_ldap,mod_authz_dbm,mod_authz_owner

RequireAuthNameAuthType AuthUserFileAuthGroupFile

()

AuthTypeBasic

AuthName"RestrictedResource"

AuthUserFile/web/users

AuthGroupFile/web/groups

Requiregroupadmin

Require<Limit>

RequireAllowDeny Satisfy

Page 655: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Satisfy mod_authz_host

<Directory/path/to/protected/>

Requireuserdavid

</Directory>

<Directory/path/to/protected/unprotected>

#

SatisfyAny

Allowfromall

</Directory>

Satisfy

mod_authz_host

Page 656: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RLimitCPU

ApacheCPURLimitCPUseconds|max[seconds|max]

serverconfig,virtualhost,directory,.htaccessAll(C)core

" max" root

ApacheApacheCGISSIApache

CPU

RLimitMEM

RLimitNPROC

Page 657: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RLimitMEM

ApacheRLimitMEMbytes|max[bytes|max]

serverconfig,virtualhost,directory,.htaccessAll(C)core

" max" root

ApacheApacheCGISSIApache

RLimitCPU

RLimitNPROC

Page 658: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RLimitNPROC

ApacheRLimitNPROCnumber|max[number|max]

serverconfig,virtualhost,directory,.htaccessAll(C)core

" max" root

ApacheApacheCGISSIApache

CGIwebuid error_log" cannotfork"

RLimitMEM

RLimitCPU

Page 659: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Satisfy

SatisfyAny|All

SatisfyAll

directory,.htaccessAuthConfig(C)core2.0.51<Limit><LimitExcept>

AllowRequire All Any/ ( All) Any

web

Requirevalid-user

Allowfrom192.168.1

SatisfyAny

2.0.51 Satisfy<Limit><LimitExcept>

Allow

Require

Page 660: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ScriptInterpreterSource

CGIScriptInterpreterSourceRegistry|Registry-

Strict|Script

ScriptInterpreterSourceScript

serverconfig,virtualhost,directory,.htaccessFileInfo(C)coreWin32 Registry-StrictApache2.0

ApacheCGI Script" #!"Win32

#!C:/Perl/bin/perl.exe

perlPATH

#!perl

ScriptInterpreterSourceRegistry( .pl)WindowsHKEY_CLASSES_ROOT Shell\ExecCGI\Command

Shell\Open\Command()Apache Script

ScriptInterpreterSourceRegistryScriptAliasApache RegistryWindows .htmIE .htmIE

Registry-StrictRegistry Shell\ExecCGI\Command

ExecCGI

Page 661: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerAdmin

ServerAdminemail-address|URL

serverconfig,virtualhost(C)core

ServerAdmin httpdURLemail-addressmailto:EmailCGIURL

[email protected]

Page 662: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerAlias

ServerAliashostname[hostname]...

virtualhost(C)core

ServerAlias

<VirtualHost*>

ServerNameserver.domain.com

ServerAliasserverserver2.domain.comserver2

#...

</VirtualHost>

Apache

Page 663: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerName

ServerNamefully-qualified-domain-name[:port]

serverconfig,virtualhost(C)core2.01.3 Port

ServerNameURLweb simple.example.comDNSwww.example.comweb

ServerNamewww.example.com:80

ServerNameIP ServerName ServerName

<VirtualHost>ServerName" Host:"

UseCanonicalNameUseCanonicalPhysicalPortURL(mod_dir)

DNSApacheApacheUseCanonicalName

UseCanonicalPhysicalPort

NameVirtualHost

ServerAlias

Page 664: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerPath

URLServerPathURL-path

virtualhost(C)core

ServerPath(legacy)URL

Apache

Page 665: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerRoot

ServerRootdirectory-path

ServerRoot/usr/local/apache

serverconfig(C)core

ServerRoot conf/logs/( IncludeLoadModule)

ServerRoot/home/httpd

httpd -dServerRoot

Page 666: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerSignature

ServerSignatureOn|Off|EMail

ServerSignatureOff

serverconfig,virtualhost,directory,.htaccessAll(C)core

ServerSignature( mod_proxyftp mod_info)

Off(Apache1.2) OnServerName EMailServerAdmin"mailto:"

2.0.44 ServerTokens

ServerTokens

Page 667: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerTokens

" Server:"ServerTokens

Major|Minor|Min[imal]|Prod[uctOnly]|OS|Full

ServerTokensFull

serverconfig(C)core

" Server:"

ServerTokensProd[uctOnly]

() Server:Apache

ServerTokensMajor

() Server:Apache/2

ServerTokensMinor

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

Page 668: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 669: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SetHandler

SetHandlerhandler-name|None

serverconfig,virtualhost,directory,.htaccessFileInfo(C)coreApache2.0

.htaccess<Directory><Location> handler-name.htaccess

SetHandlerimap-file

http://servername/status httpd.conf

<Location/status>

SetHandlerserver-status

</Location>

NoneSetHandler

AddHandler

Page 670: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SetInputFilter

POSTSetInputFilterfilter[;filter...]

serverconfig,virtualhost,directory,.htaccessFileInfo(C)core

SetInputFilterPOST( AddInputFilter)

(;)

Page 671: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SetOutputFilter

SetOutputFilterfilter[;filter...]

serverconfig,virtualhost,directory,.htaccessFileInfo(C)core

SetOutputFilter( AddOutputFilter)

/www/data/SSI

<Directory/www/data/>

SetOutputFilterINCLUDES

</Directory>

(;)

Page 672: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TimeOut

TimeOutseconds

TimeOut300

serverconfig(C)core

TimeOutApache

1. GET

2. POSTPUTTCP

3. TCPACK

1.21200300

Page 673: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TraceEnable

TRACE

TraceEnable[on|off|extended]

TraceEnableon

serverconfig(C)coreApache1.3.34,2.0.55

mod_proxyTRACE( TraceEnableon)RFC2616TRACETraceEnableoffmod_proxy" 405"()

" TraceEnableextended"()64k( Transfer-

Encoding:chunkedHTTP8k)64k

Page 674: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UseCanonicalName

UseCanonicalNameOn|Off|DNS

UseCanonicalNameOff

serverconfig,virtualhost,directory(C)core

Apache URL(URL) UseCanonicalNameOnServerNameURL SERVER_NAMECGISERVER_PORT

UseCanonicalNameOff()ApacheURL CGISERVER_NAMESERVER_PORT

www http://www/splatURL Apachehttp://www.domain.com/splat/ www

www.domain.com( FAQ) UseCanonicalName OffApachehttp://www/splat/

UseCanonicalNameDNSIP" Host:"ApacheIPDNSURL

CGISERVER_NAMECGI SERVER_NAMEURL

UseCanonicalPhysicalPort

ServerName

Listen

Page 675: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UseCanonicalPhysicalPort

UseCanonicalPhysicalPortOn|Off

UseCanonicalPhysicalPortOff

serverconfig,virtualhost,directory(C)coreApache2.2.0

Apache URL(URL) UseCanonicalPhysicalPortOnApache UseCanonicalName(physicalport)UseCanonicalPhysicalPortOffApache

UseCanonicalNameOn

Servername

UseCanonicalNameOff|DNS

"Host:"

Servername

UseCanonicalPhysicalPortOff

Page 676: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UseCanonicalName

ServerName

Listen

Page 677: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<VirtualHost>

IP<VirtualHostaddr[:port][addr[:port]]...>...

</VirtualHost>

serverconfig(C)core

<VirtualHost></VirtualHost> <VirtualHost>

Addr

IPIP" *"" NameVirtualHost*"IP" _default_"IPIP

<VirtualHost10.1.2.3>

[email protected]

DocumentRoot/www/docs/host.foo.com

ServerNamehost.foo.com

ErrorLoglogs/host.foo.com-error_log

TransferLoglogs/host.foo.com-access_log

</VirtualHost>

IPv6IPv6

<VirtualHost[2001:db8::a00:20ff:fea7:ccea]>

[email protected]

DocumentRoot/www/docs/host.example.com

ServerNamehost.example.com

ErrorLoglogs/host.example.com-error_log

TransferLoglogs/host.example.com-access_log

</VirtualHost>

Page 678: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

IPIPIP( ifconfigalias)

<VirtualHost>Apache ListenApache

IP" _default_"IP" _default_"IP""()NameVirtualHostIP""" _default_"

" :port" Listen" :*"(" _default_")

ApacheDNSApacheApache<Directory><Location><Files>

Page 679: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006122|

Page 680: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheMPM

(MPM)MPM

Page 681: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AcceptMutex

Apache()(socket)AcceptMutexDefault|method

AcceptMutexDefault

serverconfigMPMprefork,worker

AcceptMutex()2.0

Default

flock

flock(2)( LockFile)

fcntl

fcntl(2)( LockFile)

posixsem

(2.0)POSIXsegfault

pthread

(1.3)POSIXPOSIXSolaris2.5

sysvsem

(1.3)SysVSysVApache( ipcs()manpage)APIuidCGI(CGI

LogLeveldebugAcceptMutexErrorLog

pthread AcceptCntlSolaris(Apache)

pthread_mutexattr_setrobust_np() pthread

Page 682: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CoreDumpDirectory

ApacheCoreDumpDirectorydirectory

serverconfigMPMbeos,mpm_winnt,prefork,worker

Apache ServerRoot

Linux

ApacherootLinux ApacheApache2.0.46CoreDumpDirectoryLinux2.4

Page 683: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

EnableExceptionHook

EnableExceptionHookOn|Off

EnableExceptionHookOff

serverconfigMPMprefork,workerApache2.0.49

--enable-exception-hook(hook)

(mod_whatkilledusmod_backtrace)JeffTrawickEnableExceptionHooksite

Page 684: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

GracefulShutdownTimeout

GracefulShutDownTimeoutseconds

GracefulShutDownTimeout0

serverconfigMPMprefork,worker,eventApache2.2

GracefulShutdownTimeout""

"0"

Page 685: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Group

ApacheGroupunix-group

Group#-1

serverconfigMPMbeos,mpmt_os2,prefork,workerApache2.0

GroupApacheApache root Unix-group

"#"(GID)

Groupwww-group

Apache nobody

Group( User)root

<VirtualHost> suexecSuexecUserGroup

Groupbeosmpmt_os2MPM

Page 686: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Listen

IPListen[IP-address:]portnumber[protocol]

serverconfigMPMbeos,mpm_netware,mpm_winnt,mpmt_os2,prefork,worker,eventApache2.0 protocol2.1.5

ListenApacheIPApacheIP 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

protocol443 https http AcceptFilter

protocol8443 https

Page 687: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Listen192.170.2.1:8443https

Listen" Addressalreadyinuse"

DNS

Page 688: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ListenBackLog

(pendingconnection)ListenBacklogbacklog

ListenBacklog511

serverconfigMPMbeos,mpm_netware,mpm_winnt,mpmt_os2,prefork,worker

(pendingconnection)TCPSYN listen(2)

()

Page 689: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LockFile

LockFilefilename

LockFilelogs/accept.lock

serverconfigMPMprefork,worker

LockFileAcceptMutexfcntlflockApache logsNFSPID

( /var/tmp)

AcceptMutex

Page 690: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MaxClients

MaxClientsnumber

serverconfigMPMbeos,prefork,worker

MaxClients MaxClients ListenBacklog

MPM( prefork) MaxClients 256 ServerLimit

MPM( beosworker) MaxClients beos50MPM16(ServerLimit)25(ThreadsPerChild) MaxClients16ServerLimit

Page 691: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MaxMemFree

free()(KB)MaxMemFreeKBytes

MaxMemFree0

serverconfigMPMbeos,mpm_netware,prefork,worker,mpm_winnt

MaxMemFreefree()(KB)"0"

Page 692: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MaxRequestsPerChild

MaxRequestsPerChildnumber

MaxRequestsPerChild10000

serverconfigMPMmpm_netware,mpm_winnt,mpmt_os2,prefork,worker

MaxRequestsPerChild MaxRequestsPerChild

MaxRequestsPerChild" 0"

mpm_netwarempm_winnt" 0"

MaxRequestsPerChild

()

KeepAlive

Page 693: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MaxSpareThreads

MaxSpareThreadsnumber

serverconfigMPMbeos,mpm_netware,mpmt_os2,worker

MPM

worker" 250"MPM

mpm_netware" 100"MPMMPM

beosmpmt_os2mpm_netware beos" 50" mpmt_os2" 10"

MaxSpareThreadsApache

mpm_netwareMinSpareThreads

workerMinSpareThreadsThreadsPerChild

MinSpareThreads

StartServers

Page 694: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MinSpareThreads

MinSpareThreadsnumber

serverconfigMPMbeos,mpm_netware,mpmt_os2,worker

MPM

worker" 75"MPM

mpm_netware" 10"MPMMPM

beosmpmt_os2mpm_netware beos" 1" mpmt_os2" 5"

MaxSpareThreads

StartServers

Page 695: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

PidFile

()PIDPidFilefilename

PidFilelogs/httpd.pid

serverconfigMPMbeos,mpm_winnt,mpmt_os2,prefork,worker

PidFile()PID ServerRoot

PidFile/var/run/apache.pid

ErrorLogTransferLog"SIGHUP"(kill-1) PidFile

PID

PidFile

Apache2 apachectl

Page 696: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ReceiveBufferSize

TCP()ReceiveBufferSizebytes

ReceiveBufferSize0

serverconfigMPMbeos,mpm_netware,mpm_winnt,mpmt_os2,prefork,worker

TCP()(100ms)

" 0"

Page 697: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ScoreBoardFile

(coordinationdata)ScoreBoardFilefile-path

ScoreBoardFilelogs/apache_status

serverconfigMPMbeos,mpm_winnt,prefork,worker

Apache(scoreboard)Apache(scoreboard)Apache

ScoreBoardFile/var/run/apache_status

(scoreboard)

ScoreBoardFileRAMdisk

Apache

Page 698: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SendBufferSize

TCP()SendBufferSizebytes

SendBufferSize0

serverconfigMPMbeos,mpm_netware,mpm_winnt,mpmt_os2,prefork,worker

TCP()(100ms)

" 0"

Page 699: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerLimit

ServerLimitnumber

serverconfigMPMprefork,worker

preforkMPM MaxClients workerMPM ThreadLimit

MaxClients MaxClients

ServerLimit ServerLimitMaxClientsApache

preforkMPM MaxClients256 MaxClients

workerMPM MaxClientsThreadsPerChild16 MaxClients

ThreadsPerChild

Apache" ServerLimit20000"( preforkMPM" ServerLimit200000")

Apache

Page 700: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

StartServers

StartServersnumber

serverconfigMPMmpmt_os2,prefork,worker

StartServers

MPM worker" 3" prefork" 5" mpmt_os2" 2"

Page 701: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

StartThreads

StartThreadsnumber

serverconfigMPMbeos,mpm_netware

mpm_netware" 50"

beos" 10"

Page 702: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ThreadLimit

ThreadLimitnumber

serverconfigMPMmpm_winnt,worker2.0.41mpm_winnt

ThreadsPerChild ThreadsPerChild

ThreadLimitThreadsPerChild ThreadLimit

ThreadsPerChildApache ThreadsPerChild

mpm_winntThreadLimit1920MPM64

Apache" ThreadLimit20000"( mpm_winnt" ThreadLimit

15000")

Page 703: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ThreadsPerChild

ThreadsPerChildnumber

serverconfigMPMmpm_winnt,worker

mpm_winntMPM workerMPM

mpm_winntThreadsPerChild64MPM25

Page 704: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ThreadStackSize

()ThreadStackSizesize

NetWare65536

serverconfigMPMmpm_netware,mpm_winnt,workerApache2.1

ThreadStackSize()()

(HP-UX)Apache ThreadStackSize

ThreadStackSize ThreadStackSize

Page 705: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

User

Userunix-userid

User#-1

serverconfigMPMprefork,worker2.0

User root root root root Unix-userid

"#"

Apache nobody

User( Group)root

<VirtualHost> suexecSuexecUserGroup

Userbeosmpmt_os2MPM

Page 706: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 707: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheMPMbeos

ThisMulti-ProcessingModuleisoptimizedforBeOS.MPMmpm_beos_modulebeos.c

ThisMulti-ProcessingModule(MPM)isthedefaultforBeOS.Itusesasinglecontrolprocesswhichcreatesthreadstohandlerequests.

Page 708: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

MaxRequestsPerThread

LimitonthenumberofrequeststhatanindividualthreadwillhandleduringitslifeMaxRequestsPerThreadnumber

MaxRequestsPerThread0

serverconfigMPMbeos

MaxRequestsPerThreaddirectivesetsthelimitonthenumberofrequeststhatanindividualserverthreadwillhandle.AfterMaxRequestsPerThreadrequests,thethreadwilldie.IfMaxRequestsPerThreadis0,thenthethreadwillneverexpire.

SettingMaxRequestsPerThreadtoanon-zerolimithastwobeneficialeffects:

itlimitstheamountofmemorythatathreadcanconsumeby(accidental)memoryleakage;bygivingthreadsafinitelifetime,ithelpsreducethenumberofthreadswhentheserverloadreduces.

ForKeepAliverequests,onlythefirstrequestiscountedtowardsthislimit.Ineffect,itchangesthebehaviortolimitthenumberofconnectionsperthread.

Page 709: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 710: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheMPMevent

AnexperimentalvariantofthestandardworkerMPMMPMmpm_event_moduleevent.c

ThisMPMisexperimental,soitmayormaynotworkasexpected.

TousetheeventMPM,add--with-mpm=eventtotheconfigurescript'sargumentswhenbuildingthehttpd.

ThisMPMdependsonAPR'satomiccompare-and-swapoperationsforthreadsynchronization.Ifyouarecompilingforanx86targetandyoudon'tneedtosupport386s,oryouarecompilingforaSPARCandyoudon'tneedtorunonpre-UltraSPARCchips,add--enable-nonportable-atomics=yestotheconfigurescript'sarguments.ThiswillcauseAPRtoimplementatomicoperationsusingefficientopcodesnotavailableinolderCPUs.

Page 711: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 712: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheMPMnetware

Multi-ProcessingModuleimplementinganexclusivelythreadedwebserveroptimizedforNovellNetWareMPMmpm_netware_modulempm_netware.c

ThisMulti-ProcessingModule(MPM)implementsanexclusivelythreadedwebserverthathasbeenoptimizedforNovellNetWare.

Themainthreadisresponsibleforlaunchingchildworkerthreadswhichlistenforconnectionsandservethemwhentheyarrive.Apachealwaystriestomaintainseveralspareoridleworkerthreads,whichstandreadytoserveincomingrequests.Inthisway,clientsdonotneedtowaitforanewchildthreadstobespawnedbeforetheirrequestscanbeserved.

StartThreads,MinSpareThreads,MaxSpareThreads,andMaxThreadsregulatehowthemainthreadcreatesworkerthreadstoserverequests.Ingeneral,Apacheisveryself-regulating,somostsitesdonotneedtoadjustthesedirectivesfromtheirdefaultvalues.SiteswithlimitedmemorymayneedtodecreaseMaxThreadstokeeptheserverfromthrashing(spawningandterminatingidlethreads).Moreinformationabouttuningprocesscreationisprovidedintheperformancehintsdocumentation.

MaxRequestsPerChildcontrolshowfrequentlytheserverrecyclesprocessesbykillingoldonesandlaunchingnewones.OntheNetWareOSitishighlyrecommendedthatthisdirectiveremainsetto0.Thisallowsworkerthreadstocontinueservicing

Page 713: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

requestsindefinitely.

Page 714: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

MaxThreads

SetthemaximumnumberofworkerthreadsMaxThreadsnumber

MaxThreads2048

serverconfigMPMmpm_netware

MaxThreadsdirectivesetsthedesiredmaximumnumberworkerthreadsallowable.Thedefaultvalueisalsothecompiledinhardlimit.Thereforeitcanonlybelowered,forexample:

MaxThreads512

Page 715: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 716: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheMPMos2

Hybridmulti-process,multi-threadedMPMforOS/2MPMmpm_mpmt_os2_modulempmt_os2.c

TheServerconsistsofamain,parentprocessandasmall,staticnumberofchildprocesses.

Theparentprocess'sjobistomanagethechildprocesses.ThisinvolvesspawningchildrenasrequiredtoensuretherearealwaysStartServersprocessesacceptingconnections.

Eachchildprocessconsistsofaapoolofworkerthreadsandamainthreadthatacceptsconnectionsandpassesthemtotheworkersviaaworkqueue.Theworkerthreadpoolisdynamic,managedbyamaintenancethreadsothatthenumberofidlethreadsiskeptbetweenMinSpareThreadsMaxSpareThreads.

Page 717: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006121|

Page 718: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheMPMprefork

MPMMPMmpm_prefork_moduleprefork.c

(MPM)webApache1.3MPM

MPM MaxClients

Page 719: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

()Apache (spare)

StartServers,MinSpareServers,MaxSpareServers,MaxClientsApache256 MaxClients MaxClients

Unix root80Apache UserGroup

MaxRequestsPerChild

Page 720: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MaxSpareServers

MaxSpareServersnumber

MaxSpareServers10

serverconfigMPMprefork

MaxSpareServers MaxSpareServers

MinSpareServersApache" MinSpareServers+1"

MinSpareServers

StartServers

Page 721: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

MinSpareServers

MinSpareServersnumber

MinSpareServers5

serverconfigMPMprefork

MinSpareServers MinSpareServersApache

MaxSpareServers

StartServers

Page 722: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006121|

Page 723: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheMPMwinnt

WindowsNTMPMMPMmpm_winnt_modulempm_winnt.c

(MPM)WindowsNT

Page 724: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Win32DisableAcceptEx

accept()AcceptEx()Win32DisableAcceptEx

AcceptEx()

serverconfigMPMmpm_winntApache2.0.49

AcceptEx()WinSock2APIBSDaccept()APIWindowsAcceptEx()

[error](730038)Anoperationwasattemptedon

somethingthatisnotasocket.:winnt_accept:

AcceptExfailed.Attemptingtorecover.

AcceptEx()

Page 725: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006121|

Page 726: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheMPMworker

MPMmpm_worker_moduleworker.c

(MPM)MPMMPM

MPM ThreadsPerChild MaxClients

Page 727: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

() ThreadsPerChild

Apache(spare) StartServers MinSpareThreads

MaxSpareThreads MaxClients MaxClients

ThreadsPerChild

() ServerLimit MaxClientsThreadsPerChild

ThreadLimit ThreadsPerChild workerMPM

"" MaxClients

MaxRequestsPerChild"0"MaxSpareThreadsMaxClients

workerMPM

ServerLimit16

StartServers2

MaxClients150

MinSpareThreads25

MaxSpareThreads75

ThreadsPerChild25

Unix80 rootApache UserGroupApachesuexecCGI

MaxRequestsPerChild

Page 728: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006122|

Page 729: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_actions

CGI(B)actions_modulemod_actions.c

ActionMIMECGI ScriptCGICGI

Page 730: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Action

CGIActionaction-typecgi-script[virtual]

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_actionsvirtualApache2.1

action-typecgi-script cgi-scriptURL ScriptAliasAddHandler

CGI action-typeMIMEPATH_INFOPATH_TRANSLATEDURLREDIRECT_HANDLER

#MIME

Actionimage/gif/cgi-bin/images.cgi

#

AddHandlermy-file-type.xyz

Actionmy-file-type/cgi-bin/program.cgi

MIME" image/gif"CGI /cgi-bin/images.cgi

" .xyz"CGI /cgi-bin/program.cgi

virtual Action

<Location/news>

SetHandlernews-handler

Actionnews-handler/cgi-bin/news.cgivirtual

</Location>

Page 731: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddHandler

Page 732: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Script

CGIScriptmethodcgi-script

serverconfig,virtualhost,directory(B)mod_actions

methodcgi-script cgi-scriptURL ScriptAliasAddHandlerCGIPATH_INFOPATH_TRANSLATEDURL

ScriptPUT Scriptput

ScriptCGI GET("foo.html?hi")

#<ISINDEX>

ScriptGET/cgi-bin/search

#ACGIPUT

ScriptPUT/~bob/put.cgi

Page 733: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006123|

Page 734: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_alias

URL(B)alias_modulemod_alias.c

URL AliasScriptAliasURL DocumentRoot

ScriptAliasCGI

RedirectURL

mod_aliasURLURL mod_rewrite

Page 735: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(context) (context)( <VirtualHost>)

RedirectRedirectMatch

Alias/foo/bar/baz

Alias/foo/gaq

Page 736: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Alias

URLAliasURL-pathfile-path|directory-path

serverconfig,virtualhost(B)mod_alias

AliasDocumentRoot(%) url-pathURLdirectory-path

Alias/image/ftp/pub/image

"http://myserver/image/foo.gif""/ftp/pub/image/foo.gif""http://myserver/imagefoo.gif" AliasMatch

url-path"/""/"" Alias/icons/

/usr/local/apache/icons/"" /icons"

<Directory><Directory>( <Location>)

DocumentRootAlias

Alias/image/ftp/pub/image

<Directory/ftp/pub/image>

Orderallow,deny

Allowfromall

</Directory>

Page 737: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AliasMatch

URLAliasMatchregexfile-path|directory-path

serverconfig,virtualhost(B)mod_alias

Alias URL-path" /icons"

AliasMatch^/icons(.*)/usr/local/apache/icons$1

Page 738: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Redirect

URLRedirect[status]URL-pathURL

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_alias

URLURLURL

URL-path(%)"/"() URL(%)"/"()URL URLURL-path

URL-path URL

Redirect/servicehttp://foo2.example.com/service

"http://example.com/service/foo.txt""http://foo2.example.com/service/foo.txt""http://example.com/servicefoo.txt" RedirectMatch

AliasScriptAlias

status""(HTTPstatus302) statusHTTP

permanent(301)

temp(302)

seeother

Page 739: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

""(303)

gone""(410) URL

status300-399 URLApache(http_protocol.csend_error_response)

Redirectpermanent/onehttp://example.com/two

Redirect303/threehttp://example.com/other

Page 740: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RedirectMatch

URLRedirectMatch[status]regexURL

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_alias

Redirect regexURL-pathGIFJPEG

RedirectMatch(.*)\.gif$

http://www.anotherserver.com$1.jpg

Page 741: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RedirectPermanent

URLRedirectPermanentURL-pathURL

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_alias

(status301)" Redirectpermanent"

Page 742: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RedirectTemp

URLRedirectTempURL-pathURL

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_alias

(status302)" Redirecttemp"

Page 743: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ScriptAlias

URLCGIScriptAliasURL-pathfile-path|directory-path

serverconfig,virtualhost(B)mod_alias

ScriptAliasAliascgi-scriptCGI URL-path(%)URL

ScriptAlias/cgi-bin//web/cgi-bin/

http://myserver/cgi-bin/foo/web/cgi-bin/foo

Page 744: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ScriptAliasMatch

URLCGIScriptAliasMatchregexfile-path|directory-path

serverconfig,virtualhost(B)mod_alias

ScriptAlias regexURL-path /cgi-bin

ScriptAliasMatch^/cgi-bin(.*)

/usr/local/apache/cgi-bin$1

Page 745: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006123|

Page 746: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_asis

HTTP(B)asis_modulemod_asis.c

send-as-isApacheHTTP(headers)

HTTPcgi-scriptnphscript

MIME httpd/send-as-is

Page 747: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

send-as-is

AddHandlersend-as-isasis

" .asis"ApacheHTTP"Status:"3HTTP

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'sexceptionallywonderfulpagehasmoved

to

<a

href="http://xyz.abc.com/foo/bar.html">Joe's</a>

site.

</h1>

</body>

</html>

" Date:"" Server:" " Last-Modified:"

Page 748: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006123|

Page 749: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_auth_basic

(B)auth_basic_modulemod_auth_basic.cApache2.1

HTTP mod_auth_digestHTTP(mod_authn_file)( mod_authz_user)

Page 750: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthBasicAuthoritative

()AuthBasicAuthoritativeOn|Off

AuthBasicAuthoritativeOn

directory,.htaccessAuthConfig(B)mod_auth_basic

AuthBasicProvider AuthBasicAuthoritative

OffuserID userIDrule() (non-provider-based)()mod_auth_basicAuthBasicProvider

Page 751: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthBasicProvider

()(Provider)AuthBasicProviderprovider-name[provider-name]

...

AuthBasicProviderfile

directory,.htaccessAuthConfig(B)mod_auth_basic

AuthBasicProvider()(Provider) filemod_authn_file(DSO)

<Location/secure>

AuthTypebasic

AuthBasicProviderdbm

AuthDBMTypeSDBM

AuthDBMUserFile/www/etc/dbmpasswd

Requirevalid-user

</Location>

(Provider) mod_authn_dbm,mod_authn_file,mod_authn_dbd,mod_authnz_ldap

Page 752: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006123|

Page 753: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_auth_digest

MD5()(X)auth_digest_modulemod_auth_digest.c

HTTP

Page 754: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MD5" AuthTypeDigest" AuthDigestProvider

" AuthTypeBasic" AuthBasicProviderAuthDigestDomainURI

htdigest()

<Location/private/>

AuthTypeDigest

AuthName"privatearea"

AuthDigestDomain/private/

http://mirror.my.dom/private2/

AuthDigestProviderfile

AuthUserFile/web/auth/.digest_pw

Requirevalid-user

</Location>

20049 Amaya,Konqueror,MSInternetExplorer6("MSInternetExplorer6 "),Mozilla,Netscape7,Opera,Safarilynx

Page 755: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MSInternetExplorer6

InternetExplorer6 GETRFC

POSTGET

2.0.51Apache AuthDigestEnableQueryStringHack

(workaround) AuthDigestEnableQueryStringHackApacheInternetExplorer6bugURI

MSIE6BrowserMatch"MSIE"

AuthDigestEnableQueryStringHack=On

BrowserMatch

Page 756: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDigestAlgorithm

AuthDigestAlgorithmMD5|MD5-sess

AuthDigestAlgorithmMD5

directory,.htaccessAuthConfig(X)mod_auth_digest

AuthDigestAlgorithm

MD5-sess

Page 757: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDigestDomain

URIAuthDigestDomainURI[URI]...

directory,.htaccessAuthConfig(X)mod_auth_digest

AuthDigestDomainURI(/)URIURI""URI/URIURI()URI

URI AuthDigestNcCheck"On"

URI

Page 758: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDigestNcCheck

Enablesordisablescheckingofthenonce-countsentbytheserverAuthDigestNcCheckOn|Off

AuthDigestNcCheckOff

serverconfig(X)mod_auth_digest

Page 759: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDigestNonceFormat

DetermineshowthenonceisgeneratedAuthDigestNonceFormatformat

directory,.htaccessAuthConfig(X)mod_auth_digest

Page 760: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDigestNonceLifetime

nonce()AuthDigestNonceLifetimeseconds

AuthDigestNonceLifetime300

directory,.htaccessAuthConfig(X)mod_auth_digest

AuthDigestNonceLifetimenonce()nonce()" stale=true"401() seconds"0"nonce()()30120(10)

Page 761: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDigestProvider

()(Provider)AuthDigestProviderprovider-name[provider-name]

...

AuthDigestProviderfile

directory,.htaccessAuthConfig(X)mod_auth_digest

AuthDigestProvider()(Provider) filemod_authn_file

(DSO)

(Provider) mod_authn_dbmmod_authn_file

Page 762: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDigestQop

AuthDigestQopnone|auth|auth-int[auth|auth-int]

AuthDigestQopauth

directory,.htaccessAuthConfig(X)mod_auth_digest

AuthDigestQop(quality-of-protection)auth(/) auth-int(MD5) noneRFC-2069() authauth-int none

auth-int

Page 763: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthDigestShmemSize

AuthDigestShmemSizesize

AuthDigestShmemSize1000

serverconfig(X)mod_auth_digest

AuthDigestShmemSize AuthDigestShmemSize

" 0"Apache

size" K"" M"KBMB

AuthDigestShmemSize1048576

AuthDigestShmemSize1024K

AuthDigestShmemSize1M

Page 764: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006123|

Page 765: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authn_alias

(E)authn_alias_modulemod_authn_alias.cApache2.1

AuthBasicProviderAuthDigestProvider

Page 766: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ldap()ldap()ldap

LoadModuleauthn_alias_module

modules/mod_authn_alias.so

<AuthnProviderAliasldapldap-alias1>

AuthLDAPBindDNcn=youruser,o=ctx

AuthLDAPBindPasswordyourpassword

AuthLDAPURLldap://ldap.host/o=ctx

</AuthnProviderAlias>

<AuthnProviderAliasldapldap-other-alias>

AuthLDAPBindDNcn=yourotheruser,o=dev

AuthLDAPBindPasswordyourotherpassword

AuthLDAPURLldap://other.ldap.host/o=dev?cn

</AuthnProviderAlias>

Alias/secure/webpages/secure

<Directory/webpages/secure>

Orderdeny,allow

Allowfromall

AuthBasicProviderldap-other-aliasldap-alias1

AuthTypeBasic

AuthNameLDAP_Protected_Place

AuthzLDAPAuthoritativeoff

requirevalid-user

</Directory>

Page 767: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

<AuthnProviderAlias>

<AuthnProviderAliasbaseProviderAlias>...

</AuthnProviderAlias>

serverconfig,virtualhost(E)mod_authn_alias

<AuthnProviderAlias></AuthnProviderAlias>

AuthBasicProviderAuthDigestProvider

Page 768: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 769: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authn_anon

(E)authn_anon_modulemod_authn_anon.cApache2.1

Thismoduleprovidesauthenticationfront-endssuchasmod_auth_basictoauthenticateuserssimilartoanonymous-ftpsites,i.e.havea'magic'userid'anonymous'andtheemailaddressasapassword.Theseemailaddressescanbelogged.

Combinedwithother(database)accesscontrolmethods,thisallowsforeffectiveusertrackingandcustomizationaccordingtoauserprofilewhilestillkeepingthesiteopenfor'unregistered'users.OneadvantageofusingAuth-basedusertrackingisthat,unlikemagic-cookiesandfunnyURLpre/postfixes,itiscompletelybrowserindependentanditallowsuserstoshareURLs.

Whenusingmod_auth_basic,thismoduleisinvokedviatheAuthBasicProviderdirectivewiththeanonvalue.

Page 770: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Example

Theexamplebelowiscombinedwith"normal"htpasswd-filebasedauthenticationandallowsusersinadditionallyas'guests'withthefollowingproperties:

ItinsiststhattheuserentersauserID.(Anonymous_NoUserID)Itinsiststhattheuserentersapassword.(Anonymous_MustGiveEmail)Thepasswordenteredmustbeavalidemailaddress,i.e.containatleastone'@'anda'.'.(Anonymous_VerifyEmail)TheuserIDmustbeoneofanonymousguestwwwtestwelcomeandcomparisonisnotcasesensitive.(Anonymous)AndtheEmailaddressesenteredinthepasswdfieldareloggedtotheerrorlogfile.(Anonymous_LogEmail)

<Directory/foo>

AuthName"Use'anonymous'&Emailaddressfor

guestentry"

AuthTypeBasic

AuthBasicProviderfileanon

AuthUserFile/path/to/your/.htpasswd

Anonymous_NoUserIDoff

Anonymous_MustGiveEmailon

Anonymous_VerifyEmailon

Anonymous_LogEmailon

Anonymousanonymousguestwwwtestwelcome

OrderDeny,Allow

Allowfromall

Requirevalid-user

</Directory>

Page 771: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 772: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Anonymous

SpecifiesuserIDsthatareallowedaccesswithoutpasswordverificationAnonymoususer[user]...

directory,.htaccessAuthConfig(E)mod_authn_anon

Alistofoneormore'magic'userIDswhichareallowedaccesswithoutpasswordverification.TheuserIDsarespaceseparated.Itispossibletousethe'and"quotestoallowaspaceinauserIDaswellasthe\escapecharacter.

Pleasenotethatthecomparisoniscase-IN-sensitive.It'sstronglyrecommendedthatthemagicusername'anonymous'isalwaysoneofthealloweduserIDs.

Anonymousanonymous"NotRegistered""Idon't

know"

ThiswouldallowtheusertoenterwithoutpasswordverificationbyusingtheuserIDs"anonymous","AnonyMous","NotRegistered"and"IDon'tKnow".

AsofApache2.1itispossibletospecifytheuserIDas"*".ThatallowsanysupplieduserIDtobeaccepted.

Page 773: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Anonymous_LogEmail

SetswhetherthepasswordenteredwillbeloggedintheerrorlogAnonymous_LogEmailOn|Off

Anonymous_LogEmailOn

directory,.htaccessAuthConfig(E)mod_authn_anon

WhensetOn,thedefault,the'password'entered(whichhopefullycontainsasensibleemailaddress)isloggedintheerrorlog.

Page 774: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Anonymous_MustGiveEmail

SpecifieswhetherblankpasswordsareallowedAnonymous_MustGiveEmailOn|Off

Anonymous_MustGiveEmailOn

directory,.htaccessAuthConfig(E)mod_authn_anon

Specifieswhethertheusermustspecifyanemailaddressasthepassword.Thisprohibitsblankpasswords.

Page 775: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Anonymous_NoUserID

SetswhethertheuserIDfieldmaybeemptyAnonymous_NoUserIDOn|Off

Anonymous_NoUserIDOff

directory,.htaccessAuthConfig(E)mod_authn_anon

WhensetOn,userscanleavetheuserID(andperhapsthepasswordfield)empty.ThiscanbeveryconvenientforMS-ExploreruserswhocanjusthitreturnorclickdirectlyontheOKbutton;whichseemsanaturalreaction.

Page 776: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Anonymous_VerifyEmail

SetswhethertocheckthepasswordfieldforacorrectlyformattedemailaddressAnonymous_VerifyEmailOn|Off

Anonymous_VerifyEmailOff

directory,.htaccessAuthConfig(E)mod_authn_anon

WhensetOnthe'password'enteredischeckedforatleastone'@'anda'.'toencourageuserstoentervalidemailaddresses(seetheaboveAnonymous_LogEmail).

Page 777: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 778: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authn_dbd

SQL(E)authn_dbd_modulemod_authn_dbd.cApache2.1

Thismoduleprovidesauthenticationfront-endssuchasmod_auth_digestmod_auth_basictoauthenticateusersbylookingupusersinSQLtables.Similarfunctionalityisprovidedby,forexample,mod_authn_file.

Thismodulereliesonmod_dbdtospecifythebackenddatabasedriverandconnectionparameters,andmanagethedatabaseconnections.

Whenusingmod_auth_basicmod_auth_digest,thismoduleisinvokedviatheAuthBasicProviderAuthDigestProviderwiththedbdvalue.

Page 779: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ConfigurationExample

ThissimpleexampleshowsuseofthismoduleinthecontextoftheAuthenticationandDBDframeworks.

#DatabaseManagement

#UsethePostgreSQLdriver

DBDriverpgsql

#Connectionstring:databasenameandlogincredentials

DBDParams"dbname=htpasswduser=apachepass=xxxxxx"

#ParametersforConnectionPoolManagement

DBDMin1

DBDKeep2

DBDMax10

DBDExptime60

#AuthenticationSection

<Directory/usr/www/myhost/private>

#mod_authconfigurationforauthn_dbd

AuthTypeBasic

AuthName"MyServer"

AuthBasicProviderdbd

#authzconfiguration

Requirevalid-user

#SQLquerytoverifyauser

#(note:DBDdriversrecognisebothstdio-like%sandnativesyntax)

AuthDBDUserPWQuery"selectpasswordfromauthnwhereusername=%s"

</Directory>

Page 780: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDBDUserPWQuery

SQLquerytolookupapasswordforauserAuthDBDUserPWQueryquery

directoryAuthConfig(E)mod_authn_dbd

AuthDBDUserPWQueryspecifiesanSQLquerytolookupapasswordforaspecifieduser.Thequerymusttakeasinglestring(typicallySQLvarchar)argument(username),andreturnasinglevalue(encryptedpassword).

AuthDBDUserPWQuery"SELECTpasswordFROMauthn

WHEREusername=%s"

Page 781: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthDBDUserRealmQuery

SQLquerytolookupapasswordhashforauserandrealm.AuthDBDUserRealmQueryquery

directoryAuthConfig(E)mod_authn_dbd

AuthDBDUserRealmPWQueryspecifiesanSQLquerytolookupapasswordforaspecifieduserandrealm.Thequerymusttaketwostring(typicallySQLvarchar)arguments(usernameandrealm),andreturnasinglevalue(encryptedpassword).

AuthDBDUserRealmPWQuery"SELECTpasswordFROM

authnWHEREusername=%sANDrealm=%s"

Page 782: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 783: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authn_dbm

DBM(E)authn_dbm_modulemod_authn_dbm.cApache2.1

Thismoduleprovidesauthenticationfront-endssuchasmod_auth_digestmod_auth_basictoauthenticateusersbylookingupusersindbmpasswordfiles.Similarfunctionalityisprovidedbymod_authn_file.

Whenusingmod_auth_basicmod_auth_digest,thismoduleisinvokedviatheAuthBasicProviderAuthDigestProviderwiththedbmvalue.

Page 784: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDBMType

SetsthetypeofdatabasefilethatisusedtostorepasswordsAuthDBMTypedefault|SDBM|GDBM|NDBM|DB

AuthDBMTypedefault

directory,.htaccessAuthConfig(E)mod_authn_dbm

Setsthetypeofdatabasefilethatisusedtostorethepasswords.Thedefaultdatabasetypeisdeterminedatcompiletime.Theavailabilityofothertypesofdatabasefilesalsodependsoncompile-timesettings.

Itiscrucialthatwhateverprogramyouusetocreateyourpasswordfilesisconfiguredtousethesametypeofdatabase.

Page 785: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDBMUserFile

SetsthenameofadatabasefilecontainingthelistofusersandpasswordsforauthenticationAuthDBMUserFilefile-path

directory,.htaccessAuthConfig(E)mod_authn_dbm

AuthDBMUserFiledirectivesetsthenameofaDBMfilecontainingthelistofusersandpasswordsforuserauthentication.File-pathistheabsolutepathtotheuserfile.

Theuserfileiskeyedontheusername.Thevalueforauseristheencryptedpassword,optionallyfollowedbyacolonandarbitrarydata.Thecolonandthedatafollowingitwillbeignoredbytheserver.

MakesurethattheAuthDBMUserFileisstoredoutsidethedocumenttreeoftheweb-server;donotputitinthedirectorythatitprotects.Otherwise,clientswillbeabletodownloadtheAuthDBMUserFile.

Importantcompatibilitynote:TheimplementationofdbmopenintheapachemodulesreadsthestringlengthofthehashedvaluesfromtheDBMdatastructures,ratherthanrelyinguponthestringbeingNULL-appended.Someapplications,suchastheNetscapewebserver,relyuponthestringbeingNULL-appended,soifyouarehavingtroubleusingDBMfilesinterchangeablybetweenapplicationsthismaybeapartoftheproblem.

AperlscriptcalleddbmmanageisincludedwithApache.ThisprogramcanbeusedtocreateandupdateDBMformatpasswordfilesforuse

Page 786: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

withthismodule.

Page 787: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006124|

Page 788: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authn_default

(B)authn_default_modulemod_authn_default.cApache2.1

(fallback)( mod_auth_basic)

Page 789: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthDefaultAuthoritative

AuthDefaultAuthoritativeOn|Off

AuthDefaultAuthoritativeOn

directory,.htaccessAuthConfig(B)mod_authn_default

AuthDefaultAuthoritative Off( modules.c)

mod_authn_default AuthDefaultAuthoritative

(On)

Page 790: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006124|

Page 791: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authn_file

(B)authn_file_modulemod_authn_file.cApache2.1

(mod_auth_digestmod_auth_basic) mod_authn_dbm

mod_auth_basicmod_auth_digest AuthBasicProvider

AuthDigestProviderfile

Page 792: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthUserFile

/AuthUserFilefile-path

directory,.htaccessAuthConfig(B)mod_authn_file

AuthUserFile/ File-path() ServerRoot

mod_authn_file

(" src/support") htpasswdHTTP

usernameFilename

htpasswd-cFilenameusername

Filenameusername2

htpasswdFilenameusername2

AuthDBMUserFile

HTTPhtpasswd htdigest

AuthUserFileWEB

Page 793: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 794: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authnz_ldap

LDAP(E)authnz_ldap_modulemod_authnz_ldap.cApache2.1

Thismoduleprovidesauthenticationfront-endssuchasmod_auth_basictoauthenticateusersthroughanldapdirectory.

mod_authnz_ldapsupportsthefollowingfeatures:

KnowntosupporttheOpenLDAPSDK(both1.xand2.x),NovellLDAPSDKandtheiPlanet(Netscape)SDK.ComplexauthorizationpoliciescanbeimplementedbyrepresentingthepolicywithLDAPfilters.UsesextensivecachingofLDAPoperationsviamod_ldap.SupportforLDAPoverSSL(requirestheNetscapeSDK)orTLS(requirestheOpenLDAP2.xSDKorNovellLDAPSDK).

Whenusingmod_auth_basic,thismoduleisinvokedviatheAuthBasicProviderdirectivewiththeldapvalue.

Page 795: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Contents

OperationTheAuthenticationPhaseTheAuthorizationPhase

TherequireDirectivesrequirevalid-userrequireldap-userrequireldap-grouprequireldap-dnrequireldap-attributerequireldap-filter

ExamplesUsingTLSUsingSSLUsingMicrosoftFrontPagewithmod_authnz_ldap

HowItWorksCaveats

Page 796: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Operation

Therearetwophasesingrantingaccesstoauser.Thefirstphaseisauthentication,inwhichthemod_authnz_ldapauthenticationproviderverifiesthattheuser'scredentialsarevalid.Thisisalsocalledthesearch/bindphase.Thesecondphaseisauthorization,inwhichmod_authnz_ldapdeterminesiftheauthenticateduserisallowedaccesstotheresourceinquestion.Thisisalsoknownasthecomparephase.

mod_authnz_ldapregistersbothanauthn_ldapauthenticationproviderandanauthz_ldapauthorizationhandler.Theauthn_ldapauthenticationprovidercanbeenabledthroughtheAuthBasicProviderdirectiveusingtheldapvalue.Theauthz_ldaphandlerextendstheRequiredirective'sauthorizationtypesbyaddingldap-user,ldap-dnldap-groupvalues.

TheAuthenticationPhaseDuringtheauthenticationphase,mod_authnz_ldapsearchesforanentryinthedirectorythatmatchestheusernamethattheHTTPclientpasses.Ifasingleuniquematchisfound,thenmod_authnz_ldapattemptstobindtothedirectoryserverusingtheDNoftheentryplusthepasswordprovidedbytheHTTPclient.Becauseitdoesasearch,thenabind,itisoftenreferredtoasthesearch/bindphase.Herearethestepstakenduringthesearch/bindphase.

1. GenerateasearchfilterbycombiningtheattributeandfilterprovidedintheAuthLDAPURLdirectivewiththeusernamepassedbytheHTTPclient.

2. Searchthedirectoryusingthegeneratedfilter.Ifthesearchdoesnotreturnexactlyoneentry,denyordeclineaccess.

3. FetchthedistinguishednameoftheentryretrievedfromthesearchandattempttobindtotheLDAPserverusingtheDNandthepasswordpassedbytheHTTPclient.Ifthebindis

Page 797: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

unsuccessful,denyordeclineaccess.

Thefollowingdirectivesareusedduringthesearch/bindphase

AuthLDAPURL SpecifiestheLDAPserver,thebaseDN,theattributetouseinthesearch,aswellastheextrasearchfiltertouse.

AuthLDAPBindDN AnoptionalDNtobindwithduringthesearchphase.

AuthLDAPBindPassword Anoptionalpasswordtobindwithduringthesearchphase.

TheAuthorizationPhaseDuringtheauthorizationphase,mod_authnz_ldapattemptstodetermineiftheuserisauthorizedtoaccesstheresource.Manyofthesechecksrequiremod_authnz_ldaptodoacompareoperationontheLDAPserver.Thisiswhythisphaseisoftenreferredtoasthecomparephase.mod_authnz_ldapacceptsthefollowingRequiredirectivestodetermineifthecredentialsareacceptable:

Grantaccessifthereisarequireldap-userdirective,andtheusernameinthedirectivematchestheusernamepassedbytheclient.Grantaccessifthereisarequireldap-dndirective,andtheDNinthedirectivematchestheDNfetchedfromtheLDAPdirectory.Grantaccessifthereisarequireldap-groupdirective,andtheDNfetchedfromtheLDAPdirectory(ortheusernamepassedbytheclient)occursintheLDAPgroup.Grantaccessifthereisarequireldap-attributedirective,andtheattributefetchedfromtheLDAPdirectorymatchesthegivenvalue.Grantaccessifthereisarequireldap-filterdirective,and

Page 798: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

thesearchfiltersuccessfullyfindsasingleuserobjectthatmatchesthednoftheauthenticateduser.otherwise,denyordeclineaccess

OtherRequirevaluesmayalsobeusedwhichmayrequireloadingadditionalauthorizationmodules.

Grantaccessifthereisarequirevalid-userdirective.(requiresmod_authz_user)Grantaccessifthereisarequiregroupdirective,andmod_authz_groupfilehasbeenloadedwiththeAuthGroupFiledirectiveset.others...

mod_authnz_ldapusesthefollowingdirectivesduringthecomparephase:

AuthLDAPURL TheattributespecifiedintheURLisusedincompareoperationsfortherequireldap-useroperation.

AuthLDAPCompareDNOnServer Determinesthebehavioroftherequireldap-dndirective.

AuthLDAPGroupAttribute Determinestheattributetouseforcomparisonsintherequireldap-groupdirective.

AuthLDAPGroupAttributeIsDN SpecifieswhethertousetheuserDNortheusernamewhendoingcomparisonsfortherequireldap-group

directive.

Page 799: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TherequireDirectives

Apache'sRequiredirectivesareusedduringtheauthorizationphasetoensurethatauserisallowedtoaccessaresource.mod_authnz_ldapextendstheauthorizationtypeswithldap-user,ldap-dn,ldap-group,ldap-attributeldap-filter.Otherauthorizationtypesmayalsobeusedbutmayrequirethatadditionalauthorizationmodulesbeloaded.

requirevalid-userIfthisdirectiveexists,mod_authnz_ldapgrantsaccesstoanyuserthathassuccessfullyauthenticatedduringthesearch/bindphase.Requiresthatmod_authz_userbeloadedandthattheAuthzLDAPAuthoritativedirectivebesettooff.

requireldap-userrequireldap-userdirectivespecifieswhatusernamescanaccesstheresource.Oncemod_authnz_ldaphasretrievedauniqueDNfromthedirectory,itdoesanLDAPcompareoperationusingtheusernamespecifiedintherequireldap-usertoseeifthatusernameispartofthejust-fetchedLDAPentry.Multipleuserscanbegrantedaccessbyputtingmultipleusernamesontheline,separatedwithspaces.Ifausernamehasaspaceinit,thenitmustbesurroundedwithdoublequotes.Multipleuserscanalsobegrantedaccessbyusingmultiplerequireldap-userdirectives,withoneuserperline.Forexample,withaAuthLDAPURLofldap://ldap/o=Airius?cn(i.e.,cnisusedforsearches),thefollowingrequiredirectivescouldbeusedtorestrictaccess:

requireldap-user"BarbaraJenson"

requireldap-user"FredUser"

requireldap-user"JoeManager"

Becauseofthewaythatmod_authnz_ldaphandlesthisdirective,

Page 800: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

BarbaraJensoncouldsignonasBarbaraJenson,BabsJensonoranyothercnthatshehasinherLDAPentry.Onlythesinglerequireldap-userlineisneededtosupportallvaluesoftheattributeintheuser'sentry.

IftheuidattributewasusedinsteadofthecnattributeintheURLabove,theabovethreelinescouldbecondensedto

requireldap-userbjensonfuserjmanager

requireldap-groupThisdirectivespecifiesanLDAPgroupwhosemembersareallowedaccess.IttakesthedistinguishednameoftheLDAPgroup.Note:Donotsurroundthegroupnamewithquotes.Forexample,assumethatthefollowingentryexistedintheLDAPdirectory:

dn:cn=Administrators,o=Airius

objectClass:groupOfUniqueNames

uniqueMember:cn=BarbaraJenson,o=Airius

uniqueMember:cn=FredUser,o=Airius

ThefollowingdirectivewouldgrantaccesstobothFredandBarbara:

requireldap-groupcn=Administrators,o=Airius

BehaviorofthisdirectiveismodifiedbytheAuthLDAPGroupAttributeAuthLDAPGroupAttributeIsDN

directives.

requireldap-dnrequireldap-dndirectiveallowstheadministratortograntaccessbasedondistinguishednames.ItspecifiesaDNthatmustmatchfor

Page 801: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

accesstobegranted.Ifthedistinguishednamethatwasretrievedfromthedirectoryservermatchesthedistinguishednameintherequireldap-dn,thenauthorizationisgranted.Note:donotsurroundthedistinguishednamewithquotes.

ThefollowingdirectivewouldgrantaccesstoaspecificDN:

requireldap-dncn=BarbaraJenson,o=Airius

BehaviorofthisdirectiveismodifiedbytheAuthLDAPCompareDNOnServerdirective.

requireldap-attributerequireldap-attributedirectiveallowstheadministratortograntaccessbasedonattributesoftheauthenticateduserintheLDAPdirectory.Iftheattributeinthedirectorymatchesthevaluegivenintheconfiguration,accessisgranted.

ThefollowingdirectivewouldgrantaccesstoanyonewiththeattributeemployeeType=active

requireldap-attributeemployeeType=active

Multipleattribute/valuepairscanbespecifiedonthesamelineseparatedbyspacesortheycanbespecifiedinmultiplerequireldap-attributedirectives.Theeffectoflistingmultipleattribute/valuespairsisanORoperation.Accesswillbegrantedifanyofthelistedattributevaluesmatchthevalueofthecorrespondingattributeintheuserobject.Ifthevalueoftheattributecontainsaspace,onlythevaluemustbewithindoublequotes.

Thefollowingdirectivewouldgrantaccesstoanyonewiththecityattributeequalto"SanJose"orstatusequalto"Active"

Page 802: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

requireldap-attributecity="SanJose"

status=active

requireldap-filterrequireldap-filterdirectiveallowstheadministratortograntaccessbasedonacomplexLDAPsearchfilter.Ifthednreturnedbythefiltersearchmatchestheauthenticateduserdn,accessisgranted.

Thefollowingdirectivewouldgrantaccesstoanyonehavingacellphoneandisinthemarketingdepartment

requireldap-filter&(cell=*)

(department=marketing)

Thedifferencebetweentherequireldap-filterdirectiveandtherequireldap-attributedirectiveisthatldap-filterperformsasearchoperationontheLDAPdirectoryusingthespecifiedsearchfilterratherthanasimpleattributecomparison.Ifasimpleattributecomparisonisallthatisrequired,thecomparisonoperationperformedbyldap-attributewillbefasterthanthesearchoperationusedbyldap-filterespeciallywithinalargedirectory.

Page 803: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Examples

GrantaccesstoanyonewhoexistsintheLDAPdirectory,usingtheirUIDforsearches.

AuthLDAPURL

ldap://ldap1.airius.com:389/ou=People,

o=Airius?uid?sub?(objectClass=*)

requirevalid-user

Thenextexampleisthesameasabove;butwiththefieldsthathaveusefuldefaultsomitted.Also,notetheuseofaredundantLDAPserver.

AuthLDAPURLldap://ldap1.airius.com

ldap2.airius.com/ou=People,o=Airius

requirevalid-user

Thenextexampleissimilartothepreviousone,butitusesthecommonnameinsteadoftheUID.Notethatthiscouldbeproblematicalifmultiplepeopleinthedirectorysharethesamecn,becauseasearchoncnmustreturnexactlyoneentry.That'swhythisapproachisnotrecommended:it'sabetterideatochooseanattributethatisguaranteeduniqueinyourdirectory,suchasuid.

AuthLDAPURLldap://ldap.airius.com/ou=People,

o=Airius?cn

requirevalid-user

GrantaccesstoanybodyintheAdministratorsgroup.TheusersmustauthenticateusingtheirUID.

AuthLDAPURLldap://ldap.airius.com/o=Airius?

uid

Page 804: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

requireldap-groupcn=Administrators,o=Airius

ThenextexampleassumesthateveryoneatAiriuswhocarriesanalphanumericpagerwillhaveanLDAPattributeofqpagePagerID.Theexamplewillgrantaccessonlytopeople(authenticatedviatheirUID)whohavealphanumericpagers:

AuthLDAPURLldap://ldap.airius.com/o=Airius?

uid??(qpagePagerID=*)

requirevalid-user

Thenextexampledemonstratesthepowerofusingfilterstoaccomplishcomplicatedadministrativerequirements.Withoutfilters,itwouldhavebeennecessarytocreateanewLDAPgroupandensurethatthegroup'smembersremainsynchronizedwiththepagerusers.Thisbecomestrivialwithfilters.Thegoalistograntaccesstoanyonewhohasapager,plusgrantaccesstoJoeManager,whodoesn'thaveapager,butdoesneedtoaccessthesameresource:

AuthLDAPURLldap://ldap.airius.com/o=Airius?

uid??(|(qpagePagerID=*)(uid=jmanager))

requirevalid-user

Thislastmaylookconfusingatfirst,soithelpstoevaluatewhatthesearchfilterwilllooklikebasedonwhoconnects,asshownbelow.IfFredUserconnectsasfuser,thefilterwouldlooklike

(&(|(qpagePagerID=*)(uid=jmanager))

(uid=fuser))

Theabovesearchwillonlysucceediffuserhasapager.WhenJoeManagerconnectsasjmanager,thefilterlookslike

Page 805: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(&(|(qpagePagerID=*)(uid=jmanager))

(uid=jmanager))

Theabovesearchwillsucceedwhetherjmanagerhasapagerornot.

Page 806: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UsingTLS

TouseTLS,seethemod_ldapdirectivesLDAPTrustedClientCert,LDAPTrustedGlobalCertLDAPTrustedMode.

AnoptionalsecondparametercanbeaddedtotheAuthLDAPURLtooverridethedefaultconnectiontypesetbyLDAPTrustedMode.Thiswillallowtheconnectionestablishedbyanldap://Urltobeupgradedtoasecureconnectiononthesameport.

Page 807: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UsingSSL

TouseSSL,seethemod_ldapdirectivesLDAPTrustedClientCert,LDAPTrustedGlobalCertLDAPTrustedMode.

TospecifyasecureLDAPserver,useldaps://intheAuthLDAPURLdirective,insteadofldap://.

Page 808: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UsingMicrosoftFrontPagewithmod_authnz_ldap

Normally,FrontPageusesFrontPage-web-specificuser/groupfiles(i.e.,themod_authn_filemod_authz_groupfilemodules)tohandleallauthentication.Unfortunately,itisnotpossibletojustchangetoLDAPauthenticationbyaddingtheproperdirectives,becauseitwillbreakthePermissionsformsintheFrontPageclient,whichattempttomodifythestandardtext-basedauthorizationfiles.

OnceaFrontPagewebhasbeencreated,addingLDAPauthenticationtoitisamatterofaddingthefollowingdirectivestoevery.htaccessfilethatgetscreatedintheweb

AuthLDAPURL"theurl"

AuthzLDAPAuthoritativeoff

AuthGroupFilemygroupfile

requiregroupmygroupfile

AuthzLDAPAuthoritativemustbeofftoallowmod_authnz_ldaptodeclinegroupauthenticationsothatApachewillfallbacktofileauthenticationforcheckinggroupmembership.ThisallowstheFrontPage-managedgroupfiletobeused.

HowItWorksFrontPagerestrictsaccesstoawebbyaddingtherequirevalid-userdirectivetothe.htaccessfiles.Therequirevalid-userdirectivewillsucceedforanyuserwhoisvalidasfarasLDAPisconcerned.ThismeansthatanybodywhohasanentryintheLDAPdirectoryisconsideredavaliduser,whereasFrontPageconsidersonlythosepeopleinthelocaluserfiletobevalid.Bysubstitutingtheldap-groupwithgroupfileauthorization,Apacheisallowedtoconsultthelocaluserfile(whichismanagedbyFrontPage)-insteadofLDAP-whenhandlingauthorizingtheuser.

Oncedirectiveshavebeenaddedasspecifiedabove,FrontPage

Page 809: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

userswillbeabletoperformallmanagementoperationsfromtheFrontPageclient.

CaveatsWhenchoosingtheLDAPURL,theattributetouseforauthenticationshouldbesomethingthatwillalsobevalidforputtingintoamod_authn_fileuserfile.TheuserIDisidealforthis.WhenaddingusersviaFrontPage,FrontPageadministratorsshouldchooseusernamesthatalreadyexistintheLDAPdirectory(forobviousreasons).Also,thepasswordthattheadministratorentersintotheformisignored,sinceApachewillactuallybeauthenticatingagainstthepasswordintheLDAPdatabase,andnotagainstthepasswordinthelocaluserfile.Thiscouldcauseconfusionforwebadministrators.Apachemustbecompiledwithmod_auth_basic,mod_authn_filemod_authz_groupfileinordertouseFrontPagesupport.ThisisbecauseApachewillstillusethemod_authz_groupfilegroupfilefordeterminetheextentofauser'saccesstotheFrontPageweb.Thedirectivesmustbeputinthe.htaccessfiles.Attemptingtoputtheminside<Location><Directory>directiveswon'twork.Thisisbecausemod_authnz_ldaphastobeabletograbtheAuthGroupFiledirectivethatisfoundinFrontPage.htaccessfilessothatitknowswheretolookforthevaliduserlist.Ifthemod_authnz_ldapdirectivesaren'tinthesame.htaccessfileastheFrontPagedirectives,thenthehackwon'twork,becausemod_authnz_ldapwillnevergetachancetoprocessthe.htaccessfile,andwon'tbeabletofindtheFrontPage-manageduserfile.

Page 810: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPBindDN

OptionalDNtouseinbindingtotheLDAPserverAuthLDAPBindDNdistinguished-name

directory,.htaccessAuthConfig(E)mod_authnz_ldap

AnoptionalDNusedtobindtotheserverwhensearchingforentries.Ifnotprovided,mod_authnz_ldapwilluseananonymousbind.

Page 811: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPBindPassword

PasswordusedinconjuctionwiththebindDNAuthLDAPBindPasswordpassword

directory,.htaccessAuthConfig(E)mod_authnz_ldap

AbindpasswordtouseinconjunctionwiththebindDN.Notethatthebindpasswordisprobablysensitivedata,andshouldbeproperlyprotected.YoushouldonlyusetheAuthLDAPBindDNAuthLDAPBindPasswordifyouabsolutelyneedthemtosearchthedirectory.

Page 812: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPCharsetConfig

LanguagetocharsetconversionconfigurationfileAuthLDAPCharsetConfigfile-path

serverconfig(E)mod_authnz_ldap

AuthLDAPCharsetConfigdirectivesetsthelocationofthelanguagetocharsetconversionconfigurationfile.File-pathisrelativetotheServerRoot.Thisfilespecifiesthelistoflanguageextensionstocharactersets.Mostadministratorsusetheprovidedcharset.convfile,whichassociatescommonlanguageextensionstocharactersets.

Thefilecontainslinesinthefollowingformat:

Language-Extensioncharset[Language-String]...

Thecaseoftheextensiondoesnotmatter.Blanklines,andlinesbeginningwithahashcharacter(#)areignored.

Page 813: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPCompareDNOnServer

UsetheLDAPservertocomparetheDNsAuthLDAPCompareDNOnServeron|off

AuthLDAPCompareDNOnServeron

directory,.htaccessAuthConfig(E)mod_authnz_ldap

Whenset,mod_authnz_ldapwillusetheLDAPservertocomparetheDNs.ThisistheonlyfoolproofwaytocompareDNs.mod_authnz_ldapwillsearchthedirectoryfortheDNspecifiedwiththerequiredndirective,then,retrievetheDNandcompareitwiththeDNretrievedfromtheuserentry.Ifthisdirectiveisnotset,mod_authnz_ldapsimplydoesastringcomparison.Itispossibletogetfalsenegativeswiththisapproach,butitismuchfaster.Notethemod_ldapcachecanspeedupDNcomparisoninmostsituations.

Page 814: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPDereferenceAliases

Whenwillthemodulede-referencealiasesAuthLDAPDereferenceAliases

never|searching|finding|always

AuthLDAPDereferenceAliasesAlways

directory,.htaccessAuthConfig(E)mod_authnz_ldap

Thisdirectivespecifieswhenmod_authnz_ldapwillde-referencealiasesduringLDAPoperations.Thedefaultisalways.

Page 815: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPGroupAttribute

LDAPattributesusedtocheckforgroupmembershipAuthLDAPGroupAttributeattribute

directory,.htaccessAuthConfig(E)mod_authnz_ldap

ThisdirectivespecifieswhichLDAPattributesareusedtocheckforgroupmembership.Multipleattributescanbeusedbyspecifyingthisdirectivemultipletimes.Ifnotspecified,thenmod_authnz_ldapusesthememberuniquememberattributes.

Page 816: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPGroupAttributeIsDN

UsetheDNoftheclientusernamewhencheckingforgroupmembershipAuthLDAPGroupAttributeIsDNon|off

AuthLDAPGroupAttributeIsDNon

directory,.htaccessAuthConfig(E)mod_authnz_ldap

Whenseton,thisdirectivesaystousethedistinguishednameoftheclientusernamewhencheckingforgroupmembership.Otherwise,theusernamewillbeused.Forexample,assumethattheclientsenttheusernamebjenson,whichcorrespondstotheLDAPDNcn=BabsJenson,o=Airius.Ifthisdirectiveisset,mod_authnz_ldapwillcheckifthegrouphascn=BabsJenson,o=Airiusasamember.Ifthisdirectiveisnotset,thenmod_authnz_ldapwillcheckifthegrouphasbjensonasamember.

Page 817: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPRemoteUserIsDN

UsetheDNoftheclientusernametosettheREMOTE_USERenvironmentvariableAuthLDAPRemoteUserIsDNon|off

AuthLDAPRemoteUserIsDNoff

directory,.htaccessAuthConfig(E)mod_authnz_ldap

Ifthisdirectiveissettoon,thevalueoftheREMOTE_USERenvironmentvariablewillbesettothefulldistinguishednameoftheauthenticateduser,ratherthanjusttheusernamethatwaspassedbytheclient.Itisturnedoffbydefault.

Page 818: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPUrl

URLspecifyingtheLDAPsearchparametersAuthLDAPUrlurl[NONE|SSL|TLS|STARTTLS]

directory,.htaccessAuthConfig(E)mod_authnz_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_authnz_ldapwilltryconnectingtoeachserverinturn,untilitmakesasuccessfulconnection.

Onceaconnectionhasbeenmadetoaserver,thatconnectionremainsactiveforthelifeofthehttpdprocess,oruntiltheLDAPservergoesdown.

IftheLDAPservergoesdownandbreaksanexistingconnection,mod_authnz_ldapwillattempttore-connect,startingwiththeprimaryserver,andtryingeachredundantserverinturn.Notethatthisisdifferentthanatrueround-robinsearch.

Page 819: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

basednTheDNofthebranchofthedirectorywhereallsearchesshouldstartfrom.Attheveryleast,thismustbethetopofyourdirectorytree,butcouldalsospecifyasubtreeinthedirectory.

attributeTheattributetosearchfor.AlthoughRFC2255allowsacomma-separatedlistofattributes,onlythefirstattributewillbeused,nomatterhowmanyareprovided.Ifnoattributesareprovided,thedefaultistouseuid.It'sagoodideatochooseanattributethatwillbeuniqueacrossallentriesinthesubtreeyouwillbeusing.

scopeThescopeofthesearch.Canbeeitheronesub.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=*).WhenaclientattemptstoconnectusingausernameofBabsJenson,theresultingsearchfilterwillbe(&(posixid=*)(cn=BabsJenson)).

AnoptionalparametercanbeaddedtoallowtheLDAPUrltooverride

Page 820: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

theconnectiontype.Thisparametercanbeoneofthefollowing:

NONEEstablishanunsecureconnectiononthedefaultLDAPport.Thisisthesameasldap://onport389.

SSLEstablishasecureconnectiononthedefaultsecureLDAPport.Thisisthesameasldaps://

TLS|STARTTLSEstablishanupgradedsecureconnectiononthedefaultLDAPport.Thisconnectionwillbeinitiatedonport389bydefaultandthenupgradedtoasecureconnectiononthesameport.

SeeaboveforexamplesofAuthLDAPURLURLs.

Page 821: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthzLDAPAuthoritative

PreventotherauthenticationmodulesfromauthenticatingtheuserifthisonefailsAuthzLDAPAuthoritativeon|off

AuthzLDAPAuthoritativeon

directory,.htaccessAuthConfig(E)mod_authnz_ldap

Settooffifthismoduleshouldletotherauthenticationmodulesattempttoauthenticatetheuser,shouldauthenticationwiththismodulefail.ControlisonlypassedontolowermodulesifthereisnoDNorrulethatmatchesthesuppliedusername(aspassedbytheclient).

Page 822: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 823: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authz_dbm

DBM(E)authz_dbm_modulemod_authz_dbm.cApache2.1

Thismoduleprovidesauthorizationcapabilitiessothatauthenticateduserscanbeallowedordeniedaccesstoportionsofthewebsitebygroupmembership.Similarfunctionalityisprovidedbymod_authz_groupfile.

Page 824: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthDBMGroupFile

SetsthenameofthedatabasefilecontainingthelistofusergroupsforauthorizationAuthDBMGroupFilefile-path

directory,.htaccessAuthConfig(E)mod_authz_dbm

AuthDBMGroupFiledirectivesetsthenameofaDBMfilecontainingthelistofusergroupsforuserauthorization.File-pathistheabsolutepathtothegroupfile.

Thegroupfileiskeyedontheusername.Thevalueforauserisacomma-separatedlistofthegroupstowhichtheusersbelongs.Theremustbenowhitespacewithinthevalue,anditmustnevercontainanycolons.

MakesurethattheAuthDBMGroupFileisstoredoutsidethedocumenttreeoftheweb-server.Donotputitinthedirectorythatitprotects.Otherwise,clientswillbeabletodownloadtheAuthDBMGroupFileunlessotherwiseprotected.

CombiningGroupandPasswordDBMfiles:Insomecasesitiseasiertomanageasingledatabasewhichcontainsboththepasswordandgroupdetailsforeachuser.Thissimplifiesanysupportprogramsthatneedtobewritten:theynowonlyhavetodealwithwritingtoandlockingasingleDBMfile.ThiscanbeaccomplishedbyfirstsettingthegroupandpasswordfilestopointtothesameDBM:

AuthDBMGroupFile/www/userbase

AuthDBMUserFile/www/userbase

Page 825: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ThekeyforthesingleDBMistheusername.Thevalueconsistsof

EncryptedPassword:ListofGroups[:(ignored)

]

Thepasswordsectioncontainstheencryptedpasswordasbefore.Thisisfollowedbyacolonandthecommaseparatedlistofgroups.OtherdatamayoptionallybeleftintheDBMfileafteranothercolon;itisignoredbytheauthorizationmodule.Thisiswhatwww.telescope.orgusesforitscombinedpasswordandgroupdatabase.

Page 826: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthzDBMAuthoritative

SetswhetherauthorizationwillbepassedontolowerlevelmodulesAuthzDBMAuthoritativeOn|Off

AuthzDBMAuthoritativeOn

directory,.htaccessAuthConfig(E)mod_authz_dbm

SettingtheAuthzDBMAuthoritativedirectiveexplicitlytoOffallowsgroupauthorizationtobepassedontolowerlevelmodules(asdefinedinthemodules.cfile)ifthereisnogroupfoundforthethesupplieduserID.Ifthereareanygroupsspecified,theusualcheckswillbeappliedandafailurewillgiveanAuthenticationRequiredreply.

SoifauserIDappearsinthedatabaseofmorethanonemodule;orifavalidRequiredirectiveappliestomorethanonemodule;thenthefirstmodulewillverifythecredentials;andnoaccessispassedon;regardlessoftheAuthBasicAuthoritativesetting.

Acommonuseforthisisinconjunctionwithoneoftheauthproviders;suchasmod_authn_dbmmod_authn_file.WhereasthisDBMmodulesuppliesthebulkoftheusercredentialchecking;afew(administrator)relatedaccessesfallthroughtoalowerlevelwithawellprotected.htpasswdfile.

Bydefault,controlisnotpassedonandanunknowngroupwillresultinanAuthenticationRequiredreply.NotsettingitthuskeepsthesystemsecureandforcesanNCSAcompliantbehaviour.

Doconsidertheimplicationsofallowingausertoallowfall-throughinhis.htaccessfile;andverifythatthisisreallywhatyouwant;

Page 827: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Generallyitiseasiertojustsecureasingle.htpasswdfile,thanitistosecureadatabasewhichmighthavemoreaccessinterfaces.

Page 828: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthzDBMType

SetsthetypeofdatabasefilethatisusedtostorelistofusergroupsAuthzDBMTypedefault|SDBM|GDBM|NDBM|DB

AuthzDBMTypedefault

directory,.htaccessAuthConfig(E)mod_authz_dbm

Setsthetypeofdatabasefilethatisusedtostorethelistofusergroups.Thedefaultdatabasetypeisdeterminedatcompiletime.Theavailabilityofothertypesofdatabasefilesalsodependsoncompile-timesettings.

Itiscrucialthatwhateverprogramyouusetocreateyourgroupfilesisconfiguredtousethesametypeofdatabase.

Page 829: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006124|

Page 830: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authz_default

(B)authz_default_modulemod_authz_default.cApache2.1

(fallback)( mod_authz_usermod_authz_groupfile)

Page 831: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthzDefaultAuthoritative

AuthzDefaultAuthoritativeOn|Off

AuthzDefaultAuthoritativeOn

directory,.htaccessAuthConfig(B)mod_authz_default

AuthzDefaultAuthoritative Off( modules.c)

mod_authz_default AuthzDefaultAuthoritative

(On)

Page 832: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006124|

Page 833: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authz_groupfile

(B)authz_groupfile_modulemod_authz_groupfile.cApache2.1

mod_authz_dbm

Page 834: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthGroupFile

AuthGroupFilefile-path

directory,.htaccessAuthConfig(B)mod_authz_groupfile

AuthGroupFile File-path ServerRoot

mygroup:bobjoeanne

AuthDBMGroupFile

AuthGroupFileWEB

Page 835: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthzGroupFileAuthoritative

AuthzGroupFileAuthoritativeOn|Off

AuthzGroupFileAuthoritativeOn

directory,.htaccessAuthConfig(B)mod_authz_groupfile

AuthzGroupFileAuthoritative OffuserID()( modules.c)

NCSA

.htaccess .htpasswd

Page 836: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006124|

Page 837: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authz_host

IP(B)authz_host_modulemod_authz_host.cApache2.1

mod_authz_host<Directory>,<Files>,<Location>.htaccess IP AllowDeny OrderAllowDeny

Satisfy

( GET,PUT,POST) <Limit>

Page 838: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Allow

Allowfromall|host|env=env-variable

[host|env=env-variable]...

directory,.htaccessLimit(B)mod_authz_host

AllowIPIP

" from"" Allowfromall" DenyOrder host

()

Allowfromapache.org

Allowfrom.netexample.edu

foo.apache.orgfooapache.orgApacheHostnameLookupsIPDNSIP

IP

Allowfrom10.1.2.3

Allowfrom192.168.1.104192.168.1.205

IP

IP

Page 839: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Allowfrom10.1

Allowfrom10172.20192.168.2

IP13

/

Allowfrom10.1.0.0/255.255.0.0

"a.b.c.d""w.x.y.z"

/nnn(CIDRspecification)

Allowfrom10.1.0.0/16

nnn

IPv6IPv6

Allowfrom2001:db8::a00:20ff:fea7:ccea

Allowfrom2001:db8::a00:20ff:fea7:ccea/10

Allow" Allowfromenv=env-variable" env-variablemod_setenvif User-Agent() RefererHTTP

SetEnvIfUser-Agent^KnockKnock/2\.0let_me_in

<Directory/docroot>

OrderDeny,Allow

Denyfromall

Page 840: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Allowfromenv=let_me_in

</Directory>

KnockKnock/2.0

Page 841: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Deny

Denyfromall|host|env=env-variable[host|env=env-

variable]...

directory,.htaccessLimit(B)mod_authz_host

IP DenyAllow

Page 842: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Order

AllowDeny

Orderordering

OrderDeny,Allow

directory,.htaccessLimit(B)mod_authz_host

OrderAllowDeny Ordering

Deny,Allow

DenyAllow DenyAllow

Allow,Deny

AllowDeny AllowDeny

Mutual-failure

AllowDeny" OrderAllow,Deny"

AllowDeny

apache.org

OrderDeny,Allow

Denyfromall

Allowfromapache.org

apache.orgfoo.apache.orgapache.org

OrderAllow,Deny

Allowfromapache.org

Denyfromfoo.apache.org

Order" Deny,Allow"" Allowfrom

Page 843: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

apache.org"" Denyfromfoo.apache.org" apache.org

AllowDeny Order

<Directory/www>

OrderAllow,Deny

</Directory>

/www

Order <Location>AllowDeny<Directory>.htaccess

AllowDeny Order

Page 844: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 845: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authz_owner

(E)authz_owner_modulemod_authz_owner.cApache2.1

ThismoduleauthorizesaccesstofilesbycomparingtheuseridusedforHTTPauthentication(thewebuserid)withthefile-systemownerorgroupoftherequestedfile.Thesuppliedusernameandpasswordmustbealreadyproperlyverifiedbyanauthenticationmodule,suchasmod_auth_basicmod_auth_digest.mod_authz_ownerrecognizestwoargumentsfortheRequiredirective,file-ownerfile-group,asfollows:

file-owner

Thesuppliedweb-usernamemustmatchthesystem'snamefortheownerofthefilebeingrequested.Thatis,iftheoperatingsystemsaystherequestedfileisownedbyjones,thentheusernameusedtoaccessitthroughthewebmustbejonesaswell.

file-group

Thenameofthesystemgroupthatownsthefilemustbepresentinagroupdatabase,whichisprovided,forexample,bymod_authz_groupfilemod_authz_dbm,andtheweb-usernamemustbeamemberofthatgroup.Forexample,iftheoperatingsystemsaystherequestedfileisownedby(system)groupaccounts,thegroupaccountsmustappearinthegroupdatabaseandtheweb-usernameusedintherequestmustbeamemberofthatgroup.

Page 846: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Ifmod_authz_ownerisusedinordertoauthorizearesourcethatisnotactuallypresentinthefilesystem(i.e.avirtualresource),itwilldenytheaccess.

Particularlyitwillneverauthorizecontentnegotiated"MultiViews"resources.

Page 847: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ConfigurationExamples

Requirefile-ownerConsideramulti-usersystemrunningtheApacheWebserver,witheachuserhavinghisorherownfilesin~/public_html/private.AssumingthatthereisasingleAuthDBMUserFiledatabasethatlistsalloftheirweb-usernames,andthattheseusernamesmatchthesystem'susernamesthatactuallyownthefilesontheserver,thenthefollowingstanzawouldallowonlytheuserhimselfaccesstohisownfiles.Userjoneswouldnotbeallowedtoaccessfilesin/home/smith/public_html/privateunlesstheywereownedbyjonesinsteadofsmith.

<Directory/home/*/public_html/private>

AuthTypeBasic

AuthNameMyPrivateFiles

AuthBasicProviderdbm

AuthDBMUserFile/usr/local/apache2/etc/.htdbm-

all

SatisfyAll

Requirefile-owner

</Directory>

Requirefile-groupConsiderasystemsimilartotheonedescribedabove,butwithsomeusersthatsharetheirprojectfilesin~/public_html/project-foo.ThefilesareownedbythesystemgroupfooandthereisasingleAuthDBMGroupFiledatabasethatcontainsalloftheweb-usernamesandtheirgroupmembership,i.e.theymustbeatleastmemberofagroupnamedfoo.Soifjonessmitharebothmemberofthegroupfoo,thenbothwillbeauthorizedtoaccesstheproject-foodirectoriesofeachother.

Page 848: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Directory/home/*/public_html/project-foo>

AuthTypeBasic

AuthName"ProjectFooFiles"

AuthBasicProviderdbm

#combineduser/groupdatabase

AuthDBMUserFile/usr/local/apache2/etc/.htdbm-

all

AuthDBMGroupFile/usr/local/apache2/etc/.htdbm-

all

SatisfyAll

Requirefile-group

</Directory>

Page 849: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthzOwnerAuthoritative

SetswhetherauthorizationwillbepassedontolowerlevelmodulesAuthzOwnerAuthoritativeOn|Off

AuthzOwnerAuthoritativeOn

directory,.htaccessAuthConfig(E)mod_authz_owner

SettingtheAuthzOwnerAuthoritativedirectiveexplicitlytoOffallowsforuserauthorizationtobepassedontolowerlevelmodules(asdefinedinthemodules.cfiles)if:

inthecaseoffile-ownerthefile-systemownerdoesnotmatchthesuppliedweb-usernameorcouldnotbedetermined,orinthecaseoffile-groupthefile-systemgroupdoesnotcontainthesuppliedweb-usernameorcouldnotbedetermined.

NotethatsettingthevaluetoOffalsoallowsthecombinationoffile-ownerfile-group,soaccesswillbeallowedifeitheroneortheother(orboth)match.

Bydefault,controlisnotpassedonandanauthorizationfailurewillresultinan"AuthenticationRequired"reply.NotsettingittoOffthuskeepsthesystemsecureandforcesanNCSAcompliantbehaviour.

Page 850: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006124|

Page 851: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_authz_user

(B)authz_user_modulemod_authz_user.cApache2.1

mod_authz_user() Requireuser require

valid-user

Page 852: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AuthzUserAuthoritative

AuthzUserAuthoritativeOn|Off

AuthzUserAuthoritativeOn

directory,.htaccessAuthConfig(B)mod_authz_user

AuthzUserAuthoritative OffuserID() ( modules.c

)

NCSA

Page 853: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 854: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_autoindex

"ls""dir"(B)autoindex_modulemod_autoindex.c

Theindexofadirectorycancomefromoneoftwosources:

Afilewrittenbytheuser,typicallycalledindex.html.TheDirectoryIndexdirectivesetsthenameofthisfile.Thisiscontrolledbymod_dir.Otherwise,alistinggeneratedbytheserver.Theotherdirectivescontroltheformatofthislisting.TheAddIcon,AddIconByEncodingAddIconByTypeareusedtosetalistoficonstodisplayforvariousfiletypes;foreachfilelisted,thefirsticonlistedthatmatchesthefileisdisplayed.Thesearecontrolledbymod_autoindex.

Thetwofunctionsareseparatedsothatyoucancompletelyremove(orreplace)automaticindexgenerationshouldyouwantto.

AutomaticindexgenerationisenabledwithusingOptions+Indexes.SeetheOptionsdirectiveformoredetails.

IftheFancyIndexingoptionisgivenwiththeIndexOptionsdirective,thecolumnheadersarelinksthatcontroltheorderofthedisplay.Ifyouselectaheaderlink,thelistingwillberegenerated,sortedbythevaluesinthatcolumn.Selectingthesameheaderrepeatedlytogglesbetweenascendinganddescendingorder.ThesecolumnheaderlinksaresuppressedwithIndexOptions

Page 855: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

directive'sSuppressColumnSortingoption.

Notethatwhenthedisplayissortedby"Size",it'stheactualsizeofthefilesthat'sused,notthedisplayedvalue-soa1010-bytefilewillalwaysbedisplayedbeforea1011-bytefile(ifinascendingorder)eventhoughtheybothareshownas"1K".

Page 856: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AutoindexRequestQueryArguments

Apache2.0.23reorganizedtheQueryArgumentsforColumnSorting,andintroducedanentiregroupofnewqueryoptions.Toeffectivelyeliminateallclientcontrolovertheoutput,theIndexOptionsIgnoreClientoptionwasintroduced.

Thecolumnsortingheadersthemselvesareself-referencinghyperlinksthataddthesortqueryoptionsshownbelow.Anyoptionbelowmaybeaddedtoanyrequestforthedirectoryresource.

C=NsortsthedirectorybyfilenameC=Msortsthedirectorybylast-modifieddate,thenfilenameC=Ssortsthedirectorybysize,thenfilenameC=Dsortsthedirectorybydescription,thenfilename

O=AsortsthelistinginAscendingOrderO=DsortsthelistinginDescendingOrder

F=0formatsthelistingasasimplelist(notFancyIndexed)F=1formatsthelistingasaFancyIndexedlistF=2formatsthelistingasanHTMLTableFancyIndexedlist

V=0disablesversionsortingV=1enablesversionsorting

P=patternlistsonlyfilesmatchingthegivenpattern

Notethatthe'P'atternqueryargumentistestedaftertheusualIndexIgnoredirectivesareprocessed,andallfilenamesarestillsubjectedtothesamecriteriaasanyotherautoindexlisting.TheQueryArgumentsparserinmod_autoindexwillstopabruptlywhenanunrecognizedoptionisencountered.TheQueryArgumentsmustbewellformed,accordingtothetableabove.

Thesimpleexamplebelow,whichcanbeclippedandsavedina

Page 857: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

header.htmlfile,illustratesthesequeryoptions.Notethattheunknown"X"argument,forthesubmitbutton,islistedlasttoassuretheargumentsareallparsedbeforemod_autoindexencounterstheX=Goinput.

<formaction=""method="get">

Showmea<selectname="F">

<optionvalue="0">Plainlist</option>

<optionvalue="1"selected="selected">Fancy

list</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">in

Normalorder</option>

<optionvalue="1">inVersionorder</option>

</select>

Matching<inputtype="text"name="P"value="*"

/>

<inputtype="submit"name="X"value="Go"/>

</form>

Page 858: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddAlt

Alternatetexttodisplayforafile,insteadofaniconselectedbyfilenameAddAltstringfile[file]...

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

AddAltprovidesthealternatetexttodisplayforafile,insteadofanicon,forFancyIndexing.Fileisafileextension,partialfilename,wild-cardexpressionorfullfilenameforfilestodescribe.IfStringcontainsanywhitespace,youhavetoencloseitinquotes("').Thisalternatetextisdisplayediftheclientisimage-incapable,hasimageloadingdisabled,orfailstoretrievetheicon.

AddAlt"PDFfile"*.pdf

AddAltCompressed*.gz*.zip*.Z

Page 859: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddAltByEncoding

AlternatetexttodisplayforafileinsteadofaniconselectedbyMIME-encodingAddAltByEncodingstringMIME-encoding[MIME-

encoding]...

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

AddAltByEncodingprovidesthealternatetexttodisplayforafile,insteadofanicon,forFancyIndexing.MIME-encodingisavalidcontent-encoding,suchasx-compress.IfStringcontainsanywhitespace,youhavetoencloseitinquotes("').Thisalternatetextisdisplayediftheclientisimage-incapable,hasimageloadingdisabled,orfailstoretrievetheicon.

AddAltByEncodinggzipx-gzip

Page 860: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddAltByType

Alternatetexttodisplayforafile,insteadofaniconselectedbyMIMEcontent-typeAddAltByTypestringMIME-type[MIME-type]...

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

AddAltByTypesetsthealternatetexttodisplayforafile,insteadofanicon,forFancyIndexing.MIME-typeisavalidcontent-type,suchastext/html.IfStringcontainsanywhitespace,youhavetoencloseitinquotes("').Thisalternatetextisdisplayediftheclientisimage-incapable,hasimageloadingdisabled,orfailstoretrievetheicon.

AddAltByType'plaintext'text/plain

Page 861: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddDescription

DescriptiontodisplayforafileAddDescriptionstringfile[file]...

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

Thissetsthedescriptiontodisplayforafile,forFancyIndexing.Fileisafileextension,partialfilename,wild-cardexpressionorfullfilenameforfilestodescribe.Stringisenclosedindoublequotes(").

AddDescription"TheplanetMars"

/web/pics/mars.gif

Thetypical,defaultdescriptionfieldis23byteswide.6morebytesareaddedbytheIndexOptionsSuppressIconoption,7bytesareaddedbytheIndexOptionsSuppressSizeoption,and19bytesareaddedbytheIndexOptionsSuppressLastModifiedoption.Therefore,thewidestdefaultthedescriptioncolumniseverassignedis55bytes.

SeetheDescriptionWidthIndexOptionskeywordfordetailsonoverridingthesizeofthiscolumn,orallowingdescriptionsofunlimitedlength.

Caution

DescriptivetextdefinedwithAddDescriptionmaycontainHTMLmarkup,suchastagsandcharacterentities.Ifthewidthofthedescriptioncolumnshouldhappentotruncateataggedelement(suchascuttingofftheendofaboldedphrase),theresultsmay

Page 862: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

affecttherestofthedirectorylisting.

Page 863: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddIcon

IcontodisplayforafileselectedbynameAddIconiconname[name]...

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

ThissetstheicontodisplaynexttoafileendinginnameforFancyIndexing.Iconiseithera(%-escaped)relativeURLtotheicon,oroftheformat(alttext,url)wherealttextisthetexttaggivenforaniconfornon-graphicalbrowsers.

Nameiseither^^DIRECTORY^^fordirectories,^^BLANKICON^^forblanklines(toformatthelistcorrectly),afileextension,awildcardexpression,apartialfilenameoracompletefilename.

AddIcon(IMG,/icons/image.xbm).gif.jpg.xbm

AddIcon/icons/dir.xbm^^DIRECTORY^^

AddIcon/icons/backup.xbm*~

AddIconByTypeshouldbeusedinpreferencetoAddIcon,whenpossible.

Page 864: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddIconByEncoding

IcontodisplaynexttofilesselectedbyMIMEcontent-encodingAddIconByEncodingiconMIME-encoding[MIME-

encoding]...

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

ThissetstheicontodisplaynexttofileswithFancyIndexing.Iconiseithera(%-escaped)relativeURLtotheicon,oroftheformat(alttext,url)wherealttextisthetexttaggivenforaniconfornon-graphicalbrowsers.

MIME-encodingisawildcardexpressionmatchingrequiredthecontent-encoding.

AddIconByEncoding/icons/compress.xbmx-compress

Page 865: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddIconByType

IcontodisplaynexttofilesselectedbyMIMEcontent-typeAddIconByTypeiconMIME-type[MIME-type]...

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

ThissetstheicontodisplaynexttofilesoftypeMIME-typeforFancyIndexing.Iconiseithera(%-escaped)relativeURLtotheicon,oroftheformat(alttext,url)wherealttextisthetexttaggivenforaniconfornon-graphicalbrowsers.

MIME-typeisawildcardexpressionmatchingrequiredthemimetypes.

AddIconByType(IMG,/icons/image.xbm)image/*

Page 866: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DefaultIcon

IcontodisplayforfileswhennospecificiconisconfiguredDefaultIconurl-path

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

DefaultIcondirectivesetstheicontodisplayforfileswhennospecificiconisknown,forFancyIndexing.Url-pathisa(%-escaped)relativeURLtotheicon.

DefaultIcon/icon/unknown.xbm

Page 867: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HeaderName

NameofthefilethatwillbeinsertedatthetopoftheindexlistingHeaderNamefilename

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

HeaderNamedirectivesetsthenameofthefilethatwillbeinsertedatthetopoftheindexlisting.Filenameisthenameofthefiletoinclude.

HeaderNameHEADER.html

BothHeaderNameandReadmeNamenowtreatFilenameasaURIpathrelativetotheoneusedtoaccessthedirectorybeingindexed.IfFilenamebeginswithaslash,itwillbetakentoberelativetotheDocumentRoot.

HeaderName/include/HEADER.html

Filenamemustresolvetoadocumentwithamajorcontenttypeoftext/*( text/html,text/plain,etc.).ThismeansthatfilenamemayrefertoaCGIscriptifthescript'sactualfiletype(asopposedtoitsoutput)ismarkedastext/htmlsuchaswithadirectivelike:

AddTypetext/html.cgi

Page 868: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ContentnegotiationwillbeperformedifOptionsMultiViewsisineffect.Iffilenameresolvestoastatictext/htmldocument(notaCGIscript)andeitheroneoftheoptionsIncludesIncludesNOEXECisenabled,thefilewillbeprocessedforserver-sideincludes(seethemod_includedocumentation).

IfthefilespecifiedbyHeaderNamecontainsthebeginningsofanHTMLdocument(<html>,<head>,etc.)thenyouwillprobablywanttosetIndexOptions+SuppressHTMLPreamble,sothatthesetagsarenotrepeated.

Page 869: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IndexIgnore

AddstothelistoffilestohidewhenlistingadirectoryIndexIgnorefile[file]...

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

IndexIgnoredirectiveaddstothelistoffilestohidewhenlistingadirectory.Fileisashell-stylewildcardexpressionorfullfilename.MultipleIndexIgnoredirectivesaddtothelist,ratherthanthereplacingthelistofignoredfiles.Bydefault,thelistcontains.(thecurrentdirectory).

IndexIgnoreREADME.htaccess*.bak*~

Page 870: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IndexOptions

VariousconfigurationsettingsfordirectoryindexingIndexOptions[+|-]option[[+|-]option]...

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

IndexOptionsdirectivespecifiesthebehaviorofthedirectoryindexing.Optioncanbeoneof

DescriptionWidth=[n|*](Apache2.0.23andlater)TheDescriptionWidthkeywordallowsyoutospecifythewidthofthedescriptioncolumnincharacters.-DescriptionWidth(orunset)allowsmod_autoindextocalculatethebestwidth.DescriptionWidth=nfixesthecolumnwidthtonbyteswide.DescriptionWidth=*growsthecolumntothewidthnecessarytoaccommodatethelongestdescriptionstring.SeethesectiononAddDescriptionfordangersinherentintruncatingdescriptions.

FancyIndexingThisturnsonfancyindexingofdirectories.

FoldersFirst(Apache2.0.23andlater)Ifthisoptionisenabled,subdirectorylistingswillalwaysappearfirst,followedbynormalfilesinthedirectory.Thelistingisbasicallybrokenintotwocomponents,thefilesandthesubdirectories,andeachissortedseparatelyandthendisplayedsubdirectories-first.Forinstance,ifthesortorderisdescendingbyname,andFoldersFirstisenabled,subdirectoryZedwillbelistedbeforesubdirectoryBeta,whichwillbelistedbeforenormalfilesGammaAlpha.Thisoptiononlyhasaneffectif

Page 871: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FancyIndexingisalsoenabled.

HTMLTable(Experimental,Apache2.0.23andlater)ThisexperimentaloptionwithFancyIndexingconstructsasimpletableforthefancydirectorylisting.Notethiswillconfuseolderbrowsers.Itisparticularlynecessaryiffilenamesordescriptiontextwillalternatebetweenleft-to-rightandright-to-leftreadingorder,ascanhappenonWinNTorotherutf-8enabledplatforms.

IconsAreLinksThismakestheiconspartoftheanchorforthefilename,forfancyindexing.

IconHeight[=pixels]Presenceofthisoption,whenusedwithIconWidth,willcausetheservertoincludeheightwidthattributesintheimgtagforthefileicon.Thisallowsbrowsertoprecalculatethepagelayoutwithouthavingtowaituntilalltheimageshavebeenloaded.Ifnovalueisgivenfortheoption,itdefaultstothestandardheightoftheiconssuppliedwiththeApachesoftware.

IconWidth[=pixels]Presenceofthisoption,whenusedwithIconHeight,willcausetheservertoincludeheightwidthattributesintheimgtagforthefileicon.Thisallowsbrowsertoprecalculatethepagelayoutwithouthavingtowaituntilalltheimageshavebeenloaded.Ifnovalueisgivenfortheoption,itdefaultstothestandardwidthoftheiconssuppliedwiththeApachesoftware.

IgnoreCaseIfthisoptionisenabled,namesaresortedinacase-insensitivemanner.Forinstance,ifthesortorderisascendingbyname,andIgnoreCaseisenabled,fileZetawillbelistedafterfilealfa(Note:fileGAMMAwillalwaysbelistedbeforefilegamma).

IgnoreClientThisoptioncausesmod_autoindextoignoreallqueryvariablesfromtheclient,includingsortorder(implies

Page 872: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SuppressColumnSorting.)

NameWidth=[n|*]TheNameWidthkeywordallowsyoutospecifythewidthofthefilenamecolumninbytes.-NameWidth(orunset)allowsmod_autoindextocalculatethebestwidth.NameWidth=nfixesthecolumnwidthtonbyteswide.NameWidth=*growsthecolumntothenecessarywidth.

ScanHTMLTitlesThisenablestheextractionofthetitlefromHTMLdocumentsforfancyindexing.IfthefiledoesnothaveadescriptiongivenbyAddDescriptionthenhttpdwillreadthedocumentforthevalueofthetitleelement.ThisisCPUanddiskintensive.

ShowForbiddenIfspecified,ApachewillshowfilesnormallyhiddenbecausethesubrequestreturnedHTTP_UNAUTHORIZEDorHTTP_FORBIDDEN

SuppressColumnSortingIfspecified,ApachewillnotmakethecolumnheadingsinaFancyIndexeddirectorylistingintolinksforsorting.Thedefaultbehaviorisforthemtobelinks;selectingthecolumnheadingwillsortthedirectorylistingbythevaluesinthatcolumn.PriortoApache2.0.23,thisalsodisabledparsingtheQueryArgumentsforthesortstring.ThatbehaviorisnowcontrolledbyIndexOptionsIgnoreClientinApache2.0.23.

SuppressDescriptionThiswillsuppressthefiledescriptioninfancyindexinglistings.Bydefault,nofiledescriptionsaredefined,andsotheuseofthisoptionwillregain23charactersofscreenspacetouseforsomethingelse.SeeAddDescriptionforinformationaboutsettingthefiledescription.SeealsotheDescriptionWidthindexoptiontolimitthesizeofthedescriptioncolumn.

Page 873: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SuppressHTMLPreambleIfthedirectoryactuallycontainsafilespecifiedbytheHeaderNamedirective,themoduleusuallyincludesthecontentsofthefileafterastandardHTMLpreamble(<html>,<head>,etcetera).TheSuppressHTMLPreambleoptiondisablesthisbehaviour,causingthemoduletostartthedisplaywiththeheaderfilecontents.TheheaderfilemustcontainappropriateHTMLinstructionsinthiscase.Ifthereisnoheaderfile,thepreambleisgeneratedasusual.

SuppressIcon(Apache2.0.23andlater)Thiswillsuppresstheiconinfancyindexinglistings.CombiningbothSuppressIconSuppressRulesyieldsproperHTML3.2output,whichbythefinalspecificationprohibitsimghrelementsfromthepreblock(usedtoformatFancyIndexedlistings.)

SuppressLastModifiedThiswillsuppressthedisplayofthelastmodificationdate,infancyindexinglistings.

SuppressRules(Apache2.0.23andlater)Thiswillsuppressthehorizontalrulelines(hrelements)indirectorylistings.CombiningbothSuppressIconSuppressRulesyieldsproperHTML3.2output,whichbythefinalspecificationprohibitsimghrelementsfromthepreblock(usedtoformatFancyIndexedlistings.)

SuppressSizeThiswillsuppressthefilesizeinfancyindexinglistings.

TrackModified(Apache2.0.23andlater)ThisreturnstheLast-ModifiedandETagvaluesforthelisteddirectoryintheHTTPheader.Itisonlyvalidiftheoperatingsystemandfilesystemreturnappropriatestat()results.SomeUnixsystemsdoso,asdoOS2'sJFSandWin32'sNTFSvolumes.OS2andWin32FATvolumes,forexample,donot.Oncethisfeatureisenabled,theclientorproxycantrack

Page 874: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

changestothelistoffileswhentheyperformaHEADrequest.Notesomeoperatingsystemscorrectlytracknewandremovedfiles,butdonottrackchangesforsizesordatesofthefileswithinthedirectory.ChangestothesizeordatestampofanexistingfilewillnotupdatetheLast-ModifiedheaderonallUnixplatforms.Ifthisisaconcern,leavethisoptiondisabled.

VersionSort(Apache2.0a3andlater)TheVersionSortkeywordcausesfilescontainingversionnumberstosortinanaturalway.Stringsaresortedasusual,exceptthatsubstringsofdigitsinthenameanddescriptionarecomparedaccordingtotheirnumericvalue.

foo-1.7

foo-1.7.2

foo-1.7.12

foo-1.8.2

foo-1.8.2a

foo-1.12

Ifthenumberstartswithazero,thenitisconsideredtobeafraction:

foo-1.001

foo-1.002

foo-1.030

foo-1.04

XHTML(Apache2.0.49andlater)TheXHTMLkeywordforcesmod_autoindextoemitXHTML1.0codeinsteadofHTML3.2.

IncrementalIndexOptionsApache1.3.3introducedsomesignificantchangesinthe

Page 875: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

handlingofIndexOptionsdirectives.Inparticular:

MultipleIndexOptionsdirectivesforasingledirectoryarenowmergedtogether.Theresultof:

<Directory/foo>

IndexOptionsHTMLTable

IndexOptionsSuppressColumnsorting

</Directory>

willbetheequivalentof

IndexOptionsHTMLTable

SuppressColumnsorting

Theadditionoftheincrementalsyntax(i.e.,prefixingkeywordswith+-).

Whenevera'+'or'-'prefixedkeywordisencountered,itisappliedtothecurrentIndexOptionssettings(whichmayhavebeeninheritedfromanupper-leveldirectory).However,wheneveranunprefixedkeywordisprocessed,itclearsallinheritedoptionsandanyincrementalsettingsencounteredsofar.Considerthefollowingexample:

IndexOptions+ScanHTMLTitles-IconsAreLinks

FancyIndexing

IndexOptions+SuppressSize

TheneteffectisequivalenttoIndexOptionsFancyIndexing+SuppressSize,becausetheunprefixedFancyIndexingdiscardedtheincrementalkeywordsbeforeit,butallowedthemtostartaccumulatingagainafterward.

Page 876: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TounconditionallysettheIndexOptionsforaparticulardirectory,clearingtheinheritedsettings,specifykeywordswithoutany+-prefixes.

Page 877: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IndexOrderDefault

SetsthedefaultorderingofthedirectoryindexIndexOrderDefaultAscending|Descending

Name|Date|Size|Description

IndexOrderDefaultAscendingName

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

IndexOrderDefaultdirectiveisusedincombinationwiththeFancyIndexingindexoption.Bydefault,fancyindexeddirectorylistingsaredisplayedinascendingorderbyfilename;theIndexOrderDefaultallowsyoutochangethisinitialdisplayorder.

IndexOrderDefaulttakestwoarguments.ThefirstmustbeeitherAscendingDescending,indicatingthedirectionofthesort.ThesecondargumentmustbeoneofthekeywordsName,Date,Size,orDescription,andidentifiestheprimarykey.Thesecondarykeyisalwaystheascendingfilename.

YoucanforceadirectorylistingtoonlybedisplayedinaparticularorderbycombiningthisdirectivewiththeSuppressColumnSortingindexoption;thiswillpreventtheclientfromrequestingthedirectorylistinginadifferentorder.

Page 878: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IndexStyleSheet

AddsaCSSstylesheettothedirectoryindexIndexStyleSheeturl-path

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

IndexStyleSheetdirectivesetsthenameofthefilethatwillbeusedastheCSSfortheindexlisting.

IndexStyleSheet"/css/style.css"

Page 879: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ReadmeName

NameofthefilethatwillbeinsertedattheendoftheindexlistingReadmeNamefilename

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex

ReadmeNamedirectivesetsthenameofthefilethatwillbeappendedtotheendoftheindexlisting.Filenameisthenameofthefiletoinclude,andistakentoberelativetothelocationbeingindexed.IfFilenamebeginswithaslash,itwillbetakentoberelativetotheDocumentRoot.

ReadmeNameFOOTER.html

Example2ReadmeName/include/FOOTER.html

SeealsoHeaderName,wherethisbehaviorisdescribedingreaterdetail.

Page 880: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 881: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_cache

URI()(E)cache_modulemod_cache.c

ThismoduleshouldbeusedwithcareandcanbeusedtocircumventAllowDenydirectives.Youshouldnotenablecachingforanycontenttowhichyouwishtolimitaccessbyclienthostname,addressorenvironmentvariable.

mod_cacheimplementsanRFC2616compliantHTTPcontentcachethatcanbeusedtocacheeitherlocalorproxiedcontent.mod_cacherequirestheservicesofoneormorestoragemanagementmodules.TwostoragemanagementmodulesareincludedinthebaseApachedistribution:

mod_disk_cache

implementsadiskbasedstoragemanager.

mod_mem_cache

implementsamemorybasedstoragemanager.mod_mem_cachecanbeconfiguredtooperateintwomodes:cachingopenfiledescriptorsorcachingobjectsinheapstorage.mod_mem_cachecanbeusedtocachelocallygeneratedcontentortocachebackendservercontentformod_proxywhenconfiguredusingProxyPass(akareverseproxy)

ContentisstoredinandretrievedfromthecacheusingURIbasedkeys.Contentwithaccessprotectionisnotcached.

Page 882: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 883: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RelatedModulesandDirectives

mod_disk_cache

mod_mem_cache

CacheRoot

CacheSize

CacheDirLevels

CacheDirLength

CacheMinFileSize

CacheMaxFileSize

MCacheSize

MCacheMaxObjectCount

MCacheMinObjectSize

MCacheMaxObjectSize

MCacheRemovalAlgorithm

MCacheMaxStreamingBuffer

Page 884: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SampleConfiguration

Samplehttpd.conf#

#SampleCacheConfiguration

#

LoadModulecache_modulemodules/mod_cache.so

<IfModulemod_cache.c>

#LoadModuledisk_cache_module

modules/mod_disk_cache.so

#Ifyouwanttousemod_disk_cacheinsteadof

mod_mem_cache,

#uncommentthelineaboveandcommentoutthe

LoadModulelinebelow.

<IfModulemod_disk_cache.c>

CacheRootc:/cacheroot

CacheEnabledisk/

CacheDirLevels5

CacheDirLength3

</IfModule>

LoadModulemem_cache_module

modules/mod_mem_cache.so

<IfModulemod_mem_cache.c>

CacheEnablemem/

MCacheSize4096

MCacheMaxObjectCount100

MCacheMinObjectSize1

MCacheMaxObjectSize2048

</IfModule>

#Whenactingasaproxy,don'tcachethelist

ofsecurityupdates

CacheDisable

http://security.update.server/update-list/

</IfModule>

Page 885: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 886: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheDefaultExpire

Thedefaultdurationtocacheadocumentwhennoexpirydateisspecified.CacheDefaultExpireseconds

CacheDefaultExpire3600(onehour)

serverconfig,virtualhost(E)mod_cache

CacheDefaultExpiredirectivespecifiesadefaulttime,inseconds,tocacheadocumentifneitheranexpirydatenorlast-modifieddateareprovidedwiththedocument.ThevaluespecifiedwiththeCacheMaxExpiredirectivedoesnotoverridethissetting.

CacheDefaultExpire86400

Page 887: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheDisable

DisablecachingofspecifiedURLsCacheDisableurl-string

serverconfig,virtualhost(E)mod_cache

CacheDisabledirectiveinstructsmod_cachetonotcacheurlsatorbelowurl-string.

CacheDisable/local_files

Page 888: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheEnable

EnablecachingofspecifiedURLsusingaspecifiedstoragemanagerCacheEnablecache_typeurl-string

serverconfig,virtualhost(E)mod_cache

CacheEnabledirectiveinstructsmod_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/

Whenactingasaforwardproxyserver,url-stringcanalsobeusedtospecifyremotesitesandproxyprotocolswhichcachingshouldbeenabledfor.

#Cacheproxiedurl's

Page 889: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheEnabledisk/

#CacheFTP-proxiedurl's

CacheEnablediskftp://

#Cachecontentfromwww.apache.org

CacheEnablediskhttp://www.apache.org/

Page 890: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheIgnoreCacheControl

IgnorerequesttonotservecachedcontenttoclientCacheIgnoreCacheControlOn|Off

CacheIgnoreCacheControlOff

serverconfig,virtualhost(E)mod_cache

Ordinarily,requestscontainingaCache-Control:no-cacheorPragma:no-cacheheadervaluewillnotbeservedfromthecache.TheCacheIgnoreCacheControldirectiveallowsthisbehaviortobeoverridden.CacheIgnoreCacheControlOntellstheservertoattempttoservetheresourcefromthecacheeveniftherequestcontainsno-cacheheadervalues.Resourcesrequiringauthorizationwillneverbecached.

CacheIgnoreCacheControlOn

Warning:Thisdirectivewillallowservingfromthecacheeveniftheclienthasrequestedthatthedocumentnotbeservedfromthecache.Thismightresultinstalecontentbeingserved.

CacheStorePrivate

CacheStoreNoStore

Page 891: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheIgnoreHeaders

DonotstorethegivenHTTPheader(s)inthecache.CacheIgnoreHeadersheader-string[header-string]

...

CacheIgnoreHeadersNone

serverconfig,virtualhost(E)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.

Example1

Page 892: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheIgnoreHeadersSet-Cookie

Example2CacheIgnoreHeadersNone

Warning:IfheaderslikeExpireswhichareneededforpropercachemanagementarenotstoredduetoaCacheIgnoreHeaderssetting,thebehaviourofmod_cacheisundefined.

Page 893: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheIgnoreNoLastMod

IgnorethefactthataresponsehasnoLastModifiedheader.CacheIgnoreNoLastModOn|Off

CacheIgnoreNoLastModOff

serverconfig,virtualhost(E)mod_cache

Ordinarily,documentswithoutalast-modifieddatearenotcached.Undersomecircumstancesthelast-modifieddateisremoved(duringmod_includeprocessingforexample)ornotprovidedatall.TheCacheIgnoreNoLastModdirectiveprovidesawaytospecifythatdocumentswithoutlast-modifieddatesshouldbeconsideredforcaching,evenwithoutalast-modifieddate.Ifneitheralast-modifieddatenoranexpirydateareprovidedwiththedocumentthenthevaluespecifiedbytheCacheDefaultExpiredirectivewillbeusedtogenerateanexpirationdate.

CacheIgnoreNoLastModOn

Page 894: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheLastModifiedFactor

ThefactorusedtocomputeanexpirydatebasedontheLastModifieddate.CacheLastModifiedFactorfloat

CacheLastModifiedFactor0.1

serverconfig,virtualhost(E)mod_cache

Intheeventthatadocumentdoesnotprovideanexpirydatebutdoesprovidealast-modifieddate,anexpirydatecanbecalculatedbasedonthetimesincethedocumentwaslastmodified.TheCacheLastModifiedFactordirectivespecifiesafactortobeusedinthegenerationofthisexpirydateaccordingtothefollowingformula:expiry-period=time-since-last-modified-date*

factorexpiry-date=current-date+expiry-period

Forexample,ifthedocumentwaslastmodified10hoursago,andfactoris0.1thentheexpiry-periodwillbesetto10*0.1=1hour.Ifthecurrenttimewas3:00pmthenthecomputedexpiry-datewouldbe3:00pm+1hour=4:00pm.Iftheexpiry-periodwouldbelongerthanthatsetbyCacheMaxExpire,thenthelattertakesprecedence.

CacheLastModifiedFactor0.5

Page 895: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheMaxExpire

ThemaximumtimeinsecondstocacheadocumentCacheMaxExpireseconds

CacheMaxExpire86400(oneday)

serverconfig,virtualhost(E)mod_cache

CacheMaxExpiredirectivespecifiesthemaximumnumberofsecondsforwhichcachableHTTPdocumentswillberetainedwithoutcheckingtheoriginserver.Thus,documentswillbeoutofdateatmostthisnumberofseconds.Thismaximumvalueisenforcedevenifanexpirydatewassuppliedwiththedocument.

CacheMaxExpire604800

Page 896: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheStoreNoStore

Attempttocacherequestsorresponsesthathavebeenmarkedasno-store.CacheStoreNoStoreOn|Off

CacheStoreNoStoreOff

serverconfig,virtualhost(E)mod_cache

Ordinarily,requestsorresponseswithCache-Control:no-storeheadervalueswillnotbestoredinthecache.TheCacheStoreNoCachedirectiveallowsthisbehaviortobeoverridden.CacheStoreNoCacheOntellstheservertoattempttocachetheresourceevenifitcontainsno-storeheadervalues.Resourcesrequiringauthorizationwillneverbecached.

CacheStoreNoStoreOn

Warning:AsdescribedinRFC2616,theno-storedirectiveisintendedto"preventtheinadvertentreleaseorretentionofsensitiveinformation(forexample,onbackuptapes)."Enablingthisoptioncouldstoresensitiveinformationinthecache.Youareherebywarned.

CacheIgnoreCacheControl

CacheStorePrivate

Page 897: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

CacheStorePrivate

AttempttocacheresponsesthattheserverhasmarkedasprivateCacheStorePrivateOn|Off

CacheStorePrivateOff

serverconfig,virtualhost(E)mod_cache

Ordinarily,responseswithCache-Control:privateheadervalueswillnotbestoredinthecache.TheCacheStorePrivatedirectiveallowsthisbehaviortobeoverridden.CacheStorePrivateOntellstheservertoattempttocachetheresourceevenifitcontainsprivateheadervalues.Resourcesrequiringauthorizationwillneverbecached.

CacheStorePrivateOn

Warning:Thisdirectivewillallowcachingeveniftheupstreamserverhasrequestedthattheresourcenotbecached.Thisdirectiveisonlyidealfora'private'cache.

CacheIgnoreCacheControl

CacheStoreNoStore

Page 898: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 899: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_cern_meta

ApacheCERNhttpd(E)cern_meta_modulemod_cern_meta.c

EmulatetheCERNHTTPDMetafilesemantics.MetafilesareHTTPheadersthatcanbeoutputinadditiontothenormalrangeofheadersforeachfileaccessed.TheyappearratherliketheApache.asisfiles,andareabletoprovideacrudewayofinfluencingtheExpires:header,aswellasprovidingothercuriosities.Therearemanywaystomanagemetainformation,thisonewaschosenbecausethereisalreadyalargenumberofCERNuserswhocanexploitthismodule.

MoreinformationontheCERNmetafilesemanticsisavailable.

Page 900: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MetaDir

NameofthedirectorytofindCERN-stylemetainformationfilesMetaDirdirectory

MetaDir.web

serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_cern_meta

SpecifiesthenameofthedirectoryinwhichApachecanfindmetainformationfiles.Thedirectoryisusuallya'hidden'subdirectoryofthedirectorythatcontainsthefilebeingaccessed.Setto"."tolookinthesamedirectoryasthefile:

MetaDir.

Or,tosetittoasubdirectoryofthedirectorycontainingthefiles:

MetaDir.meta

Page 901: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MetaFiles

ActivatesCERNmeta-fileprocessingMetaFileson|off

MetaFilesoff

serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_cern_meta

Turnson/offMetafileprocessingonaper-directorybasis.

Page 902: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

MetaSuffix

FilenamesuffixforthefilecontaingCERN-stylemetainformationMetaSuffixsuffix

MetaSuffix.meta

serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_cern_meta

Specifiesthefilenamesuffixforthefilecontainingthemetainformation.Forexample,thedefaultvaluesforthetwodirectiveswillcausearequesttoDOCUMENT_ROOT/somedir/index.htmltolookinDOCUMENT_ROOT/somedir/.web/index.html.metaandwilluseitscontentstogenerateadditionalMIMEheaderinformation.

MetaSuffix.meta

Page 903: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006124|

Page 904: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_cgi

MPM(prefork)CGI(B)cgi_modulemod_cgi.c

MIMEapplication/x-httpd-cgicgi-scriptCGICGIAddType ScriptAlias

CGIDOCUMENT_ROOT DocumentRoot

ApacheCGI CGI

UNIXMPM mod_cgid

Page 905: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI

ApacheCGI

PATH_INFOAcceptPathInfo off AcceptPathInfomod_cgi(URI /more/path/info)"404NOTFOUND"AcceptPathInfo Onmod_cgi

REMOTE_HOSTHostnameLookups" on"("off")DNS

REMOTE_IDENTIdentityCheck on

REMOTE_USERCGI

Page 906: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI

CGI(stdoutstderr)

CGICGICGICGI

%%[time]request-line

%%HTTP-statusCGI-script-filename

CGI

%%error

error-message

(bug)

%request

AllHTTPrequestheadersreceived

POSTorPUTentity(ifany)

%response

AllheadersoutputbytheCGIscript

%stdout

CGIstandardoutput

%stderr

CGIstandarderror

stdoutstderr%stdout%stderr

Page 907: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ScriptLog

CGIScriptLogfile-path

serverconfig,virtualhost(B)mod_cgi,mod_cgid

ScriptLogCGI ScriptLogCGI ServerRoot

ScriptLoglogs/cgi_log

User

CGI

Page 908: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ScriptLogBuffer

PUTPOSTScriptLogBufferbytes

ScriptLogBuffer1024

serverconfig,virtualhost(B)mod_cgi,mod_cgid

PUTPOST1024

Page 909: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ScriptLogLength

()ScriptLogLengthbytes

ScriptLogLength10385760

serverconfig,virtualhost(B)mod_cgi,mod_cgid

ScriptLogLengthCGICGI()CGI

Page 910: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006124|

Page 911: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_cgid

MPM(worker)CGICGI(B)cgid_modulemod_cgid.cUnixMPM

ScriptSock mod_cgidmod_cgi mod_cgiApacheCGI

unixforkCGI mod_cgidforkCGIunixdomain

MPM mod_cgi mod_cgi ScriptSockcgi

Page 912: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ScriptSock

CGIScriptSockfile-path

ScriptSocklogs/cgisock

serverconfig,virtualhost(B)mod_cgid

CGI(PID)Apache(root)CGI

ScriptSock/var/run/cgid.sock

Page 913: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 914: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_charset_lite

(X)charset_lite_modulemod_charset_lite.c

Thisisanexperimentalmoduleandshouldbeusedwithcare.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.

Page 915: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CommonProblems

InvalidcharactersetnamesThecharactersetnameparametersofCharsetSourceEncCharsetDefaultmustbeacceptabletothetranslationmechanismusedbyAPRonthesystemwheremod_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.

Page 916: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CharsetDefault

CharsettotranslateintoCharsetDefaultcharset

serverconfig,virtualhost,directory,.htaccessFileInfo(X)mod_charset_lite

CharsetDefaultdirectivespecifiesthecharsetthatcontentintheassociatedcontainershouldbetranslatedto.

ThevalueofthecharsetargumentmustbeacceptedasavalidcharactersetnamebythecharactersetsupportinAPR.Generally,thismeansthatitmustbesupportedbyiconv.

<Directory

/export/home/trawick/apacheinst/htdocs/convert>

CharsetSourceEncUTF-16BE

CharsetDefaultISO-8859-1

</Directory>

Page 917: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CharsetOptions

ConfigurescharsettranslationbehaviorCharsetOptionsoption[option]...

CharsetOptionsDebugLevel=0NoImplicitAdd

serverconfig,virtualhost,directory,.htaccessFileInfo(X)mod_charset_lite

CharsetOptionsdirectiveconfigurescertainbehaviorsofmod_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.

Page 918: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

CharsetSourceEnc

SourcecharsetoffilesCharsetSourceEnccharset

serverconfig,virtualhost,directory,.htaccessFileInfo(X)mod_charset_lite

CharsetSourceEncdirectivespecifiesthesourcecharsetoffilesintheassociatedcontainer.

ThevalueofthecharsetargumentmustbeacceptedasavalidcharactersetnamebythecharactersetsupportinAPR.Generally,thismeansthatitmustbesupportedbyiconv.

<Directory

/export/home/trawick/apacheinst/htdocs/convert>

CharsetSourceEncUTF-16BE

CharsetDefaultISO-8859-1

</Directory>

ThecharactersetnamesinthisexampleworkwiththeiconvtranslationsupportinSolaris8.

Page 919: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 920: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_dav

ApacheDAV(E)dav_modulemod_dav.c

Thismoduleprovidesclass1andclass2WebDAV('Web-basedDistributedAuthoringandVersioning')functionalityforApache.ThisextensiontotheHTTPprotocolallowscreating,moving,copying,anddeletingresourcesandcollectionsonaremotewebserver.

Page 921: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

EnablingWebDAV

Toenablemod_dav,addthefollowingtoacontainerinyourhttpd.conffile:

DavOn

ThisenablestheDAVfilesystemprovider,whichisimplementedbythemod_dav_fsmodule.Therefore,thatmodulemustbecompiledintotheserverorloadedatruntimeusingtheLoadModuledirective.

Inaddition,alocationfortheDAVlockdatabasemustbespecifiedintheglobalsectionofyourhttpd.conffileusingtheDavLockDBdirective:

DavLockDB/usr/local/apache2/var/DavLock

ThedirectorycontainingthelockdatabasefilemustbewritablebytheUserGroupunderwhichApacheisrunning.

Youmaywishtoadda<Limit>clauseinsidethe<Location>directivetolimitaccesstoDAV-enabledlocations.IfyouwanttosetthemaximumamountofbytesthataDAVclientcansendatonerequest,youhavetousetheLimitXMLRequestBodydirective.The"normal"LimitRequestBodydirectivehasnoeffectonDAVrequests.

FullExampleDavLockDB/usr/local/apache2/var/DavLock

<Location/foo>

DavOn

AuthTypeBasic

AuthNameDAV

Page 922: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthUserFileuser.passwd

<LimitExceptGETOPTIONS>

requireuseradmin

</LimitExcept>

</Location>

mod_davisadescendentofGregStein'smod_davforApache1.3.Moreinformationaboutthemoduleisavailablefromthatsite.

Page 923: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SinceDAVaccessmethodsallowremoteclientstomanipulatefilesontheserver,youmusttakeparticularcaretoassurethatyourserverissecurebeforeenablingmod_dav.

AnylocationontheserverwhereDAVisenabledshouldbeprotectedbyauthentication.TheuseofHTTPBasicAuthenticationisnotrecommended.YoushoulduseatleastHTTPDigestAuthentication,whichisprovidedbythemod_auth_digestmodule.NearlyallWebDAVclientssupportthisauthenticationmethod.AnalternativeisBasicAuthenticationoveranSSLenabledconnection.

Inorderformod_davtomanagefiles,itmustbeabletowritetothedirectoriesandfilesunderitscontrolusingtheUserGroupunderwhichApacheisrunning.NewfilescreatedwillalsobeownedbythisUserGroup.Forthisreason,itisimportanttocontrolaccesstothisaccount.TheDAVrepositoryisconsideredprivatetoApache;modifyingfilesoutsideofApache(forexampleusingFTPorfilesystem-leveltools)shouldnotbeallowed.

mod_davmaybesubjecttovariouskindsofdenial-of-serviceattacks.TheLimitXMLRequestBodydirectivecanbeusedtolimittheamountofmemoryconsumedinparsinglargeDAVrequests.TheDavDepthInfinitydirectivecanbeusedtopreventPROPFINDrequestsonaverylargerepositoryfromconsuminglargeamountsofmemory.Anotherpossibledenial-of-serviceattackinvolvesaclientsimplyfillingupallavailablediskspacewithmanylargefiles.ThereisnodirectwaytopreventthisinApache,soyoushouldavoidgivingDAVaccesstountrustedusers.

Page 924: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ComplexConfigurations

Onecommonrequestistousemod_davtomanipulatedynamicfiles(PHPscripts,CGIscripts,etc).ThisisdifficultbecauseaGETrequestwillalwaysrunthescript,ratherthandownloadingitscontents.OnewaytoavoidthisistomaptwodifferentURLstothecontent,oneofwhichwillrunthescript,andoneofwhichwillallowittobedownloadedandmanipulatedwithDAV.

Alias/phparea/home/gstein/php_files

Alias/php-source/home/gstein/php_files

<Location/php-source>

DAVOn

ForceTypetext/plain

</Location>

Withthissetup,http://example.com/phpareacanbeusedtoaccesstheoutputofthePHPscripts,andhttp://example.com/php-sourcecanbeusedwithaDAVclienttomanipulatethem.

Page 925: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Dav

EnableWebDAVHTTPmethodsDavOn|Off|provider-name

DavOff

directory(E)mod_dav

UsetheDavdirectivetoenabletheWebDAVHTTPmethodsforthegivencontainer:

<Location/foo>

DavOn

</Location>

ThevalueOnisactuallyanaliasforthedefaultproviderfilesystemwhichisservedbythemod_dav_fsmodule.Note,thatonceyouhaveDAVenabledforsomelocation,itcannotbedisabledforsublocations.Foracompleteconfigurationexamplehavealookatthesectionabove.

DonotenableWebDAVuntilyouhavesecuredyourserver.Otherwiseeveryonewillbeabletodistributefilesonyoursystem.

Page 926: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DavDepthInfinity

AllowPROPFIND,Depth:InfinityrequestsDavDepthInfinityon|off

DavDepthInfinityoff

serverconfig,virtualhost,directory(E)mod_dav

UsetheDavDepthInfinitydirectivetoallowtheprocessingofPROPFINDrequestscontainingtheheader'Depth:Infinity'.Becausethistypeofrequestcouldconstituteadenial-of-serviceattack,bydefaultitisnotallowed.

Page 927: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DavMinTimeout

MinimumamountoftimetheserverholdsalockonaDAVresourceDavMinTimeoutseconds

DavMinTimeout0

serverconfig,virtualhost,directory(E)mod_dav

WhenaclientrequestsaDAVresourcelock,itcanalsospecifyatimewhenthelockwillbeautomaticallyremovedbytheserver.Thisvalueisonlyarequest,andtheservercanignoreitorinformtheclientofanarbitraryvalue.

UsetheDavMinTimeoutdirectivetospecify,inseconds,theminimumlocktimeouttoreturntoaclient.MicrosoftWebFoldersdefaultstoatimeoutof120seconds;theDavMinTimeoutcanoverridethistoahighervalue(like600seconds)toreducethechanceoftheclientlosingthelockduetonetworklatency.

<Location/MSWord>

DavMinTimeout600

</Location>

Page 928: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 929: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_dav_fs

mod_dav

(E)dav_fs_modulemod_dav_fs.c

Thismodulerequirestheserviceofmod_dav.Itactsasasupportmoduleformod_davandprovidesaccesstoresourceslocatedintheserver'sfilesystem.Theformalnameofthisproviderisfilesystem.mod_davbackendproviderswillbeinvokedbyusingtheDavdirective:

Davfilesystem

Sincefilesystemisthedefaultproviderformod_dav,youmaysimplyusethevalueOninstead.

Page 930: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DavLockDB

LocationoftheDAVlockdatabaseDavLockDBfile-path

serverconfig,virtualhost(E)mod_dav_fs

UsetheDavLockDBdirectivetospecifythefullpathtothelockdatabase,excludinganextension.Ifthepathisnotabsolute,itwillbetakenrelativetoServerRoot.Theimplementationofmod_dav_fsusesaSDBMdatabasetotrackuserlocks.

DavLockDBvar/DavLock

ThedirectorycontainingthelockdatabasefilemustbewritablebytheUserGroupunderwhichApacheisrunning.Forsecurityreasons,youshouldcreateadirectoryforthispurposeratherthanchangingthepermissionsonanexistingdirectory.Intheaboveexample,Apachewillcreatefilesinthevar/directoryundertheServerRootwiththebasefilenameDavLockandextensionnamechosenbytheserver.

Page 931: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 932: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_dav_lock

mod_dav

(E)dav_lock_modulemod_dav_lock.cApache2.1

ThismoduleimplementsagenericlockingAPIwhichcanbeusedbyanybackendproviderofmod_dav.Itrequiresatleasttheserviceofmod_dav.Butwithoutabackendproviderwhichmakesuseofit,it'suselessandshouldnotbeloadedintotheserver.Asamplebackendmodulewhichactuallyutilizesmod_dav_lock,ismod_dav_svn,thesubversionprovidermodule.

Notethatmod_dav_fsdoesnotneedthisgenericlockingmodule,becauseitusesit'sownmorespecializedversion.

Inordertomakemod_dav_lockfunctional,youjusthavetospecifythelocationofthelockdatabaseusingtheDavGenericLockDBdirectivedescribedbelow.

Developer'sNote

Inordertoretrievethepointertothelockingproviderfunction,youhavetousetheap_lookup_providerAPIwiththeargumentsdav-lock,generic0.

Page 933: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DavGenericLockDB

LocationoftheDAVlockdatabaseDavGenericLockDBfile-path

serverconfig,virtualhost,directory(E)mod_dav_lock

UsetheDavGenericLockDBdirectivetospecifythefullpathtothelockdatabase,excludinganextension.Ifthepathisnotabsolute,itwillbetakenrelativetoServerRoot.Theimplementationofmod_dav_lockusesaSDBMdatabasetotrackuserlocks.

DavGenericLockDBvar/DavLock

ThedirectorycontainingthelockdatabasefilemustbewritablebytheUserGroupunderwhichApacheisrunning.Forsecurityreasons,youshouldcreateadirectoryforthispurposeratherthanchangingthepermissionsonanexistingdirectory.Intheaboveexample,Apachewillcreatefilesinthevar/directoryundertheServerRootwiththebasefilenameDavLockandextensionnamechosenbytheserver.

Page 934: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 935: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_dbd

SQL(E)dbd_modulemod_dbd.cVersion2.1

mod_dbdmanagesSQLdatabaseconnectionsusingapr_dbd.ItprovidesdatabaseconnectionsonrequesttomodulesrequiringSQLdatabasefunctions,andtakescareofmanagingdatabaseswithoptimalefficiencyandscalabilityforboththreadedandnon-threadedMPMs.

Page 936: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ConnectionPooling

Thismodulemanagesdatabaseconnections,inamanneroptimisedfortheplatform.Onnon-threadedplatforms,itprovidesapersistentconnectioninthemannerofclassicLAMP(Linux,Apache,Mysql,Perl/PHP/Python).Onthreadedplatform,itprovidesanaltogethermorescalableandefficientconnectionpool,asdescribedinthisarticleatApacheTutor.mod_dbdsupersedesthemodulespresentedinthatarticle.

Page 937: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheDBDAPI

mod_dbdexportsfivefunctionsforothermodulestouse.TheAPIisasfollows:

typedefstruct{

apr_dbd_t*handle;

apr_dbd_driver_t*driver;

apr_hash_t*prepared;

}ap_dbd_t;

/*Exportfunctionstoaccessthedatabase*/

/*acquireaconnectionthatMUSTbeexplicitlyclosed.

*ReturnsNULLonerror

*/

AP_DECLARE(ap_dbd_t*)ap_dbd_open(apr_pool_t*,server_rec*);

/*releaseaconnectionacquiredwithap_dbd_open*/

AP_DECLARE(void)ap_dbd_close(server_rec*,ap_dbd_t*);

/*acquireaconnectionthatwillhavethelifetimeofarequest

*andMUSTNOTbeexplicitlyclosed.ReturnNULLonerror.

*Thisisthepreferredfunctionformostapplications.

*/

AP_DECLARE(ap_dbd_t*)ap_dbd_acquire(request_rec*);

/*acquireaconnectionthatwillhavethelifetimeofaconnection

*andMUSTNOTbeexplicitlyclosed.ReturnNULLonerror.

*/

AP_DECLARE(ap_dbd_t*)ap_dbd_cacquire(request_rec*);

/*Prepareastatementforusebyaclientmodule*/

AP_DECLARE(void)ap_dbd_prepare(server_rec*,constchar*,constchar*);

/*Alsoexportthemasoptionalfunctionsformodulesthatpreferit*/

APR_DECLARE_OPTIONAL_FN(ap_dbd_t*,ap_dbd_open,(apr_pool_t*,server_rec*));

APR_DECLARE_OPTIONAL_FN(void,ap_dbd_close,(server_rec*,ap_dbd_t*));

Page 938: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

APR_DECLARE_OPTIONAL_FN(ap_dbd_t*,ap_dbd_acquire,(request_rec*));

APR_DECLARE_OPTIONAL_FN(ap_dbd_t*,ap_dbd_cacquire,(conn_rec*));

APR_DECLARE_OPTIONAL_FN(void,ap_dbd_prepare,(server_rec*,constchar*,constchar*));

Page 939: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SQLPreparedStatements

mod_dbdsupportsSQLpreparedstatementsonbehalfofmodulesthatmaywishtousethem.Eachpreparedstatementmustbeassignedaname(label),andtheyarestoredinahash:thepreparedfieldofanap_dbd_t.Hashentriesareoftypeapr_dbd_prepared_tandcanbeusedinanyoftheapr_dbdpreparedstatementSQLqueryorselectcommands.

Itisuptodbdusermodulestousethepreparedstatementsanddocumentwhatstatementscanbespecifiedinhttpd.conf,ortoprovidetheirowndirectivesanduseap_dbd_prepare.

Page 940: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DBDExptime

KeepalivetimeforidleconnectionsDBDExptimetime-in-seconds

serverconfig,virtualhost(E)mod_dbd

SetthetimetokeepidleconnectionsalivewherethenumberofconnectionsspecifiedinDBDKeephasbeenexceeded(threadedplatformsonly).

Page 941: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DBDKeep

MaximumsustainednumberofconnectionsDBDKeepnumber

serverconfig,virtualhost(E)mod_dbd

Setthemaximumnumberofconnectionsperprocesstobesustained,otherthanforhandlingpeakdemand(threadedplatformsonly).

Page 942: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DBDMax

MaximumnumberofconnectionsDBDMaxnumber

serverconfig,virtualhost(E)mod_dbd

Setthehardmaximumnumberofconnectionsperprocess(threadedplatformsonly).

Page 943: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DBDMin

MinimumnumberofconnectionsDBDMinnumber

serverconfig,virtualhost(E)mod_dbd

Settheminimumnumberofconnectionsperprocess(threadedplatformsonly).

Page 944: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DBDParams

ParametersfordatabaseconnectionDBDParamsparam1=value1[,param2=value2]

serverconfig,virtualhost(E)mod_dbd

Asrequiredbytheunderlyingdriver.Typicallythiswillbeusedtopasswhatevercannotbedefaultedamongstusername,password,databasename,hostnameandportnumberforconnection.

Page 945: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DBDPersist

WhethertousepersistentconnectionsDBDPersist0|1

serverconfig,virtualhost(E)mod_dbd

Ifsetto0,persistentandpooledconnectionsaredisabled.Anewdatabaseconnectionisopenedwhenrequestedbyaclient,andclosedimmediatelyonrelease.Thisoptionisfordebuggingandlow-usageservers.

Thedefaultistoenableapoolofpersistentconnections(orasingleLAMP-stylepersistentconnectioninthecaseofanon-threadedserver),andshouldalmostalwaysbeusedinoperation.

Page 946: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DBDPrepareSQL

DefineanSQLpreparedstatementDBDPrepareSQL"SQLstatement"label

serverconfig,virtualhost(E)mod_dbd

FormodulessuchasauthenticationthatuserepeatedlyuseasingleSQLstatement,optimumperformanceisachievedbypreparingthestatementatstartupratherthaneverytimeitisused.ThisdirectivepreparesanSQLstatementandassignsitalabel.

Page 947: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DBDriver

SpecifyanSQLdriverDBDrivername

serverconfig,virtualhost(E)mod_dbd

Selectsanapr_dbddriverbyname.Thedrivermustbeinstalledonyoursystem(onmostsystems,itwillbeasharedobjectordll).Forexample,DBDrivermysqlwillselecttheMySQLdriverinapr_dbd_mysql.so.

Page 948: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006125|

Page 949: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_deflate

(E)deflate_modulemod_deflate.c

mod_deflateDEFLATE

Page 950: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddOutputFilterByTypeDEFLATEtext/htmltext/plain

text/xml

Compresseverythingexceptimages<Location/>

#

SetOutputFilterDEFLATE

#Netscape4.x...

BrowserMatch^Mozilla/4gzip-only-text/html

#Netscape4.06-4.08

BrowserMatch^Mozilla/4\.0[678]no-gzip

#MSIENetscape

BrowserMatch\bMSIE!no-gzip!gzip-only-

text/html

#

SetEnvIfNoCaseRequest_URI\

\.(?:gif|jpe?g|png)$no-gzipdont-vary

#

HeaderappendVaryUser-Agentenv=!dont-vary

</Location>

Page 951: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DEFLATE

SetOutputFilterDEFLATE

gzip-only-text/html" 1"html() "1"

MIME AddOutputFilterByTypehtml

<Directory"/your-server-root/manual">

AddOutputFilterByTypeDEFLATEtext/html

</Directory>

BrowserMatchno-gzip no-gzipgzip-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-AgentNavigator4.x text/html4.06,4.07,4.08Navigator

BrowserMatchIE"Mozilla/4" User-Agent"MSIE"(" \b""")

DEFLATEPHPSSI

SetEnvforce-gzip"accept-encoding"

Page 952: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_deflategzip SetOutputFilterAddOutputFilter

INFLATE

<Location/dav-area>

ProxyPasshttp://example.com/

SetOutputFilterINFLATE

</Location>

example.com

mod_deflategzip SetInputFilterAddInputFilterDEFLATE

<Location/dav-area>

SetInputFilterDEFLATE

</Location>

" Content-Encoding:gzip" WebDAV

Content-Length

Content-Length

Page 953: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_deflate" Vary:Accept-Encoding"HTTP" Accept-

Encoding"

( User-Agent) Vary DEFLATEUser-Agent

HeaderappendVaryUser-Agent

(HTTP) Vary" *"

HeadersetVary*

Page 954: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DeflateBufferSize

zlib()DeflateBufferSizevalue

DeflateBufferSize8096

serverconfig,virtualhost(E)mod_deflate

DeflateBufferSizezlib

Page 955: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DeflateCompressionLevel

DeflateCompressionLevelvalue

Zlib

serverconfig,virtualhost(E)mod_deflateApache2.0.45

DeflateCompressionLevelCPU

1()9()

Page 956: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DeflateFilterNote

DeflateFilterNote[type]notename

serverconfig,virtualhost(E)mod_deflatetype2.0.45

DeflateFilterNote notename

DeflateFilterNoteratio

LogFormat'"%r"%b(%{ratio}n)"%{User-agent}i"'

deflate

CustomLoglogs/deflate_logdeflate

typenotename type

Input

Output

Ratio

(/*100 ) type

AccurateLoggingDeflateFilterNoteInputinstream

DeflateFilterNoteOutputoutstream

DeflateFilterNoteRatioratio

Page 957: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LogFormat'"%r"%{outstream}n/%{instream}n(%

{ratio}n%%)'deflate

CustomLoglogs/deflate_logdeflate

mod_log_config

Page 958: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DeflateMemLevel

zlibDeflateMemLevelvalue

DeflateMemLevel9

serverconfig,virtualhost(E)mod_deflate

DeflateMemLevelzlib(19)

Page 959: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DeflateWindowSize

Zlib(compressionwindow)DeflateWindowSizevalue

DeflateWindowSize15

serverconfig,virtualhost(E)mod_deflate

DeflateWindowSizezlib(compressionwindow)(115)

Page 960: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006125|

Page 961: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_dir

""(B)dir_modulemod_dir.c

index.htmlmod_dirDirectoryIndexmod_autoindex

"/" http://servername/foo/dirname dirname

mod_dir http://servername/foo/dirname/

Page 962: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DirectoryIndex

DirectoryIndexlocal-url[local-url]...

DirectoryIndexindex.html

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_dir

DirectoryIndex"/" Local-url(%)URL()URLIndexes

DirectoryIndexindex.html

http://myserver/docs/http://myserver/docs/index.html()

URL

DirectoryIndexindex.htmlindex.txt/cgi-

bin/index.pl

index.htmlindex.txtCGI/cgi-bin/index.pl

Page 963: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DirectorySlash

(/)DirectorySlashOn|Off

DirectorySlashOn

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_dirApache2.0.51

DirectorySlashmod_dirURL"/"

"/" mod_dirURL"/"

URLmod_autoindex

DirectoryIndex"/"htmlURL

#

<Location/some/path>

DirectorySlashOff

SetHandlersome-handler

</Location>

mod_autoindex(Options+Indexes)DirectoryIndex(index.html)URL"/"URL index.html "/"

Page 964: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 965: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_disk_cache

(E)disk_cache_modulemod_disk_cache.c

mod_disk_cacheimplementsadiskbasedstoragemanager.Itisprimarilyofuseinconjunctionmod_cache.

ContentisstoredinandretrievedfromthecacheusingURIbasedkeys.Contentwithaccessprotectionisnotcached.

htcachecleancanbeusedtomaintainthecachesizeatamaximumlevel.

mod_disk_cacherequirestheservicesofmod_cache.

Page 966: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheDirLength

ThenumberofcharactersinsubdirectorynamesCacheDirLengthlength

CacheDirLength2

serverconfig,virtualhost(E)mod_disk_cache

CacheDirLengthdirectivesetsthenumberofcharactersforeachsubdirectorynameinthecachehierarchy.

TheresultofCacheDirLevels*CacheDirLengthmustnotbehigherthan20.

CacheDirLength4

Page 967: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheDirLevels

Thenumberoflevelsofsubdirectoriesinthecache.CacheDirLevelslevels

CacheDirLevels3

serverconfig,virtualhost(E)mod_disk_cache

CacheDirLevelsdirectivesetsthenumberofsubdirectorylevelsinthecache.CacheddatawillbesavedthismanydirectorylevelsbelowtheCacheRootdirectory.

TheresultofCacheDirLevels*CacheDirLengthmustnotbehigherthan20.

CacheDirLevels5

Page 968: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheMaxFileSize

Themaximumsize(inbytes)ofadocumenttobeplacedinthecacheCacheMaxFileSizebytes

CacheMaxFileSize1000000

serverconfig,virtualhost(E)mod_disk_cache

CacheMaxFileSizedirectivesetsthemaximumsize,inbytes,foradocumenttobeconsideredforstorageinthecache.

CacheMaxFileSize64000

Page 969: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheMinFileSize

Theminimumsize(inbytes)ofadocumenttobeplacedinthecacheCacheMinFileSizebytes

CacheMinFileSize1

serverconfig,virtualhost(E)mod_disk_cache

CacheMinFileSizedirectivesetstheminimumsize,inbytes,foradocumenttobeconsideredforstorageinthecache.

CacheMinFileSize64

Page 970: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

CacheRoot

ThedirectoryrootunderwhichcachefilesarestoredCacheRootdirectory

serverconfig,virtualhost(E)mod_disk_cache

CacheRootdirectivedefinesthenameofthedirectoryonthedisktocontaincachefiles.Ifthemod_disk_cachemodulehasbeenloadedorcompiledintotheApacheserver,thisdirectivemustbedefined.FailingtoprovideavalueforCacheRootwillresultinaconfigurationfileprocessingerror.TheCacheDirLevelsCacheDirLengthdirectivesdefinethestructureofthedirectoriesunderthespecifiedrootdirectory.

CacheRootc:/cacheroot

Page 971: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006125|

Page 972: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_dumpio

I/O(E)dumpio_modulemod_dumpio.c

mod_dumpioApache(error.log)

SSL()SSL()

Page 973: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

dumpio

Page 974: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DumpIOInput

DumpIOInputOn|Off

DumpIOInputOff

serverconfig(E)mod_dumpioApache2.1.3

DumpIOInputOn

Page 975: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

DumpIOOutput

DumpIOOutputOn|Off

DumpIOOutputOff

serverconfig(E)mod_dumpioApache2.1.3

DumpIOOutputOn

Page 976: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 977: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_echo

(X)echo_modulemod_echo.cApache2.0

Thismoduleprovidesanexampleprotocolmoduletoillustratetheconcept.Itprovidesasimpleechoserver.Telnettoitandtypestuff,anditwillechoit.

Page 978: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ProtocolEcho

TurntheechoserveronoroffProtocolEchoOn|Off

serverconfig,virtualhost(X)mod_echoProtocolEchoisonlyavailablein2.0

ProtocolEchodirectiveenablesordisablestheechoserver.

ProtocolEchoOn

Page 979: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006125|

Page 980: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_env

ApacheCGISSI(B)env_modulemod_env.c

CGISSI httpdshell(set)(unset)

Page 981: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

PassEnv

shellPassEnvenv-variable[env-variable]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_env

httpdshellCGISSI

PassEnvLD_LIBRARY_PATH

Page 982: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SetEnv

SetEnvenv-variablevalue

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_env

CGISSI

SetEnvSPECIAL_PATH/foo/bin

Page 983: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

UnsetEnv

UnsetEnvenv-variable[env-variable]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_env

CGISSI

UnsetEnvLD_LIBRARY_PATH

Page 984: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 985: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_example

ApacheAPI(X)example_modulemod_example.c

Somefilesinthemodules/experimentaldirectoryundertheApachedistributiondirectorytreeareprovidedasanexampletothosethatwishtowritemodulesthatusetheApacheAPI.

Themainfileismod_example.c,whichillustratesallthedifferentcallbackmechanismsandcallsyntaxes.Bynomeansdoesanadd-onmoduleneedtoincluderoutinesforallofthecallbacks-quitethecontrary!

Theexamplemoduleisanactualworkingmodule.Ifyoulinkitintoyourserver,enablethe"example-handler"handlerforalocation,andthenbrowsetothatlocation,youwillseeadisplayofsomeofthetracingtheexamplemoduledidasthevariouscallbacksweremade.

Page 986: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Compilingtheexamplemodule

Toincludetheexamplemoduleinyourserver,followthestepsbelow:

1. Runconfigurewith--enable-exampleoption.

2. Maketheserver(run"make").

Toaddanothermoduleofyourown:

A. cpmodules/experimental/mod_example.cmodules/new_module/mod_myexample.c

B. Modifythefile.

C. Createmodules/new_module/config.m4.

1. AddAPACHE_MODPATH_INIT(new_module).

2. CopyAPACHE_MODULElinewith"example"frommodules/experimental/config.m4.

3. Replacethefirstargument"example"withmyexample.

4. Replacethesecondargumentwithbriefdescriptionofyourmodule.Itwillbeusedinconfigure--help.

5. IfyourmoduleneedsadditionalCcompilerflags,linkerflagsorlibraries,addthemtoCFLAGS,LDFLAGSandLIBSaccordingly.Seeotherconfig.m4filesinmodulesdirectoryforexamples.

6. AddAPACHE_MODPATH_FINISH.

D. Createmodule/new_module/Makefile.in.Ifyourmoduledoesn'tneedspecialbuildinstructions,allyouneedtohaveinthatfileisinclude$(top_srcdir)/build/special.mk.

E. Run./buildconffromthetop-leveldirectory.

F. Buildtheserverwith--enable-myexample

Page 987: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Usingthemod_exampleModule

Toactivatetheexamplemodule,includeablocksimilartothefollowinginyourhttpd.conffile:

<Location/example-info>

SetHandlerexample-handler

</Location>

Asanalternative,youcanputthefollowingintoa.htaccessfileandthenrequestthefile"test.example"fromthatlocation:

AddHandlerexample-handler.example

Afterreloading/restartingyourserver,youshouldbeabletobrowsetothislocationandseethebriefdisplaymentionedearlier.

Page 988: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Example

DemonstrationdirectivetoillustratetheApachemoduleAPIExample

serverconfig,virtualhost,directory,.htaccess(X)mod_example

Exampledirectivejustsetsademonstrationflagwhichtheexamplemodule'scontenthandlerdisplays.Ittakesnoarguments.IfyoubrowsetoanURLtowhichtheexamplecontent-handlerapplies,youwillgetadisplayoftheroutineswithinthemoduleandhowandinwhatordertheywerecalledtoservicethedocumentrequest.Theeffectofthisdirectiveonecanobserveunderthepoint"Exampledirectivedeclaredhere:YES/NO".

Page 989: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006125|

Page 990: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_expires

HTTP" Expires"" Cache-Control"(E)expires_modulemod_expires.c

ExpiresCache-Controlmax-age(expirationdate)

HTTP()

Cache-Controlmax-age( RFC2616section14.9) Header

Page 991: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Alternate(/)Interval()Syntax()

ExpiresDefaultExpiresByType

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

3

ExpiresDefault"accessplus1month"

ExpiresDefault"accessplus4weeks"

ExpiresDefault"accessplus30days"

"<num><type>"

ExpiresByTypetext/html"accessplus1month15

days2hours"

ExpiresByTypeimage/gif"modificationplus5hours

3minutes"

Page 992: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

"Expires:" ""

Page 993: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ExpiresActive

" Expires:"" Cache-Control:"ExpiresActiveOn|Off

serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_expires

ExpiresCache-Control OffExpiresCache-Control(.htaccess) OnExpiresByTypeExpiresDefault

ExpiresCache-Control

ExpiresCache-Control

Page 994: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ExpiresByType

MIMEExpiresExpiresByTypeMIME-type<code>seconds

serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_expires

MIME( text/html)ExpiresCache-Controlmax-age secondsCache-Control:max-age

<code>" M"" A" <code>seconds

" M"URL()" A"

#

ExpiresActiveOn

#GIF1

ExpiresByTypeimage/gifA2592000

#HTML

ExpiresByTypetext/htmlM604800

" ExpiresActiveOn" MIMEExpiresDefault

alternatesyntax

Page 995: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ExpiresDefault

ExpiresDefault<code>seconds

serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_expires

ExpiresByTypeMIME ExpiresByTypealternatesyntax

Page 996: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 997: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_ext_filter

(E)ext_filter_modulemod_ext_filter.c

mod_ext_filterpresentsasimpleandfamiliarprogrammingmodelfor.Withthismodule,aprogramwhichreadsfromstdinandwritestostdout(i.e.,aUnix-stylefiltercommand)canbeafilterforApache.ThisfilteringmechanismismuchslowerthanusingafilterwhichisspeciallywrittenfortheApacheAPIandrunsinsideoftheApacheserverprocess,butitdoeshavethefollowingbenefits:

theprogrammingmodelismuchsimpleranyprogramming/scriptinglanguagecanbeused,providedthatitallowstheprogramtoreadfromstandardinputandwritetostandardoutputexistingprogramscanbeusedunmodifiedasApachefilters

Evenwhentheperformancecharacteristicsarenotsuitableforproductionuse,mod_ext_filtercanbeusedasaprototypeenvironmentforfilters.

Page 998: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

#perrequestshowingtheconfigurationin

force

ExtFilterOptionsDebugLevel=1

</Directory>

ImplementingacontentencodingfilterNote:thisgzipexampleisjustforthepurposesofillustration.Pleaserefertomod_deflateforapracticalimplementation.

#mod_ext_filterdirectivetodefinetheexternal

Page 999: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

filter

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

pathlength

#andconsumesmoreresources

ExtFilterDefineslowdownmode=outputcmd=/bin/cat

\

preservescontentlength

<Location/>

#coredirectivetocausetheslowdownfilter

to

#berunseveraltimesonoutput

#

SetOutputFilterslowdown;slowdown;slowdown

</Location>

Usingsedtoreplacetextintheresponse

#mod_ext_filterdirectivetodefineafilter

Page 1000: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

which

#replacestextintheresponse

#

ExtFilterDefinefixtextmode=output

intype=text/html\

cmd="/bin/seds/verdana/arial/g"

<Location/>

#coredirectivetocausethefixtextfilterto

#berunonoutput

SetOutputFilterfixtext

</Location>

Tracinganotherfilter

#Tracethedatareadandwrittenbymod_deflate

#foraparticularclient(IP192.168.1.31)

#experiencingcompressionproblems.

#Thisfilterwilltracewhatgoesinto

mod_deflate.

ExtFilterDefinetracebefore\

cmd="/bin/tracefilter.pl/tmp/tracebefore"\

EnableEnv=trace_this_client

#Thisfilterwilltracewhatgoesafter

mod_deflate.

#Notethatwithouttheftypeparameter,the

default

#filtertypeofAP_FTYPE_RESOURCEwouldcausethe

#filtertobeplaced*before*mod_deflateinthe

filter

#chain.Givingitanumericvalueslightlyhigher

than

#AP_FTYPE_CONTENT_SETwillensurethatitis

placed

#aftermod_deflate.

Page 1001: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ExtFilterDefinetraceafter\

cmd="/bin/tracefilter.pl/tmp/traceafter"\

EnableEnv=trace_this_clientftype=21

<Directory/usr/local/docs>

SetEnvIfRemote_Addr192.168.1.31

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

Page 1002: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ExtFilterDefine

DefineanexternalfilterExtFilterDefinefilternameparameters

serverconfig(E)mod_ext_filter

ExtFilterDefinedirectivedefinesthecharacteristicsofanexternalfilter,includingtheprogramtorunanditsarguments.

filternamespecifiesthenameofthefilterbeingdefined.ThisnamecanthenbeusedinSetOutputFilterdirectives.Itmustbeuniqueamongallregisteredfilters.Atthepresenttime,noerrorisreportedbytheregister-filterAPI,soaproblemwithduplicatenamesisn'treportedtotheuser.

Subsequentparameterscanappearinanyorderanddefinetheexternalcommandtorunandcertainothercharacteristics.Theonlyrequiredparameteriscmd=.Theseparametersare:

cmd=cmdline

Thecmd=keywordallowsyoutospecifytheexternalcommandtorun.Ifthereareargumentsaftertheprogramname,thecommandlineshouldbesurroundedinquotationmarks(

cmd="/bin/mypgmarg1arg2".)Normalshellquotingisnotnecessarysincetheprogramisrundirectly,bypassingtheshell.Programargumentsareblank-delimited.Abackslashcanbeusedtoescapeblankswhichshouldbepartofaprogramargument.Anybackslasheswhicharepartoftheargumentmustbeescapedwithbackslashthemselves.InadditiontothestandardCGIenvironmentvariables,DOCUMENT_URI,DOCUMENT_PATH_INFO,andQUERY_STRING_UNESCAPEDwillalsobesetfortheprogram.

mode=mode

Page 1003: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Usemode=output(thedefault)forfilterswhichprocesstheresponse.Usemode=inputforfilterswhichprocesstherequest.mode=inputisavailableinApache2.1andlater.

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.

Page 1004: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ExtFilterOptions

Configuremod_ext_filteroptionsExtFilterOptionsoption[option]...

ExtFilterOptionsDebugLevel=0NoLogStderr

directory(E)mod_ext_filter

ExtFilterOptionsdirectivespecifiesspecialprocessingoptionsformod_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.

ExtFilterOptionsLogStderrDebugLevel=0

Messageswrittentothefilter'sstandarderrorwillbestoredintheApacheerrorlog.Nodebugmessageswillbegeneratedby

Page 1005: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

mod_ext_filter.

Page 1006: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1007: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_file_cache

Apache(X)file_cache_modulemod_file_cache.c

Thismoduleshouldbeusedwithcare.Youcaneasilycreateabrokensiteusingmod_file_cache,soreadthisdocumentcarefully.

Cachingfrequentlyrequestedfilesthatchangeveryinfrequentlyisatechniqueforreducingserverload.mod_file_cacheprovidestwotechniquesforcachingfrequentlyrequestedstaticfiles.Throughconfigurationdirectives,youcandirectmod_file_cachetoeitheropenthenmmap()afile,ortopre-openafileandsavethefile'sopenfilehandle.Bothtechniquesreduceserverloadwhenprocessingrequestsforthesefilesbydoingpartofthework(specifically,thefileI/O)forservingthefilewhentheserverisstartedratherthanduringeachrequest.

YoucannotusethisforspeedingupCGIprogramsor otherfileswhichareservedbyspecialcontenthandlers.ItcanonlybeusedforregularfileswhichareusuallyservedbytheApachecorecontenthandler.

Thismoduleisanextensionofandborrowsheavilyfromthemod_mmap_staticmoduleinApache1.3.

Page 1008: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Usingmod_file_cache

mod_file_cachecachesalistofstaticallyconfiguredfilesviaMMapFileCacheFiledirectivesinthemainserverconfiguration.

Notallplatformssupportbothdirectives.Forexample,ApacheonWindowsdoesnotcurrentlysupporttheMMapStaticdirective,whileotherplatforms,likeAIX,supportboth.Youwillreceiveanerrormessageintheservererrorlogifyouattempttouseanunsupporteddirective.Ifgivenanunsupporteddirective,theserverwillstartbutthefilewillnotbecached.Onplatformsthatsupportbothdirectives,youshouldexperimentwithbothtoseewhichworksbestforyou.

MMapFileDirectiveMMapFiledirectiveofmod_file_cachemapsalistofstaticallyconfiguredfilesintomemorythroughthesystemcallmmap().ThissystemcallisavailableonmostmodernUnixderivates,butnotonall.Therearesometimessystem-specificlimitsonthesizeandnumberoffilesthatcanbemmap()ed,experimentationisprobablytheeasiestwaytofindout.

Thismmap()ingisdoneonceatserverstartorrestart,only.Sowheneveroneofthemappedfileschangesonthefilesystemyouhavetorestarttheserver(seetheStoppingandRestartingdocumentation).Toreiteratethatpoint:ifthefilesaremodifiedinplacewithoutrestartingtheserveryoumayendupservingrequeststhatarecompletelybogus.Youshouldupdatefilesbyunlinkingtheoldcopyandputtinganewcopyinplace.Mosttoolssuchasrdistmvdothis.Thereasonwhythismodulesdoesn'ttakecareofchangestothefilesisthatthischeckwouldneedanextrastat()everytimewhichisawasteandagainsttheintentofI/Oreduction.

CacheFileDirectiveCacheFiledirectiveofmod_file_cacheopensanactivehandle

Page 1009: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

filedescriptortothefile(orfiles)listedintheconfigurationdirectiveandplacestheseopenfilehandlesinthecache.Whenthefileisrequested,theserverretrievesthehandlefromthecacheandpassesittothesendfile()(orTransmitFile()onWindows),socketAPI.

Thisfilehandlecachingisdoneonceatserverstartorrestart,only.Sowheneveroneofthecachedfileschangesonthefilesystemyouhavetorestarttheserver(seetheStoppingandRestartingdocumentation).Toreiteratethatpoint:ifthefilesaremodifiedinplacewithoutrestartingtheserveryoumayendupservingrequeststhatarecompletelybogus.Youshouldupdatefilesbyunlinkingtheoldcopyandputtinganewcopyinplace.Mosttoolssuchasrdistmvdothis.

Don'tbotheraskingforadirectivewhichrecursivelycachesallthefilesinadirectory.Trythisinstead...SeetheIncludedirective,andconsiderthiscommand:

find/www/htdocs-typef-print\

|sed-e's/.*/mmapfile&/'>

/www/conf/mmap.conf

Page 1010: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheFile

CachealistoffilehandlesatstartuptimeCacheFilefile-path[file-path]...

serverconfig(X)mod_file_cache

CacheFiledirectiveopenshandlestooneormorefiles(givenaswhitespaceseparatedarguments)andplacesthesehandlesintothecacheatserverstartuptime.Handlestocachedfilesareautomaticallyclosedonaservershutdown.Whenthefileshavechangedonthefilesystem,theservershouldberestartedtotore-cachethem.

Becarefulwiththefile-patharguments:TheyhavetoliterallymatchthefilesystempathApache'sURL-to-filenametranslationhandlerscreate.Wecannotcompareinodesorotherstufftomatchpathsthroughsymboliclinksetc.becausethatagainwouldcostextrastat()systemcallswhichisnotacceptable.Thismodulemayormaynotworkwithfilenamesrewrittenbymod_aliasmod_rewrite.

CacheFile/usr/local/apache/htdocs/index.html

Page 1011: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

MMapFile

MapalistoffilesintomemoryatstartuptimeMMapFilefile-path[file-path]...

serverconfig(X)mod_file_cache

MMapFiledirectivemapsoneormorefiles(givenaswhitespaceseparatedarguments)intomemoryatserverstartuptime.Theyareautomaticallyunmappedonaservershutdown.WhenthefileshavechangedonthefilesystematleastaHUPUSR1signalshouldbesendtotheservertore-mmap()them.

Becarefulwiththefile-patharguments:TheyhavetoliterallymatchthefilesystempathApache'sURL-to-filenametranslationhandlerscreate.Wecannotcompareinodesorotherstufftomatchpathsthroughsymboliclinksetc.becausethatagainwouldcostextrastat()systemcallswhichisnotacceptable.Thismodulemayormaynotworkwithfilenamesrewrittenbymod_aliasmod_rewrite.

MMapFile/usr/local/apache/htdocs/index.html

Page 1012: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1013: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_filter

(B)filter_modulemod_filter.cVersion2.1

Thismoduleenablessmart,context-sensitiveconfigurationofoutputcontentfilters.Forexample,apachecanbeconfiguredtoprocessdifferentcontent-typesthroughdifferentfilters,evenwhenthecontent-typeisnotknowninadvance(e.g.inaproxy).

mod_filterworksbyintroducingindirectionintothefilterchain.Insteadofinsertingfiltersinthechain,weinsertafilterharnesswhichinturndispatchesconditionallytoafilterprovider.Anycontentfiltermaybeusedasaprovidertomod_filter;nochangetoexistingfiltermodulesisrequired(althoughitmaybepossibletosimplifythem).

Page 1014: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SmartFiltering

Inthetraditionalfilteringmodel,filtersareinsertedunconditionallyusingAddOutputFilterandfamily.Eachfilterthenneedstodeterminewhethertorun,andthereislittleflexibilityavailableforserveradminstoallowthechaintobeconfigureddynamically.

mod_filterbycontrastgivesserveradministratorsagreatdealofflexibilityinconfiguringthefilterchain.Infact,filterscanbeinsertedbasedonanyRequestHeader,ResponseHeaderorEnvironmentVariable.ThisgeneralisesthelimitedflexibilityofferedbyAddOutputFilterByType,andfixesittoworkcorrectlywithdynamiccontent,regardlessofthecontentgenerator.TheabilitytodispatchbasedonEnvironmentVariablesoffersthefullflexibilityofconfigurationwithmod_rewritetoanyonewhoneedsit.

Page 1015: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FilterDeclarations,ProvidersandChains

Figure1:Thetraditionalfiltermodel

Inthetraditionalmodel,outputfiltersareasimplechainfromthecontentgenerator(handler)totheclient.Thisworkswellprovidedthefilterchaincanbecorrectlyconfigured,butpresentsproblemswhenthefiltersneedtobeconfigureddynamicallybasedontheoutcomeofthehandler.

Figure2:Themod_filtermodel

Page 1016: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_filterworksbyintroducingindirectionintothefilterchain.Insteadofinsertingfiltersinthechain,weinsertafilterharnesswhichinturndispatchesconditionallytoafilterprovider.Anycontentfiltermaybeusedasaprovidertomod_filter;nochangetoexistingfiltermodulesisrequired(althoughitmaybepossibletosimplifythem).Therecanbemultipleprovidersforonefilter,butnomorethanoneproviderwillrunforanysinglerequest.

Afilterchaincomprisesanynumberofinstancesofthefilterharness,eachofwhichmayhaveanynumberofproviders.Aspecialcaseisthatofasingleproviderwithunconditionaldispatch:thisisequivalenttoinsertingtheproviderfilterdirectlyintothechain.

Page 1017: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ConfiguringtheChain

Therearethreestagestoconfiguringafilterchainwithmod_filter.Fordetailsofthedirectives,seebelow.

DeclareFiltersTheFilterDeclaredirectivedeclaresafilter,assigningitanameandfiltertype.RequiredonlyifthefilterisnotthedefaulttypeAP_FTYPE_RESOURCE.

RegisterProvidersTheFilterProviderdirectiveregistersaproviderwithafilter.ThefiltermayhavebeendeclaredwithFilterDeclare;ifnot,FilterProviderwillimplicitlydeclareitwiththedefaulttypeAP_FTYPE_RESOURCE.Theprovidermusthavebeenregisteredwithap_register_output_filterbysomemodule.TheremainingargumentstoFilterProviderareadispatchcriterionandamatchstring.TheformermaybeanHTTPrequestorresponseheader,anenvironmentvariable,ortheHandlerusedbythisrequest.Thelatterismatchedtoitforeachrequest,todeterminewhetherthisproviderwillbeusedtoimplementthefilterforthisrequest.

ConfiguretheChainTheabovedirectivesbuildcomponentsofasmartfilterchain,butdonotconfigureittorun.TheFilterChaindirectivebuildsafilterchainfromsmartfiltersdeclared,offeringtheflexibilitytoinsertfiltersatthebeginningorendofthechain,removeafilter,orclearthechain.

Page 1018: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Examples

ServersideIncludes(SSI)Asimplecaseofusingmod_filterinplaceofAddOutputFilterByType

FilterDeclareSSI

FilterProviderSSIINCLUDESresp=Content-Type

$text/html

FilterChainSSI

ServersideIncludes(SSI)Thesameastheabovebutdispatchingonhandler(classicSSIbehaviour;.shtmlfilesgetprocessed).

FilterProviderSSIINCLUDESHandlerserver-

parsed

FilterChainSSI

Emulatingmod_gzipwithmod_deflateInsertINFLATEfilteronlyif"gzip"isNOTintheAccept-Encodingheader.ThisfilterrunswithftypeCONTENT_SET.

FilterDeclaregzipCONTENT_SET

FilterProvidergzipinflatereq=Accept-

Encoding!$gzip

FilterChaingzip

ImageDownsamplingSupposewewanttodownsampleallwebimages,andhavefiltersforGIF,JPEGandPNG.

FilterProviderunpackjpeg_unpackContent-Type

$image/jpeg

FilterProviderunpackgif_unpackContent-Type

Page 1019: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

$image/gif

FilterProviderunpackpng_unpackContent-Type

$image/png

FilterProviderdownsampledownsample_filter

Content-Type$image

FilterProtocoldownsample"change=yes"

FilterProviderrepackjpeg_packContent-Type

$image/jpeg

FilterProviderrepackgif_packContent-Type

$image/gif

FilterProviderrepackpng_packContent-Type

$image/png

<Location/image-filter>

FilterChainunpackdownsamplerepack

</Location>

Page 1020: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProtocolHandling

Historically,eachfilterisresponsibleforensuringthatwhateverchangesitmakesarecorrectlyrepresentedintheHTTPresponseheaders,andthatitdoesnotrunwhenitwouldmakeanillegalchange.Thisimposesaburdenonfilterauthorstore-implementsomecommonfunctionalityineveryfilter:

Manyfilterswillchangethecontent,invalidatingexistingcontenttags,checksums,hashes,andlengths.Filtersthatrequireanentire,unbrokenresponseininputneedtoensuretheydon'tgetbyterangesfromabackend.Filtersthattransformoutputinafilterneedtoensuretheydon'tviolateaCache-Control:no-transformheaderfromthebackend.Filtersmaymakeresponsesuncacheable.

mod_filteraimstooffergenerichandlingofthesedetailsoffilterimplementation,reducingthecomplexityrequiredofcontentfiltermodules.Thisiswork-in-progress;theFilterProtocolimplementssomeofthisfunctionalityforback-compatibilitywithApache2.0modules.Forhttpd2.1andlater,theap_register_output_filter_protocol

ap_filter_protocolAPIenablesfiltermodulestodeclaretheirownbehaviour.

Atthesametime,mod_filtershouldnotinterferewithafilterthatwantstohandleallaspectsoftheprotocol.Bydefault(i.e.intheabsenceofanyFilterProtocoldirectives),mod_filterwillleavetheheadersuntouched.

Atthetimeofwriting,thisfeatureislargelyuntested,asmodulesincommonusearedesignedtoworkwith2.0.Modulesusingitshouldtestitcarefully.

Page 1021: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FilterChain

ConfigurethefilterchainFilterChain[+=-@!]filter-name...

serverconfig,virtualhost,directory,.htaccessOptions(B)mod_filter

Thisconfiguresanactualfilterchain,fromdeclaredfilters.FilterChaintakesanynumberofarguments,eachoptionallyprecededwithasingle-charactercontrolthatdetermineswhattodo:

+filter-name

Addfilter-nametotheendofthefilterchain

@filter-name

Insertfilter-nameatthestartofthefilterchain

-filter-name

Removefilter-namefromthefilterchain

=filter-name

Emptythefilterchainandinsertfilter-name

!

Emptythefilterchain

filter-name

Equivalentto+filter-name

Page 1022: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FilterDeclare

DeclareasmartfilterFilterDeclarefilter-name[type]

serverconfig,virtualhost,directory,.htaccessOptions(B)mod_filter

Thisdirectivedeclaresanoutputfiltertogetherwithaheaderorenvironmentvariablethatwilldetermineruntimeconfiguration.Thefirstargumentisafilter-nameforuseinFilterProvider,FilterChainFilterProtocoldirectives.

Thefinal(optional)argumentisthetypeoffilter,andtakesvaluesofap_filter_type-namelyRESOURCE(thedefault),CONTENT_SET,PROTOCOL,TRANSCODE,CONNECTIONNETWORK.

Page 1023: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FilterProtocol

DealwithcorrectHTTPprotocolhandlingFilterProtocolfilter-name[provider-name]proto-

flags

serverconfig,virtualhost,directory,.htaccessOptions(B)mod_filter

Thisdirectsmod_filtertodealwithensuringthefilterdoesn'trunwhenitshouldn't,andthattheHTTPresponseheadersarecorrectlysettakingintoaccounttheeffectsofthefilter.

Therearetwoformsofthisdirective.Withthreearguments,itappliesspecificallytoafilter-nameandaprovider-nameforthatfilter.Withtwoargumentsitappliestoafilter-namewheneverthefilterrunsanyprovider.

proto-flagsisoneormoreof

change=yes

Thefilterchangesthecontent,includingpossiblythecontentlength

change=1:1

Thefilterchangesthecontent,butwillnotchangethecontentlength

byteranges=no

Thefiltercannotworkonbyterangesandrequirescompleteinput

proxy=no

Thefiltershouldnotruninaproxycontext

proxy=transform

ThefiltertransformstheresponseinamannerincompatiblewiththeHTTPCache-Control:no-transformheader.

Page 1024: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

cache=no

Thefilterrenderstheoutputuncacheable(egbyintroducingrandomisedcontentchanges)

Page 1025: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FilterProvider

RegisteracontentfilterFilterProviderfilter-nameprovider-name

[req|resp|env]=dispatchmatch

serverconfig,virtualhost,directory,.htaccessOptions(B)mod_filter

Thisdirectiveregistersaproviderforthesmartfilter.Theproviderwillbecalledifandonlyifthematchdeclaredherematchesthevalueoftheheaderorenvironmentvariabledeclaredasdispatch.

provider-namemusthavebeenregisteredbyloadingamodulethatregistersthenamewithap_register_output_filter.

dispatchargumentisastringwithoptionalreq=,resp=env=prefixcausingittodispatchon(respectively)therequestheader,responseheader,orenvironmentvariablenamed.Intheabsenceofaprefix,itdefaultstoaresponseheader.Aspecialcaseisthewordhandler,whichcausesmod_filtertodispatchonthecontenthandler.

matchargumentspecifiesamatchthatwillbeappliedtothefilter'sdispatchcriterion.Thematchmaybeastringmatch(exactmatchorsubstring),aregex,aninteger(greater,lessthanorequals),orunconditional.Thefirstcharactersofthematchargumentdeterminesthis:

First,ifthefirstcharacterisanexclamationmark(!),thisreversestherule,sotheproviderwillbeusedifandonlyifthematchfails.

Second,itinterpretsthefirstcharacterexcludinganyleading!asfollows:

Page 1026: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Character Description(none) exactmatch$ substringmatch/ regexmatch(delimitedbyasecond/)= integerequality< integerless-than<= integerless-thanorequal> integergreater-than>= integergreater-thanorequal* Unconditionalmatch

Page 1027: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

FilterTrace

Getdebug/diagnosticinformationfrommod_filterFilterTracefilter-namelevel

serverconfig,virtualhost,directory(B)mod_filter

Thisdirectivegeneratesdebuginformationfrommod_filter.Itisdesignedtohelptestanddebugproviders(filtermodules),althoughitmayalsohelpwithmod_filteritself.

Thedebugoutputdependsonthelevelset:

0(default)Nodebuginformationisgenerated.

1

mod_filterwillrecordbucketsandbrigadespassingthroughthefiltertotheerrorlog,beforetheproviderhasprocessedthem.Thisissimilartotheinformationgeneratedbymod_diagnostics.

2(notyetimplemented)Willdumpthefulldatapassingthroughtoatempfilebeforetheprovider.Forsingle-userdebugonly;thiswillnotsupportconcurrenthits.

Page 1028: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006125|

Page 1029: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_headers

HTTP(E)headers_modulemod_headers.cRequestHeaderApache2.0

HTTP

Page 1030: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_headers

RequestHeaderappendMirrorID"mirror12"

RequestHeaderunsetMirrorID

MirrorID MirrorID"mirror12"

Page 1031: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_headers""[whenRequestHeadersaresetimmediatelybeforerunningthecontentgeneratorandResponseHeadersjustastheresponseissentdownthewire.]""

""/ early""

""URL"" <Directory><Location>

Page 1032: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

1. "TS"

Headerecho^TS

2. MyHeader

HeaderaddMyHeader"%D%t"

MyHeader:D=3775428t=991424704447256

3. Joe(Hello)

HeaderaddMyHeader"HelloJoe.Ittook%D

microseconds\

forApachetoservethisrequest."

MyHeader:HelloJoe.IttookD=3775428

microsecondsforApachetoservethisrequest.

4. "MyRequestHeader"" MyHeader" mod_setenvif

SetEnvIfMyRequestHeadervalue

HAVE_MyRequestHeader

HeaderaddMyHeader"%D%tmytext"

env=HAVE_MyRequestHeader

" MyRequestHeader:value"

Page 1033: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MyHeader:D=3775428t=991424704447256mytext

Page 1034: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Header

HTTPHeader[condition]set|append|add|unset|echo

header[value][early|env=[!]variable]

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_headers

HTTP

conditiononsuccessalways(internalheader) onsuccess

" 2xx" always(" 2xx")

set

value

append

HTTP

add

() append

unset

() value

echo

headervalue

header() set,append,add,unset echoheader

add,append,set value value(") value value

%% (%)

Page 1035: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

%t (1970-1-100:00:00UCT)" t="%D " D="%{FOOBAR}e FOOBAR

%{FOOBAR}s SSLFOOBAR( mod_ssl)

"%s"Apache2.1" %e"" SSLOptions+StdEnvVars"" SSLOptions+StdEnvVars"" %e"" %s"

Header( early" ")" env=..." (" env=!...") Header

early Header

Page 1036: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

RequestHeader

HTTPRequestHeaderset|append|add|unsetheader[value]

[early|env=[!]variable]

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_headersApache2.0

HTTP

set

append

HTTP

add

() append

unset

() value

header() add,append,set value value(") unset

value value Header

RequestHeader( early" ")" env=..." (" env=!...")RequestHeader

early RequestHeaderApache

Page 1037: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006126|

Page 1038: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_ident

RFC1413ident(E)ident_modulemod_ident.cApache2.1

RFC1413

Page 1039: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IdentityCheck

RFC1413IdentityCheckOn|Off

IdentityCheckOff

serverconfig,virtualhost,directory(E)mod_identApache2.1

identd RFC1413(" %l")

IdentityCheckTimeout

Page 1040: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

IdentityCheckTimeout

identIdentityCheckTimeoutseconds

IdentityCheckTimeout30

serverconfig,virtualhost,directory(E)mod_ident

ident"30"() RFC1413

Page 1041: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1042: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_imagemap

(B)imagemap_modulemod_imagemap.c

Thismoduleprocesses.mapfiles,therebyreplacingthefunctionalityoftheimagemapCGIprogram.Anydirectoryordocumenttypeconfiguredtousethehandlerimap-file(usingeitherAddHandlerSetHandler)willbeprocessedbythismodule.

Thefollowingdirectivewillactivatefilesendingwith.mapasimagemapfiles:

AddHandlerimap-filemap

Notethatthefollowingisstillsupported:

AddTypeapplication/x-httpd-imapmap

However,wearetryingtophaseout"magicMIMEtypes"sowearedeprecatingthismethod.

Page 1043: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

NewFeatures

Theimagemapmoduleaddssomenewfeaturesthatwerenotpossiblewithpreviouslydistributedimagemapprograms.

URLreferencesrelativetotheReferer:information.Default<base>assignmentthroughanewmapdirectivebase.Noneedforimagemap.conffile.Pointreferences.Configurablegenerationofimagemapmenus.

Page 1044: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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,circlerectdirectives,andtherearenopointdirectives.DefaultstonocontentintheabsenceofanImapDefaultconfigurationsetting,causingastatuscodeof

Page 1045: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

204NoContenttobereturned.Theclientshouldkeepthesamepagedisplayed.

polyDirectiveTakesthreetoone-hundredpoints,andisobeyediftheuserselectedcoordinatesfallwithinthepolygondefinedbythesepoints.

circle

Takesthecentercoordinatesofacircleandapointonthecircle.Isobeyediftheuserselectedpointiswiththecircle.

rectDirectiveTakesthecoordinatesoftwoopposingcornersofarectangle.Obeyedifthepointselectediswithinthisrectangle.

pointDirectiveTakesasinglepoint.Thepointdirectiveclosesttotheuserselectedpointisobeyedifnootherdirectivesaresatisfied.Notethatdefaultwillnotbefollowedifapointdirectiveispresentandvalidcoordinatesaregiven.

ValuesThevaluesforeachofthedirectivescananyofthefollowing:

aURLTheURLcanberelativeorabsoluteURL.RelativeURLscancontain'..'syntaxandwillberesolvedrelativetothebasevalue.

baseitselfwillnotresolvedaccordingtothecurrentvalue.Astatementbasemailto:willworkproperly,though.

map

EquivalenttotheURLoftheimagemapfileitself.Nocoordinatesaresentwiththis,soamenuwillbegeneratedunlessImapMenuissettonone.

Page 1046: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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,thenameofthelinkwillbeusedasthetext:

<ahref="http://foo.com/">http://foo.com</a>

Page 1047: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Ifyouwanttousedoublequoteswithinthistext,youhavetowritethemas&quot;.

Page 1048: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ExampleMapfile

#Commentsareprintedina'formatted'or

'semiformatted'menu.

#Andcancontainhtmltags.<hr>

basereferer

polymap"CouldIhaveamenu,please?"0,00,10

10,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:[email protected],150200,0"Bugs?"

Page 1049: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Referencingyourmapfile

HTMLexample<ahref="/maps/imagemap1.map">

<imgismapsrc="/images/imagemap1.gif">

</a>

XHTMLexample<ahref="/maps/imagemap1.map">

<imgismap="ismap"src="/images/imagemap1.gif"

/>

</a>

Page 1050: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ImapBase

DefaultbaseforimagemapfilesImapBasemap|referer|URL

ImapBasehttp://servername/

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_imagemap

ImapBasedirectivesetsthedefaultbaseusedintheimagemapfiles.Itsvalueisoverriddenbyabasedirectivewithintheimagemapfile.Ifnotpresent,thebasedefaultstohttp://servername/.

UseCanonicalName

Page 1051: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ImapDefault

DefaultactionwhenanimagemapiscalledwithcoordinatesthatarenotexplicitlymappedImapDefaulterror|nocontent|map|referer|URL

ImapDefaultnocontent

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_imagemap

ImapDefaultdirectivesetsthedefaultdefaultusedintheimagemapfiles.Itsvalueisoverriddenbyadefaultdirectivewithintheimagemapfile.Ifnotpresent,thedefaultactionisnocontent,whichmeansthata204NoContentissenttotheclient.Inthiscase,theclientshouldcontinuetodisplaytheoriginalpage.

Page 1052: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ImapMenu

ActionifnocoordinatesaregivenwhencallinganimagemapImapMenunone|formatted|semiformatted|unformatted

serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_imagemap

ImapMenudirectivedeterminestheactiontakenifanimagemapfileiscalledwithoutvalidcoordinates.

none

IfImapMenuisnone,nomenuisgenerated,andthedefaultactionisperformed.

formatted

Aformattedmenuisthesimplestmenu.Commentsintheimagemapfileareignored.Aleveloneheaderisprinted,thenanhrule,thenthelinkseachonaseparateline.Themenuhasaconsistent,plainlookclosetothatofadirectorylisting.

semiformatted

Inthesemiformattedmenu,commentsareprintedwheretheyoccurintheimagemapfile.BlanklinesareturnedintoHTMLbreaks.Noheaderorhruleisprinted,butotherwisethemenuisthesameasaformattedmenu.

unformatted

Commentsareprinted,blanklinesareignored.Nothingisprintedthatdoesnotappearintheimagemapfile.Allbreaksandheadersmustbeincludedascommentsintheimagemapfile.Thisgivesyouthemostflexibilityovertheappearanceofyourmenus,butrequiresyoutotreatyourmapfilesasHTMLinsteadofplaintext.

Page 1053: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Page 1054: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1055: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_include

(SSI)(B)include_modulemod_include.cImplementedasanoutputfiltersinceApache2.0

Thismoduleprovidesafilterwhichwillprocessfilesbeforetheyaresenttotheclient.TheprocessingiscontrolledbyspeciallyformattedSGMLcomments,referredtoaselements.Theseelementsallowconditionaltext,theinclusionofotherfilesorprograms,aswellasthesettingandprintingofenvironmentvariables.

Page 1056: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

EnablingServer-SideIncludes

ServerSideIncludesareimplementedbytheINCLUDESfilter.Ifdocumentscontainingserver-sideincludedirectivesaregiventheextension.shtml,thefollowingdirectiveswillmakeApacheparsethemandassigntheresultingdocumentthemimetypeoftext/html:

AddTypetext/html.shtml

AddOutputFilterINCLUDES.shtml

Thefollowingdirectivemustbegivenforthedirectoriescontainingtheshtmlfiles(typicallyina<Directory>section,butthisdirectiveisalsovalidin.htaccessfilesifAllowOverrideOptionsisset):

Options+Includes

Forbackwardscompatibility,theserver-parsedalsoactivatestheINCLUDESfilter.Aswell,ApachewillactivatetheINCLUDESfilterforanydocumentwithmimetypetext/x-server-parsed-htmltext/x-server-parsed-html3(andtheresultingoutputwillhavethemimetypetext/html).

Formoreinformation,seeourTutorialonServerSideIncludes.

Page 1057: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

PATH_INFOwithServerSideIncludes

Filesprocessedforserver-sideincludesnolongeracceptrequestswithPATH_INFO(trailingpathnameinformation)bydefault.YoucanusetheAcceptPathInfodirectivetoconfiguretheservertoacceptrequestswithPATH_INFO.

Page 1058: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

BasicElements

ThedocumentisparsedasanHTMLdocument,withspecialcommandsembeddedasSGMLcomments.Acommandhasthesyntax:

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

->

Thevaluewilloftenbeenclosedindoublequotes,butsinglequotes(')andbackticks(`)arealsopossible.Manycommandsonlyallowasingleattribute-valuepair.Notethatthecommentterminator(-->)shouldbeprecededbywhitespacetoensurethatitisn'tconsideredpartofanSSItoken.Notethattheleading<!--#isonetokenandmaynotcontainanywhitespaces.

Theallowedelementsarelistedinthefollowingtable:

Element Descriptionconfig configureoutputformatsecho printvariablesexec executeexternalprogramsfsize printsizeofafileflastmod printlastmodificationtimeofafileinclude includeafileprintenv printallavailablevariablesset setavalueofavariable

SSIelementsmaybedefinedbymodulesotherthanmod_include.Infact,theexecelementisprovidedbymod_cgi,andwillonlybeavailableifthismoduleisloaded.

TheconfigElement

Page 1059: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Thiscommandcontrolsvariousaspectsoftheparsing.Thevalidattributesare:

echomsg(Apache2.1andlater)Thevalueisamessagethatissentbacktotheclientiftheechoelementattemptstoechoanundefinedvariable.ThisoverridesanySSIUndefinedEchodirectives.

errmsg

Thevalueisamessagethatissentbacktotheclientifanerroroccurswhileparsingthedocument.ThisoverridesanySSIErrorMsgdirectives.

sizefmt

Thevaluesetstheformattobeusedwhichdisplayingthesizeofafile.Validvaluesarebytesforacountinbytes,orabbrevforacountinKborMbasappropriate,forexampleasizeof1024byteswillbeprintedas"1K".

timefmt

Thevalueisastringtobeusedbythestrftime(3)libraryroutinewhenprintingdates.

TheechoElementThiscommandprintsoneoftheincludevariables,definedbelow.Ifthevariableisunset,theresultisdeterminedbytheSSIUndefinedEchodirective.Anydatesprintedaresubjecttothecurrentlyconfiguredtimefmt.

Attributes:

var

Thevalueisthenameofthevariabletoprint.

encoding

SpecifieshowApacheshouldencodespecialcharacterscontainedinthevariablebeforeoutputtingthem.Ifsettonone,

Page 1060: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

noencodingwillbedone.Ifsettourl,thenURLencoding(alsoknownas%-encoding;thisisappropriateforusewithinURLsinlinks,etc.)willbeperformed.Atthestartofanechoelement,thedefaultissettoentity,resultinginentityencoding(whichisappropriateinthecontextofablock-levelHTMLelement,aparagraphoftext).Thiscanbechangedbyaddinganencodingattribute,whichwillremainineffectuntilthenextencodingattributeisencounteredortheelementends,whichevercomesfirst.

encodingattributemustprecedethecorrespondingvarattributetobeeffective,andonlyspecialcharactersasdefinedintheISO-8859-1characterencodingwillbeencoded.Thisencodingprocessmaynothavethedesiredresultifadifferentcharacterencodingisinuse.

Inordertoavoidcross-sitescriptingissues,youshouldalwaysencodeusersupplieddata.

TheexecElementexeccommandexecutesagivenshellcommandorCGIscript.Itrequiresmod_cgitobepresentintheserver.IfOptionsIncludesNOEXECisset,thiscommandiscompletelydisabled.Thevalidattributesare:

cgi

Thevaluespecifiesa(%-encoded)URL-pathtotheCGIscript.Ifthepathdoesnotbeginwithaslash(/),thenitistakentoberelativetothecurrentdocument.ThedocumentreferencedbythispathisinvokedasaCGIscript,eveniftheserverwouldnotnormallyrecognizeitassuch.However,thedirectorycontainingthescriptmustbeenabledforCGIscripts(withScriptAliasOptionsExecCGI).

Page 1061: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TheCGIscriptisgiventhePATH_INFOandquerystring(QUERY_STRING)oftheoriginalrequestfromtheclient;thesecannotbespecifiedintheURLpath.TheincludevariableswillbeavailabletothescriptinadditiontothestandardCGIenvironment.

<!--#execcgi="/cgi-bin/example.cgi"-->

IfthescriptreturnsaLocation:headerinsteadofoutput,thenthiswillbetranslatedintoanHTMLanchor.

includevirtualelementshouldbeusedinpreferencetoexeccgi.Inparticular,ifyouneedtopassadditionalargumentstoaCGIprogram,usingthequerystring,thiscannotbedonewithexeccgi,butcanbedonewithincludevirtual,asshownhere:

<!--#includevirtual="/cgi-bin/example.cgi?

argument=value"-->

cmd

Theserverwillexecutethegivenstringusing/bin/sh.Theincludevariablesareavailabletothecommand,inadditiontotheusualsetofCGIvariables.

Theuseof#includevirtualisalmostalwayspreferedtousingeither#execcgi#execcmd.Theformer(#includevirtual)usesthestandardApachesub-requestmechanismtoincludefilesorscripts.Itismuchbettertestedandmaintained.

Inaddition,onsomeplatforms,likeWin32,andonunixwhenusingsuexec,youcannotpassargumentstoacommandinanexecdirective,orotherwiseincludespacesinthecommand.

Page 1062: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Thus,whilethefollowingwillworkunderanon-suexecconfigurationonunix,itwillnotproducethedesiredresultunderWin32,orwhenrunningsuexec:

<!--#execcmd="perl/path/to/perlscriptarg1

arg2"-->

ThefsizeElementThiscommandprintsthesizeofthespecifiedfile,subjecttothesizefmtformatspecification.Attributes:

file

Thevalueisapathrelativetothedirectorycontainingthecurrentdocumentbeingparsed.

virtual

Thevalueisa(%-encoded)URL-path.Ifitdoesnotbeginwithaslash(/)thenitistakentoberelativetothecurrentdocument.Note,thatthisdoesnotprintthesizeofanyCGIoutput,butthesizeoftheCGIscriptitself.

TheflastmodElementThiscommandprintsthelastmodificationdateofthespecifiedfile,subjecttothetimefmtformatspecification.Theattributesarethesameasforthefsizecommand.

TheincludeElementThiscommandinsertsthetextofanotherdocumentorfileintotheparsedfile.Anyincludedfileissubjecttotheusualaccesscontrol.IfthedirectorycontainingtheparsedfilehasOptionsIncludesNOEXECset,thenonlydocumentswithatextMIME-type(text/plain,text/htmletc.)willbeincluded.OtherwiseCGIscriptsareinvokedasnormalusingthecompleteURLgiveninthe

Page 1063: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

command,includinganyquerystring.

Anattributedefinesthelocationofthedocument;theinclusionisdoneforeachattributegiventotheincludecommand.Thevalidattributesare:

file

Thevalueisapathrelativetothedirectorycontainingthecurrentdocumentbeingparsed.Itcannotcontain../,norcanitbeanabsolutepath.Therefore,youcannotincludefilesthatareoutsideofthedocumentroot,orabovethecurrentdocumentinthedirectorystructure.Thevirtualattributeshouldalwaysbeusedinpreferencetothisone.

virtual

Thevalueisa(%-encoded)URL-path.TheURLcannotcontainaschemeorhostname,onlyapathandanoptionalquerystring.Ifitdoesnotbeginwithaslash(/)thenitistakentoberelativetothecurrentdocument.

AURLisconstructedfromtheattribute,andtheoutputtheserverwouldreturniftheURLwereaccessedbytheclientisincludedintheparsedoutput.Thusincludedfilescanbenested.

IfthespecifiedURLisaCGIprogram,theprogramwillbeexecutedanditsoutputinsertedinplaceofthedirectiveintheparsedfile.YoumayincludeaquerystringinaCGIurl:

<!--#includevirtual="/cgi-bin/example.cgi?

argument=value"-->

includevirtualshouldbeusedinpreferencetoexeccgitoincludetheoutputofCGIprogramsintoanHTMLdocument.

TheprintenvElement

Page 1064: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Thisprintsoutalistingofallexistingvariablesandtheirvalues.Specialcharactersareentityencoded(seetheechoelementfordetails)beforebeingoutput.Therearenoattributes.

<!--#printenv-->

ThesetElementThissetsthevalueofavariable.Attributes:

var

Thenameofthevariabletoset.

value

Thevaluetogiveavariable.

<!--#setvar="category"value="help"-->

Page 1065: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IncludeVariables

InadditiontothevariablesinthestandardCGIenvironment,theseareavailablefortheechocommand,forifelif,andtoanyprograminvokedbythedocument.

DATE_GMT

ThecurrentdateinGreenwichMeanTime.

DATE_LOCAL

Thecurrentdateinthelocaltimezone.

DOCUMENT_NAME

Thefilename(excludingdirectories)ofthedocumentrequestedbytheuser.

DOCUMENT_URI

The(%-decoded)URLpathofthedocumentrequestedbytheuser.Notethatinthecaseofnestedincludefiles,thisisnottheURLforthecurrentdocument.

LAST_MODIFIED

Thelastmodificationdateofthedocumentrequestedbytheuser.

QUERY_STRING_UNESCAPED

Ifaquerystringispresent,thisvariablecontainsthe(%-decoded)querystring,whichisescapedforshellusage(specialcharacterslike&etc.areprecededbybackslashes).

Page 1066: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

VariableSubstitution

VariablesubstitutionisdonewithinquotedstringsinmostcaseswheretheymayreasonablyoccurasanargumenttoanSSIdirective.Thisincludestheconfig,exec,flastmod,fsize,include,echo,andsetdirectives,aswellastheargumentstoconditionaloperators.Youcaninsertaliteraldollarsignintothestringusingbackslashquoting:

<!--#ifexpr="$a=\$test"-->

Ifavariablereferenceneedstobesubstitutedinthemiddleofacharactersequencethatmightotherwisebeconsideredavalididentifierinitsownright,itcanbedisambiguatedbyenclosingthereferenceinbraces,alashellsubstitution:

<!--#setvar="Zed"

value="${REMOTE_HOST}_${REQUEST_METHOD}"-->

ThiswillresultintheZedvariablebeingsetto"X_Y"ifREMOTE_HOSTis"X"andREQUEST_METHODis"Y".

Thebelowexamplewillprint"infoo"iftheDOCUMENT_URIis/foo/file.html,"inbar"ifitis/bar/file.htmland"inneither"otherwise:

<!--#ifexpr='"$DOCUMENT_URI"="/foo/file.html"'

-->

infoo

<!--#elifexpr='"$DOCUMENT_URI"=

"/bar/file.html"'-->

inbar

<!--#else-->

inneither

<!--#endif-->

Page 1067: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 1068: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FlowControlElements

Thebasicflowcontrolelementsare:

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

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

<!--#else-->

<!--#endif-->

ifelementworkslikeanifstatementinaprogramminglanguage.Thetestconditionisevaluatedandiftheresultistrue,thenthetextuntilthenextelif,elseendifelementisincludedintheoutputstream.

elifelsestatementsarebeusedtoputtextintotheoutputstreamiftheoriginaltest_conditionwasfalse.Theseelementsareoptional.

endifelementendstheifelementandisrequired.

test_conditionisoneofthefollowing:

string

trueifstringisnotempty

string1=string2

string1==string2

string1!=string2

Comparestring1withstring2.Ifstring2hastheform/string2/thenitistreatedasaregularexpression.RegularexpressionsareimplementedbythePCREengineandhavethesamesyntaxasthoseinperl5.Notethat==isjustanaliasfor=andbehavesexactlythesameway.

Ifyouarematchingpositive(===),youcancapturegroupedpartsoftheregularexpression.Thecapturedpartsarestoredinthespecialvariables$1..$9.

Page 1069: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<!--#ifexpr="$QUERY_STRING=/^sid=([a-zA-Z0-

9]+)/"-->

<!--#setvar="session"value="$1"-->

<!--#endif-->

string1<string2

string1<=string2

string1>string2

string1>=string2

Comparestring1withstring2.Note,thatstringsarecomparedliterally(usingstrcmp(3)).Thereforethestring"100"islessthan"20".

(test_condition)

trueiftest_conditionistrue

!test_condition

trueiftest_conditionisfalse

test_condition1&&test_condition2

trueifbothtest_condition1test_condition2aretrue

test_condition1||test_condition2

trueifeithertest_condition1test_condition2istrue

"="and"!="bindmoretightlythan"&&"and"||"."!"bindsmosttightly.Thus,thefollowingareequivalent:

<!--#ifexpr="$a=test1&&$b=test2"-->

<!--#ifexpr="($a=test1)&&($b=test2)"-->

Thebooleanoperators&&||sharethesamepriority.Soifyouwanttobindsuchanoperatormoretightly,youshoulduseparentheses.

Anythingthat'snotrecognizedasavariableoranoperatoristreatedasastring.Stringscanalsobequoted:'string'.Unquotedstrings

Page 1070: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

can'tcontainwhitespace(blanksandtabs)becauseitisusedtoseparatetokenssuchasvariables.Ifmultiplestringsarefoundinarow,theyareconcatenatedusingblanks.So,

string1string2resultsinstring1string2

'string1string2'resultsinstring1string2.

OptimizationofBooleanExpressions

Iftheexpressionsbecomemorecomplexandslowdownprocessingsignificantly,youcantrytooptimizethemaccordingtotheevaluationrules:

ExpressionsareevaluatedfromlefttorightBinarybooleanoperators(&&||)areshortcircuitedwhereverpossible.Inconclusionwiththeruleabovethatmeans,mod_includeevaluatesatfirsttheleftexpression.Iftheleftresultissufficienttodeterminetheendresult,processingstopshere.Otherwiseitevaluatestherightsideandcomputestheendresultfrombothleftandrightresults.Shortcircuitevaluationisturnedoffaslongasthereareregularexpressionstodealwith.Thesemustbeevaluatedtofillinthebackreferencevariables($1..$9).

Ifyouwanttolookhowaparticularexpressionishandled,youcanrecompilemod_includeusingthe-DDEBUG_INCLUDEcompileroption.Thisinsertsforeveryparsedexpressiontokenizerinformation,theparsetreeandhowitisevaluatedintotheoutputsenttotheclient.

Page 1071: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSIEndTag

StringthatendsanincludeelementSSIEndTagtag

SSIEndTag"-->"

serverconfig,virtualhost(B)mod_includeApache2.0.30

Thisdirectivechangesthestringthatmod_includelooksfortomarktheendofanincludeelement.

SSIEndTag"%>"

SSIStartTag

Page 1072: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSIErrorMsg

ErrormessagedisplayedwhenthereisanSSIerrorSSIErrorMsgmessage

SSIErrorMsg"[anerroroccurredwhileprocessing

thisdirective]"

serverconfig,virtualhost,directory,.htaccessAll(B)mod_includeApache2.0.30

SSIErrorMsgdirectivechangestheerrormessagedisplayedwhenmod_includeencountersanerror.Forproductionserversyoumayconsiderchangingthedefaulterrormessageto"<!--Error-->"sothatthemessageisnotpresentedtotheuser.

Thisdirectivehasthesameeffectasthe<!--#configerrmsg=message-->element.

SSIErrorMsg"<!--Error-->"

Page 1073: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSIStartTag

StringthatstartsanincludeelementSSIStartTagtag

SSIStartTag"<!--#"

serverconfig,virtualhost(B)mod_includeApache2.0.30

Thisdirectivechangesthestringthatmod_includelooksfortomarkanincludeelementtoprocess.

Youmaywanttousethisoptionifyouhave2serversparsingtheoutputofafileeachprocessingdifferentcommands(possiblyatdifferenttimes).

SSIStartTag"<%"

SSIEndTag"%>"

Theexamplegivenabove,whichalsospecifiesamatchingSSIEndTag,willallowyoutouseSSIdirectivesasshownintheexamplebelow:

SSIdirectiveswithalternatestartandendtags<%printenv%>

SSIEndTag

Page 1074: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSITimeFormat

ConfigurestheformatinwhichdatestringsaredisplayedSSITimeFormatformatstring

SSITimeFormat"%A,%d-%b-%Y%H:%M:%S%Z"

serverconfig,virtualhost,directory,.htaccessAll(B)mod_includeApache2.0.30

ThisdirectivechangestheformatinwhichdatestringsaredisplayedwhenechoingDATEenvironmentvariables.Theformatstringisasinstrftime(3)fromtheCstandardlibrary.

Thisdirectivehasthesameeffectasthe<!--#configtimefmt=formatstring-->element.

SSITimeFormat"%R,%B%d,%Y"

Theabovedirectivewouldcausetimestobedisplayedintheformat"22:26,June14,2002".

Page 1075: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSIUndefinedEcho

StringdisplayedwhenanunsetvariableisechoedSSIUndefinedEchostring

SSIUndefinedEcho"(none)"

serverconfig,virtualhost,directory,.htaccessAll(B)mod_includeApache2.0.34

Thisdirectivechangesthestringthatmod_includedisplayswhenavariableisnotsetand"echoed".

SSIUndefinedEcho"<!--undef-->"

Page 1076: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

XBitHack

ParseSSIdirectivesinfileswiththeexecutebitsetXBitHackon|off|full

XBitHackoff

serverconfig,virtualhost,directory,.htaccessOptions(B)mod_include

XBitHackdirectivecontrolstheparsingofordinaryhtmldocuments.ThisdirectiveonlyaffectsfilesassociatedwiththeMIME-typetext/html.XBitHackcantakeonthefollowingvalues:

off

Nospecialtreatmentofexecutablefiles.

on

Anytext/htmlfilethathastheuser-executebitsetwillbetreatedasaserver-parsedhtmldocument.

full

Asforonbutalsotestthegroup-executebit.Ifitisset,thensettheLast-modifieddateofthereturnedfiletobethelastmodifiedtimeofthefile.Ifitisnotset,thennolast-modifieddateissent.Settingthisbitallowsclientsandproxiestocachetheresultoftherequest.

Youwouldnotwanttousethefulloption,unlessyouassurethegroup-executebitisunsetforeverySSIscriptwhichmight#includeaCGIorotherwiseproducesdifferentoutputoneachhit(orcouldpotentiallychangeonsubsequentrequests).

Page 1077: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006321|

Page 1078: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_info

ApacheWeb(E)info_modulemod_info.c

mod_infohttpd.conf

<Location/server-info>

SetHandlerserver-info

</Location>

<Location>mod_authz_host

<Location/server-info>

SetHandlerserver-info

Orderdeny,allow

Denyfromall

Allowfromyourcompany.com

</Location>

http://your.host.example.com/server-info

Page 1079: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_info .htaccess

/

mod_authz_host

<Location/server-info>

SetHandlerserver-info

Orderallow,deny

#

Allowfrom127.0.0.1

#

Allowfrom192.168.1.17

</Location>

Page 1080: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

server-info http://your.host.example.com/server-

info?config

?<module-name>

?config

?hooks

(Hook)

?list

?server

Page 1081: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_info

ServerRoot,LoadModule,LoadFileInclude,<IfModule>,<IfDefine> Include

.htaccess

mod_info</Directory>

( mod_ssl)

Page 1082: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

AddModuleInfo

server-infoAddModuleInfomodule-namestring

serverconfig,virtualhost(E)mod_infoApache1.3

stringmodule-nameHTML

AddModuleInfomod_deflate.c'See<a\

href="http://www.apache.org/docs/2.2/mod/mod_deflate.html">\

http://www.apache.org/docs/2.2/mod/mod_deflate.html</a>'

Page 1083: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006126|

Page 1084: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_isapi

WindowsISAPI(B)isapi_modulemod_isapi.cWin32

(InternetServerextensionAPI)WindowsApache(ISAPI)

ISAPI(.dll)ApacheISAPIISAPI Apache

Page 1085: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddHandlerisapi-isaISAPI.dllISAPIhttpd.conf

AddHandlerisapi-isa.dll

Apachehttpd.confApache

ISAPICacheFilec:/WebWork/Scripts/ISAPI/mytest.dll

ISAPIISAPICGIISAPI" OptionsExecCGI"

mod_isapiISAPI

Page 1086: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheISAPII/O(Microsoft-specific)ISAPI2.0ApacheI/OISAPIISAPII/O"

IISISAPIApacheISAPI ISAPICacheFile

ApacheISAPIApache

ApacheISAPI ISAPIISAPI

Page 1087: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.0 mod_isapi ServerSupportFunction

HSE_REQ_SEND_URL_REDIRECT_RESP

URL( http://server/location)

HSE_REQ_SEND_URL

URL( /location)

HSE_REQ_SEND_URLApache

HSE_REQ_SEND_RESPONSE_HEADER

()ApacheNULLNULL

HSE_REQ_DONE_WITH_SESSION

ApacheISAPI

HSE_REQ_MAP_URL_TO_PATH

Apache

HSE_APPEND_LOG_PARAMETER

CustomLog \"%{isapi-parameter}n\"" ISAPIAppendLogToQueryOn"" %q"" ISAPIAppendLogToErrorsOn"

%{isapi-parameter}n

HSE_REQ_IS_KEEP_CONN

Keep-Alive

HSE_REQ_SEND_RESPONSE_HEADER_EX

fKeepConn

HSE_REQ_IS_CONNECTED

Page 1088: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerSupportFunctionApache FALSEGetLastErrorERROR_INVALID_PARAMETER

ReadClient( ISAPIReadAheadBuffer)ISAPIReadAheadBuffer(ISAPI)ISAPIISAPIReadClient

WriteClientHSE_IO_SYNC("0") WriteClient FALSEGetLastErrorERROR_INVALID_PARAMETER

GetServerVariable() ALL_HTTPALL_RAWApacheCGIGetServerVariable

Apache2.0mod_isapiISAPII/O TransmitFileApacheISAPI.dllsApache1.3 mod_isapi

Page 1089: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ISAPIAppendLogToErrors

ISAPIHSE_APPEND_LOG_PARAMETERISAPIAppendLogToErrorson|off

ISAPIAppendLogToErrorsoff

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi

ISAPIHSE_APPEND_LOG_PARAMETER

Page 1090: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ISAPIAppendLogToQuery

ISAPIHSE_APPEND_LOG_PARAMETERISAPIAppendLogToQueryon|off

ISAPIAppendLogToQueryon

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi

ISAPIHSE_APPEND_LOG_PARAMETER( CustomLog%q)

Page 1091: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ISAPICacheFile

ISAPIISAPICacheFilefile-path[file-path]...

serverconfig,virtualhost(B)mod_isapi

ApacheISAPI ServerRoot

Page 1092: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ISAPIFakeAsync

ISAPIISAPIFakeAsyncon|off

ISAPIFakeAsyncoff

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi

onISAPI

Page 1093: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ISAPILogNotSupported

ISAPIISAPILogNotSupportedon|off

ISAPILogNotSupportedoff

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi

ISAPIonISAPIOff

Page 1094: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ISAPIReadAheadBuffer

ISAPIISAPIReadAheadBuffersize

ISAPIReadAheadBuffer49152

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi

ISAPI ReadClientISAPI ReadClientISAPI

Page 1095: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |???|

Page 1096: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_ldap

LDAPLDAP(E)ldap_moduleutil_ldap.cApache2.0.41

LDAPLDAPLDAPLDAP

LDAPAPUApache configure --with-ldap

SSL/TLSAPRLDAPSDKOpenLDAPSDK(2.x), NovellLDAPSDK,MozillaLDAPSDK,SolarisLDAPSDK(Mozilla),MicrosoftLDAPSDK,iPlanet(Netscape)SDKAPR

Page 1097: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_ldapmod_authnz_ldapHTTP

#LDAP

#LDAPmod_ldapmod_authnz_ldap

#"yourdomain.example.com"

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>

Page 1098: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAP

LDAPLDAPunbind->connect->rebindHTTPKeep-Alives

LDAPLDAPApache

ApacheLDAP

Page 1099: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAP

mod_ldapLDAPApachemod_authnz_ldapLDAP

mod_ldapLDAPsearch/bind search/bindcompare operationLDAPURL

Search/BindLDAPSearch/bind()

mod_ldapDN mod_ldap mod_ldap

search/bind

LDAPCacheEntriesLDAPCacheTTL

Operationmod_ldapLDAP

LDAPOpCacheEntriesLDAPOpCacheTTL

mod_ldap ldap-statusmod_ldap

<Location/server/cache-info>

SetHandlerldap-status

</Location>

URLhttp://servername/cache-infomod_ldapApache httpdURL httpd

Page 1100: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL/TSL

LDAPTrustedGlobalCert,LDAPTrustedClientCert,LDAPTrustedModeLDAPSSL/TSLCA(none,SSL,TLS/STARTTLS)

#636SSLLDAPmod_ldapmod_authnz_ldap

#"yourdomain.example.com"

LDAPTrustedGlobalCertCA_DER/certs/certfile.der

<Location/ldap-status>

SetHandlerldap-status

Orderdeny,allow

Denyfromall

Allowfromyourdomain.example.com

AuthLDAPEnabledon

AuthLDAPURL

ldaps://127.0.0.1/dc=example,dc=com?uid?one

AuthLDAPAuthoritativeon

requirevalid-user

</Location>

#389TLSLDAPmod_ldapmod_authnz_ldap

#"yourdomain.example.com"

LDAPTrustedGlobalCertCA_DER/certs/certfile.der

<Location/ldap-status>

SetHandlerldap-status

Orderdeny,allow

Denyfromall

Allowfromyourdomain.example.com

AuthLDAPEnabledon

LDAPTrustedModeTLSAuthLDAPURL

ldap://127.0.0.1/dc=example,dc=com?uid?one

AuthLDAPAuthoritativeon

Page 1101: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

requirevalid-user

</Location>

Page 1102: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL/TLSCertificates

ThedifferentLDAPSDKshavewidelydifferentmethodsofsettingandhandlingbothCAandclientsidecertificates.

IfyouintendtouseSSLorTLS,readthissectionCAREFULLYsoastounderstandthedifferencesbetweenconfigurationsonthedifferentLDAPtoolkitssupported.

Netscape/Mozilla/iPlanetSDKCAcertificatesarespecifiedwithinafilecalledcert7.db.TheSDKwillnottalktoanyLDAPserverwhosecertificatewasnotsignedbyaCAspecifiedinthisfile.Ifclientcertificatesarerequired,anoptionalkey3.dbfilemaybespecifiedwithanoptionalpassword.Thesecmodfilecanbespecifiedifrequired.ThesefilesareinthesameformatasusedbytheNetscapeCommunicatororMozillawebbrowsers.Theeasiestwaytoobtainthesefilesistograbthemfromyourbrowserinstallation.

ClientcertificatesarespecifiedperconnectionusingtheLDAPTrustedClientCertdirectivebyreferringtothecertificate"nickname".Anoptionalpasswordmaybespecifiedtounlockthecertificate'sprivatekey.

TheSDKsupportsSSLonly.AnattempttouseSTARTTLSwillcauseanerrorwhenanattemptismadetocontacttheLDAPserveratruntime.

#SpecifyaNetscapeCAcertificatefile

LDAPTrustedGlobalCertCA_CERT7_DB/certs/cert7.db

#Specifyanoptionalkey3.dbfileforclient

certificatesupport

LDAPTrustedGlobalCertCERT_KEY3_DB/certs/key3.db

#Specifythesecmodfileifrequired

LDAPTrustedGlobalCertCA_SECMOD/certs/secmod

<Location/ldap-status>

Page 1103: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SetHandlerldap-status

Orderdeny,allow

Denyfromall

Allowfromyourdomain.example.com

AuthLDAPEnabledon

LDAPTrustedClientCertCERT_NICKNAME<nickname>

[password]

AuthLDAPURL

ldaps://127.0.0.1/dc=example,dc=com?uid?one

AuthLDAPAuthoritativeon

requirevalid-user

</Location>

NovellSDKOneormoreCAcertificatesmustbespecifiedfortheNovellSDKtoworkcorrectly.ThesecertificatescanbespecifiedasbinaryDERorBase64(PEM)encodedfiles.

Note:Clientcertificatesarespecifiedgloballyratherthanperconnection,andsomustbespecifiedwiththeLDAPTrustedGlobalCertdirectiveasbelow.TryingtosetclientcertificatesviatheLDAPTrustedClientCertdirectivewillcauseanerrortobeloggedwhenanattemptismadetoconnecttotheLDAPserver..

TheSDKsupportsbothSSLandSTARTTLS,setusingtheLDAPTrustedModeparameter.Ifanldaps://URLisspecified,SSLmodeisforced,overridethisdirective.

#SpecifytwoCAcertificatefiles

LDAPTrustedGlobalCertCA_DER/certs/cacert1.der

LDAPTrustedGlobalCertCA_BASE64/certs/cacert2.pem

#Specifyaclientcertificatefileandkey

LDAPTrustedGlobalCertCERT_BASE64/certs/cert1.pem

LDAPTrustedGlobalCertKEY_BASE64/certs/key1.pem

Page 1104: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

[password]

#Donotusethisdirective,asitwillthrowan

error

#LDAPTrustedClientCertCERT_BASE64

/certs/cert1.pem

OpenLDAPSDKOneormoreCAcertificatesmustbespecifiedfortheOpenLDAPSDKtoworkcorrectly.ThesecertificatescanbespecifiedasbinaryDERorBase64(PEM)encodedfiles.

ClientcertificatesarespecifiedperconnectionusingtheLDAPTrustedClientCertdirective.

ThedocumentationfortheSDKclaimstosupportbothSSLandSTARTTLS,howeverSTARTTLSdoesnotseemtoworkonallversionsoftheSDK.TheSSL/TLSmodecanbesetusingtheLDAPTrustedModeparameter.Ifanldaps://URLisspecified,SSLmodeisforced.TheOpenLDAPdocumentationnotesthatSSL(ldaps://)supporthasbeendeprecatedtobereplacedwithTLS,althoughtheSSLfunctionalitystillworks.

#SpecifytwoCAcertificatefiles

LDAPTrustedGlobalCertCA_DER/certs/cacert1.der

LDAPTrustedGlobalCertCA_BASE64/certs/cacert2.pem

<Location/ldap-status>

SetHandlerldap-status

Orderdeny,allow

Denyfromall

Allowfromyourdomain.example.com

AuthLDAPEnabledon

LDAPTrustedClientCertCERT_BASE64

/certs/cert1.pem

LDAPTrustedClientCertKEY_BASE64

/certs/key1.pem

Page 1105: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthLDAPURL

ldaps://127.0.0.1/dc=example,dc=com?uid?one

AuthLDAPAuthoritativeon

requirevalid-user

</Location>

SolarisSDKSSL/TLSforthenativeSolarisLDAPlibrariesisnotyetsupported.Ifrequired,installandusetheOpenLDAPlibrariesinstead.

MicrosoftSDKSSL/TLScertificateconfigurationforthenativeMicrosoftLDAPlibrariesisdoneinsidethesystemregistry,andnoconfigurationdirectivesarerequired.

BothSSLandTLSaresupportedbyusingtheldaps://URLformat,orbyusingtheLDAPTrustedModedirectiveaccordingly.

Note:Thestatusofsupportforclientcertificatesisnotyetknownforthistoolkit.

Page 1106: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPCacheEntries

LDAPLDAPCacheEntriesnumber

LDAPCacheEntries1024

serverconfig(E)mod_ldap

LDAPsearch/bind0search/bind1024

Page 1107: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPCacheTTL

search/bindLDAPCacheTTLseconds

LDAPCacheTTL600

serverconfig(E)mod_ldap

search/bind600(10)

Page 1108: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPConnectionTimeout

LDAPConnectionTimeoutseconds

serverconfig(E)mod_ldap

Specifiesthetimeoutvalue(inseconds)inwhichthemodulewillattempttoconnecttotheLDAPserver.Ifaconnectionisnotsuccessfulwiththetimeoutperiod,eitheranerrorwillbereturnedorthemodulewillattempttoconnecttoasecondaryLDAPserverifoneisspecified.Thedefaultis10seconds.

Page 1109: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPOpCacheEntries

LDAPcompareLDAPOpCacheEntriesnumber

LDAPOpCacheEntries1024

serverconfig(E)mod_ldap

mod_ldapLDAPcompare10240

Page 1110: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPOpCacheTTL

LDAPOpCacheTTLseconds

LDAPOpCacheTTL600

serverconfig(E)mod_ldap

600

Page 1111: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPSharedCacheFile

LDAPSharedCacheFiledirectory-path/filename

serverconfig(E)mod_ldap

()

Page 1112: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPSharedCacheSize

LDAPSharedCacheSizebytes

LDAPSharedCacheSize102400

serverconfig(E)mod_ldap

Byte100KB

Page 1113: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPTrustedClientCert

Setsthefilecontainingornicknamereferringtoaperconnectionclientcertificate.NotallLDAPtoolkitssupportperconnectionclientcertificates.LDAPTrustedClientCerttypedirectory-

path/filename/nickname[password]

serverconfig,virtualhost,directory,.htaccess(E)mod_ldap

Itspecifiesthedirectorypath,filenameornicknameofaperconnectionclientcertificateusedwhenestablishinganSSLorTLSconnectiontoanLDAPserver.Differentlocationsordirectoriesmayhavetheirownindependantclientcertificatesettings.SomeLDAPtoolkits(notablyNovell)donotsupportperconnectionclientcertificates,andwillthrowanerroronLDAPserverconnectionifyoutrytousethisdirective(UsetheLDAPTrustedGlobalCertdirectiveinsteadforNovellclientcertificates-SeetheSSL/TLScertificateguideabovefordetails).Thetypespecifiesthekindofcertificateparameterbeingset,dependingontheLDAPtoolkitbeingused.Supportedtypesare:

CERT_DER-binaryDERencodedclientcertificateCERT_BASE64-PEMencodedclientcertificateCERT_NICKNAME-Clientcertificate"nickname"(NetscapeSDK)KEY_DER-binaryDERencodedprivatekeyKEY_BASE64-PEMencodedprivatekey

Page 1114: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPTrustedGlobalCert

SetsthefileordatabasecontainingglobaltrustedCertificateAuthorityorglobalclientcertificatesLDAPTrustedGlobalCerttypedirectory-path/filename

[password]

serverconfig(E)mod_ldap

ItspecifiesthedirectorypathandfilenameofthetrustedCAcertificatesand/orsystemwideclientcertificatesmod_ldapshouldusewhenestablishinganSSLorTLSconnectiontoanLDAPserver.Notethatallcertificateinformationspecifiedusingthisdirectiveisappliedgloballytotheentireserverinstallation.SomeLDAPtoolkits(notablyNovell)requireallclientcertificatestobesetgloballyusingthisdirective.MostothertoolkitsrequireclientscertificatestobesetperDirectoryorperLocationusingLDAPTrustedClientCert.Ifyougetthiswrong,anerrormaybeloggedwhenanattemptismadetocontacttheLDAPserver,ortheconnectionmaysilentlyfail(SeetheSSL/TLScertificateguideabovefordetails).Thetypespecifiesthekindofcertificateparameterbeingset,dependingontheLDAPtoolkitbeingused.Supportedtypesare:

CA_DER-binaryDERencodedCAcertificateCA_BASE64-PEMencodedCAcertificateCA_CERT7_DB-Netscapecert7.dbCAcertificatedatabasefileCA_SECMOD-NetscapesecmoddatabasefileCERT_DER-binaryDERencodedclientcertificateCERT_BASE64-PEMencodedclientcertificateCERT_KEY3_DB-Netscapekey3.dbclientcertificatedatabasefileCERT_NICKNAME-Clientcertificate"nickname"(NetscapeSDK)CERT_PFX-PKCS#12encodedclientcertificate(NovellSDK)

Page 1115: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

KEY_DER-binaryDERencodedprivatekeyKEY_BASE64-PEMencodedprivatekeyKEY_PFX-PKCS#12encodedprivatekey(NovellSDK)

Page 1116: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPTrustedMode

SpecifiestheSSL/TLSmodetobeusedwhenconnectingtoanLDAPserver.LDAPTrustedModetype

serverconfig,virtualhost,directory,.htaccess(E)mod_ldap

Thefollowingmodesaresupported:

NONE-noencryptionSSL-ldaps://encryptionondefaultport636TLS-STARTTLSencryptionondefaultport389

NotallLDAPtoolkitssupportalltheabovemodes.Anerrormessagewillbeloggedatruntimeifamodeisnotsupported,andtheconnectiontotheLDAPserverwillfail.

Ifanldaps://URLisspecified,themodebecomesSSLandthesettingofLDAPTrustedModeisignored.

Page 1117: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

LDAPVerifyServerCert

ForceservercertificateverificationLDAPVerifyServerCertOn|Off

LDAPVerifyServerCertOn

serverconfig(E)mod_ldap

SpecifieswhethertoforcetheverificationofaservercertificatewhenestablishinganSSLconnectiontotheLDAPserver.

Page 1118: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006126|

Page 1119: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_log_config

(B)log_config_modulemod_log_config.c

TransferLog LogFormat CustomLog

TransferLogCustomLog

Page 1120: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LogFormatCustomLogC"\n""\t""\"

" %"

%% (Apache2.0.44)%a IP%A IP%B HTTP%b CLFHTTP' -'0%

{Foobar}C

cookieFoobar

%D

%

{FOOBAR}e

FOOBAR

%f

%h

%H

%

{Foobar}i

Foobar:

%l (identd) IdentityCheck" On""-"%m

%

{Foobar}n

Foobar

%

{Foobar}o

Foobar:

%p

%P PID%

{format}P

PIDTID(ID) format pidtid(2.0.46)hextid(APR1.2.0)

Page 1121: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

%q (" ?")%r

%s --- %>s

%t ()%

{format}t

strftime(3)()

%T

%u (status( %s)401)%U URL%v ServerName

%V UseCanonicalName

%X

X=+=-=

(1.3 %cSSL %{var}c)

%I mod_logio

%O mod_logio

"%"" %400,501{User-agent}i"400501 User-agent

" -"" !"" %!200,304,302{Referer}i" 200,304,302Referer

"<"">" %s,%U,%T,%D,%r %>s %<u

Page 1122: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

2.0.46 %r,%i,%o(")(\) \" \\C( \n,\t)\xhh(hh16)2.0.46

2.0(1.3) %b %BHTTP(SSL) mod_logio %O

(CLF)"%h%l%u%t\"%r\"%>s%b"

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

NCSA/"%h%l%u%t\"%r\"%>s%b\"%{Referer}i\"\"%

{User-agent}i\""

Referer"%{Referer}i->%U"

Agent(Browser)"%{User-agent}i"

Page 1123: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Page 1124: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

BufferedLogs

BufferedLogsOn|Off

BufferedLogsOff

serverconfig(B)mod_log_configApache2.0.41

BufferedLogsmod_log_config

Page 1125: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CookieLog

cookiesCookieLogfilename

serverconfig,virtualhost(B)mod_log_config

CookieLogcookies ServerRoot mod_cookies

Page 1126: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CustomLog

CustomLogfile|pipeformat|nickname[env=

[!]environment-variable]

serverconfig,virtualhost(B)mod_log_config

CustomLog

fileServerRoot

pipe" |"

httpdhttpdrootroot

UNIX(\)(/)(/)

LogFormatnicknameformat

#nickname

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

CustomLoglogs/access_logcommon

#

Page 1127: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CustomLoglogs/access_log"%h%l%u%t\"%r\"%>s

%b"

(" env=!name")

mod_setenvif/ mod_rewriteGIF

SetEnvIfRequest_URI\.gif$gif-image

CustomLoggif-requests.logcommonenv=gif-image

CustomLognongif-requests.logcommonenv=!gif-

image

RefererIgnore

SetEnvIfRefererexample\.comlocalreferer

CustomLogreferer.logrefererenv=!localreferer

Page 1128: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LogFormat

LogFormatformat|nickname[nickname]

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

serverconfig,virtualhost(B)mod_log_config

LogFormat TransferLog format nicknameLogFormat

LogFormat formatnickname LogFormatCustomLog

LogFormatnickname TransferLog

LogFormat( %)

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

vhost_common

Page 1129: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

TransferLog

TransferLogfile|pipe

serverconfig,virtualhost(B)mod_log_config

CustomLog LogFormat

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

{Referer}i\"\"%{User-agent}i\""

TransferLoglogs/access_log

Page 1130: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1131: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_log_forensic

""(E)log_forensic_modulemod_log_forensic.cmod_unique_idisnolongerrequiredsinceversion2.1

Thismoduleprovidesforforensicloggingofclientrequests.Loggingisdonebeforeandafterprocessingarequest,sotheforensiclogcontainstwologlinesforeachrequest.Theforensicloggerisverystrict,whichmeans:

Theformatisfixed.Youcannotmodifytheloggingformatatruntime.Ifitcannotwriteitsdata,thechildprocessexitsimmediatelyandmaydumpcore(dependingonyourCoreDumpDirectoryconfiguration).

check_forensicscript,whichcanbefoundinthedistribution'ssupportdirectory,maybehelpfulinevaluatingtheforensiclogoutput.

Page 1132: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

check_forensicscripttakesasitsargumentthenameofthelogfile.Itlooksforthose+/-IDpairsandcomplainsifarequestwasnotcompleted.

Page 1133: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SecurityConsiderations

Seethesecuritytipsdocumentfordetailsonwhyyoursecuritycouldbecompromisedifthedirectorywherelogfilesarestorediswritablebyanyoneotherthantheuserthatstartstheserver.

Page 1134: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ForensicLog

SetsfilenameoftheforensiclogForensicLogfilename|pipe

serverconfig,virtualhost(E)mod_log_forensic

ForensicLogdirectiveisusedtologrequeststotheserverforforensicanalysis.EachlogentryisassignedauniqueIDwhichcanbeassociatedwiththerequestusingthenormalCustomLogdirective.mod_log_forensiccreatesatokencalledforensic-id,whichcanbeaddedtothetransferlogusingthe%{forensic-id}nformatstring.

Theargument,whichspecifiesthelocationtowhichthelogswillbewritten,cantakeoneofthefollowingtwotypesofvalues:

filenameAfilename,relativetotheServerRoot.

pipeThepipecharacter"|",followedbythepathtoaprogramtoreceivetheloginformationonitsstandardinput.TheprogramnamecanbespecifiedrelativetotheServerRootdirective.

Ifaprogramisused,thenitwillberunastheuserwhostartedhttpd.Thiswillberootiftheserverwasstartedbyroot;besurethattheprogramissecureorswitchestoalessprivilegeduser.

Whenenteringafilepathonnon-Unixplatforms,careshould

Page 1135: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

betakentomakesurethatonlyforwardslashedareusedeventhoughtheplatformmayallowtheuseofbackslashes.Ingeneralitisagoodideatoalwaysuseforwardslashesthroughouttheconfigurationfiles.

Page 1136: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006126|

Page 1137: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_logio

/HTTP(E)logio_modulemod_logio.c

/SSL/TLSSSL/TLS

mod_log_config

Page 1138: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

" %"

%I

%O

I/O"%h%l%u%t\"%r\"%>s%b\"%{Referer}i\"\"%

{User-agent}i\"%I%O"

Page 1139: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006126|

Page 1140: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_mem_cache

(E)mem_cache_modulemod_mem_cache.c

mod_cache mod_cache mod_mem_cache

mod_mem_cache mod_proxyProxyPass( )

URI

Page 1141: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MCacheMaxObjectCount

MCacheMaxObjectCountvalue

MCacheMaxObjectCount1009

serverconfig(E)mod_mem_cache

MCacheMaxObjectCount

MCacheRemovalAlgorithm

MCacheMaxObjectCount13001

Page 1142: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MCacheMaxObjectSize

()MCacheMaxObjectSizebytes

MCacheMaxObjectSize10000

serverconfig(E)mod_mem_cache

MCacheMaxObjectSize(Byte)

MCacheMaxObjectSize6400000

MCacheMaxObjectSizeMCacheMinObjectSize

Page 1143: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MCacheMaxStreamingBuffer

MCacheMaxStreamingBuffersize_in_bytes

MCacheMaxStreamingBuffer100000MCacheMaxObjectSize

serverconfig(E)mod_mem_cache

MCacheMaxStreamingBuffer Content-LengthCGIContent-Length MCacheMaxStreamingBuffer

Content-Length

MCacheMaxStreamingBuffer mod_mem_cache

#64KB

MCacheMaxStreamingBuffer65536

Page 1144: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MCacheMinObjectSize

()MCacheMinObjectSizebytes

MCacheMinObjectSize0

serverconfig(E)mod_mem_cache

MCacheMinObjectSize

MCacheMinObjectSize10000

Page 1145: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MCacheRemovalAlgorithm

MCacheRemovalAlgorithmLRU|GDSF

MCacheRemovalAlgorithmGDSF

serverconfig(E)mod_mem_cache

MCacheRemovalAlgorithm

LRU()LRU

GDSF(GreadyDual-Size)GDSF

MCacheRemovalAlgorithmGDSF

MCacheRemovalAlgorithmLRU

Page 1146: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

MCacheSize

KBMCacheSizeKBytes

MCacheSize100

serverconfig(E)mod_mem_cache

MCacheSizeKB(1024-byte)MCacheRemovalAlgorithm

MCacheSize700000

MCacheSizeMCacheMaxObjectSize

Page 1147: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006127|

Page 1148: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_mime

(/)(MIME///)(B)mime_modulemod_mime.c

""MIME mod_negotiation

AddCharset,AddEncoding,AddLanguage,AddTypeMIME() TypesConfigMIME

mod_mime AddHandler,AddOutputFilter,AddInputFilter MultiviewsMatchmod_negotiation

Multiview

mod_mime core( <Location>,<Directory>,<Files>)ForceType,SetHandler,SetInputFilter,

SetOutputFiltercoremod_mime

Last-Modified()""()

Page 1149: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

welcome.html.frtext/html welcome.fr.html

.gifMIMEwelcome.gif.htmlMIMEtext/html

welcome.html.en.deContent-Language:en,de

Content-Type:text/html

MIME .imap( mod_imagemap) imap-file

.htmlMIMEtext/htmlworld.imap.htmlimap-filetext/htmlMIME imap-file mod_imagemap

Page 1150: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MIME gzip pgpUUencodingUUencodingASCII()

HTTP/1.1RFC14.11

"Content-Encoding""Content-Type""Content-Encoding"

( )

MicrosoftWord .docMicrosoftWord .zippkzipResume.doc.zippkzipWord

ApacheContent-encoding

Content-encoding:pkzip

Page 1151: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HTTP

( mod_negotiation) AddCharset,AddEncoding,AddLanguage,AddType( MimeMagicFile)AddHandler,AddInputFilter,AddOutputFilterMultiviewsMatch

Apache Content-Language Content-Type

Content-Language:en,fr

Content-Type:text/plain;charset=ISO-8859-1

charset

Page 1152: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddCharset

AddCharsetcharsetextension[extension]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mime

AddCharset charsetextensionMIME extension

AddLanguageja.ja

AddCharsetEUC-JP.euc

AddCharsetISO-2022-JP.jis

AddCharsetSHIFT_JIS.sjis

xxxx.ja.jisISO-2022-JP( xxxx.jis.ja) AddCharset

()

extension

mod_negotiation

AddDefaultCharset

Page 1153: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddEncoding

AddEncodingMIME-encextension[extension]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mime

AddEncoding extensionMIME-enc extension

AddEncodingx-gzip.gz

AddEncodingx-compress.Z

.gzx-gzip .Zx-compress

x-gzipx-compress gzipcompressApache" x-"Apache( x-foofoo)Apachex-gzipx-compressdeflate" x-"

extension

Page 1154: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddHandler

AddHandlerhandler-nameextension[extension]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mime

extensionhandler-name extension .cgiCGI

AddHandlercgi-script.cgi

http.conf .cgiCGI

extension

SetHandler

Page 1155: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddInputFilter

AddInputFilterfilter[;filter...]extension

[extension]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.26

AddInputFilterextension SetInputFilter extension

filterextension extension

RemoveInputFilter

SetInputFilter

Page 1156: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddLanguage

AddLanguageMIME-langextension[extension]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mime

AddLanguage extensionMIME-lang extension

AddEncodingx-compress.Z

AddLanguageen.en

AddLanguagefr.fr

xxxx.en.Z(xxxx.Z.en) AddLanguage

AddLanguageen.en

AddLanguageen-gb.en

AddLanguageen-us.en

.enen-us

extension

mod_negotiation

Page 1157: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddOutputFilter

AddOutputFilterfilter[;filter...]extension

[extension]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.26

AddOutputFilterextension SetOutputFilter

AddOutputFilterByType extension

.shtml mod_deflate

AddOutputFilterINCLUDES;DEFLATEshtml

filterextension extension

RemoveOutputFilter

SetOutputFilter

Page 1158: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddType

AddTypeMIME-typeextension[extension]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mime

AddType MIME-typeextension extension( TypesConfig)

AddTypeimage/gif.gif

AddType TypesConfig

extension

DefaultType

ForceType

Page 1159: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DefaultLanguage

DefaultLanguageMIME-lang

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mime

DefaultLanguageApache( <Directory>)(AddLanguage.fr.de) MIME-lang

DefaultLanguage

DefaultLanguageAddLanguage

DefaultLanguageen

mod_negotiation

Page 1160: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ModMimeUsePathInfo

path_info

ModMimeUsePathInfoOn|Off

ModMimeUsePathInfoOff

directory(B)mod_mimeApache2.0.41

ModMimeUsePathInfomod_mimeURL path_info OffURL path_info

ModMimeUsePathInfoOn

/bar/foo.shtml" /bar" ModMimeUsePathInfo On

mod_mime/bar/foo.shtml" AddOutputFilterINCLUDES

.shtml" INCLUDES ModMimeUsePathInfo INCLUDES

AcceptPathInfo

Page 1161: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MultiviewsMatch

MultiViewsMultiviewsMatch

Any|NegotiatedOnly|Filters|Handlers

[Handlers|Filters]

MultiviewsMatchNegotiatedOnly

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.26

MultiviewsMatchmod_negotiationMultiviewsMultiviewsindex.htmlindex.html.en

index.html.gz

NegotiatedOnlymod_mime

/ MultiviewsMatchHandlersFilters500index.html.cgi1000index.html.pl .cgi .asisasis-

handler .asis

mod_mime AnyApaceh1.3.old.bak

Multviews

MultiviewsMatchHandlersFilters

Options

mod_negotiation

Page 1162: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RemoveCharset

RemoveCharsetextension[extension]...

virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.24

RemoveCharset .htaccess

extension

RemoveCharset.html.shtml

Page 1163: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RemoveEncoding

RemoveEncodingextension[extension]...

virtualhost,directory,.htaccessFileInfo(B)mod_mime

RemoveEncoding .htaccess

/foo/.htaccess:AddEncodingx-gzip.gz

AddTypetext/plain.asc

<Files*.gz.asc>

RemoveEncoding.gz

</Files>

foo.gzgzip foo.gz.asc

RemoveEncodingAddEncoding RemoveEncoding

AddEncoding

extension

Page 1164: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RemoveHandler

RemoveHandlerextension[extension]...

virtualhost,directory,.htaccessFileInfo(B)mod_mime

RemoveHandler .htaccess

/foo/.htaccessAddHandlerserver-parsed.html

/foo/bar/.htaccessRemoveHandler.html

/foo/bar.htmlparsing( mod_include)

extension

Page 1165: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RemoveInputFilter

RemoveInputFilterextension[extension]...

virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.26

RemoveInputFilter .htaccess

extension

AddInputFilter

SetInputFilter

Page 1166: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RemoveLanguage

RemoveLanguageextension[extension]...

virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.24

RemoveLanguage .htaccess

extension

Page 1167: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RemoveOutputFilter

RemoveOutputFilterextension[extension]...

virtualhost,directory,.htaccessFileInfo(B)mod_mime2.0.26

RemoveOutputFilter .htaccess

extension

RemoveOutputFiltershtml

AddOutputFilter

Page 1168: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RemoveType

RemoveTypeextension[extension]...

virtualhost,directory,.htaccessFileInfo(B)mod_mime

RemoveType .htaccess

/foo/.htaccessRemoveType.cgi

/foo/.cgi DefaultType

RemoveTypeAddType RemoveTypeAddType

extension

Page 1169: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

TypesConfig

mime.types

TypesConfigfile-path

TypesConfigconf/mime.types

serverconfig(B)mod_mime

TypesConfigMIME File-pathServerRoot mime.types

IANA http://www.iana.org/assignments/media-types/index.htmlhttpd.conf AddType mime.types

AddType

MIME-type[extension]...

( #)

ApacheHTTPmime.types(1)IANS(2) category/x-

subtype

mod_mime_magic

Page 1170: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006127|

Page 1171: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_mime_magic

MIME(E)mime_magic_modulemod_mime_magic.c

Unixfile(1) MIMEmod_mime""

Unixfile(1)"Magic""Magic" MimeMagicFile

Page 1172: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

"Magic"

Magic4-5( #)

1 ">"">"2

byte

short 16long 32string

date (UNIX/1970)beshort big-endian16belong big-endian32bedate big-endian32leshort little-endian16lelong little-endian32ledate little-endian32

34 MIME5 MIME()

Magic

#Sun/NeXTaudiodata

0string.snd

>12belong1audio/basic

>12belong2audio/basic

>12belong3audio/basic

>12belong4audio/basic

>12belong5audio/basic

Page 1173: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

>12belong6audio/basic

>12belong7audio/basic

>12belong23audio/x-adpcm

*.docMicrosoftWordFrameMaker()

#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

MIMEgzip

#gzip(GNUzip,nottobeconfusedwith

#[Info-ZIP/PKWARE]ziparchiver)

0string\037\213application/octet-streamx-gzip

Page 1174: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

web

file(1)webweb""

Page 1175: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_mime_magic

mod_mime_magic:MagicNumberMIMECopyright(c)1996-1997CiscoSystems,Inc.

Cisco19977ApacheCiscoApache

comp.sources.unixfile

-Copyright(c)IanF.Darwin,1987.WrittenbyIanF.Darwin.

(AT&T)

1.

2.

3.

4.

MrDarwin"file"

ApacheApacheApacheApache()MagicApacheAPIrealloc()()stdoutApacheMIME

Page 1176: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

MimeMagicFile

MagicMIMEMimeMagicFilefile-path

serverconfig,virtualhost(E)mod_mime_magic

MimeMagicFileMagic conf/magic ServerRoot

MimeMagicFileconf/magic

Page 1177: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006128|

Page 1178: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_negotiation

(B)negotiation_modulemod_negotiation.c

""

( type-map)"MultiViews"( OptionsMultiViews)

Page 1179: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RFC822(#)

Content-Encoding:

Apache AddEncodingcompress x-compressgzipx-gzip" x-"

Content-Language:

(RFC1766) en

Content-Length:

Content-Type:

MIMEMIME" name=value"

level

text/html"2""0"

qs

0.01.0""jpegAsciijpeg qs

Content-Type:image/jpeg;qs=0.8

URI:

URIURL

Body:

2.0Body

Body:----xyz----

<html>

<body>

<p>Contentofthepage.</p>

</body>

</html>

Page 1180: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

----xyz----

Page 1181: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MultiViews

MultiViewsOptionsMultiViews /some/dir/foo

/some/dir/foo foo.* foo.*

MultiViewsMatchApache

Page 1182: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheNegotiatedDocs

CacheNegotiatedDocsOn|Off

CacheNegotiatedDocsOff

serverconfig,virtualhost(B)mod_negotiation2.0

"On"

HTTP/1.0HTTP/1.1HTTP/1.1

2.0 CacheNegotiatedDocs

Page 1183: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ForceLanguagePriority

ForceLanguagePriorityNone|Prefer|Fallback

[Prefer|Fallback]

ForceLanguagePriorityPrefer

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_negotiationApache2.0.30

ForceLanguagePriorityLanguagePriority

ForceLanguagePriorityPrefer LanguagePriority

HTTP"300"() Accept-Languageende

en

LanguagePriorityenfrde

ForceLanguagePriorityPrefer

ForceLanguagePriorityFallbackLanguagePriorityHTTP"406"() Accept-Language

LanguagePriority

LanguagePriorityenfrde

ForceLanguagePriorityFallback

PreferFallback LanguagePriority

AddLanguage

Page 1184: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

LanguagePriority

LanguagePriorityMIME-lang[MIME-lang]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_negotiation

MultiViews LanguagePriority MIME-lang

LanguagePriorityenfrde

foo.html foo.html.frfoo.html.de foo.html.fr

ForceLanguagePriorityNoneHTTP/1.1

AddLanguage

Page 1185: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006128|

Page 1186: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_nw_ssl

NetWareSSL(B)nwssl_modulemod_nw_ssl.cNetWare

(port)SSLNetWareSSL

Page 1187: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

NWSSLTrustedCerts

NWSSLTrustedCertsfilename[filename]...

serverconfig(B)mod_nw_ssl

(DER)SSL .der

Page 1188: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

NWSSLUpgradeable

SSLNWSSLUpgradeable[IP-address:]portnumber

serverconfig(B)mod_nw_ssl

/SSL/ Listen

Page 1189: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

SecureListen

SSLSecureListen[IP-address:]portnumberCertificate-

Name[MUTUAL]

serverconfig(B)mod_nw_ssl

SSLeDirectorymutual

Page 1190: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |???|

Page 1191: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_proxy

HTTP/1.1/(E)proxy_modulemod_proxy.c

ProxyRequests

Apache/ AJP13(ApacheJServeProtocolv1.3),FTP,CONNECT(SSL), HTTP/0.9,HTTP/1.0,HTTP/1.1

Apache( mod_proxy) mod_proxy_http,mod_proxy_ftp,mod_proxy_ajp,mod_proxy_balancer,mod_proxy_connect mod_proxy( LoadModule)

mod_cache mod_sslSSLProxy*SSL/TLS

Page 1192: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache(forward)(reverse)

(originserver)()

Internet( mod_cache)

ProxyRequests

(name-space)()

InternetURLwebwebURL

ProxyPass( RewriteRule[P]) ProxyRequests

Page 1193: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_cache

ProxyRequestsOn

ProxyViaOn

<Proxy*>

Orderdeny,allow

Denyfromall

Allowfrominternal.example.com

</Proxy>

ProxyRequestsOff

<Proxy*>

Orderdeny,allow

Allowfromall

</Proxy>

ProxyPass/foohttp://foo.example.com/bar

ProxyPassReverse/foohttp://foo.example.com/bar

Page 1194: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Proxy>

<Proxy*>

OrderDeny,Allow

Denyfromall

Allowfrom192.168.0

</Proxy>

mod_authz_host

( ProxyRequests)(" ProxyRequestsOff"ProxyPass)

Page 1195: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyBlockIP

Page 1196: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache( ProxyRemote) NoProxy

WWW"http://somehost/" http://somehost.example.com/

ProxyDomain

Page 1197: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_proxy(KeepAlive)HTTP/1.1 (KeepAlive)HTTP/1.0 SetEnv

force-proxy-request-1.0proxy-nokeepalive

<Location/buggyappserver/>

ProxyPasshttp://buggyappserver:7001/foo/

SetEnvforce-proxy-request-1.01

SetEnvproxy-nokeepalive1

</Location>

Page 1198: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(POST)HTTP(chunkedtransferencoding) Content-Length

mod_proxy_httpContent-Length proxy-

sendclContent-Length proxy-sendchunked

Page 1199: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AllowCONNECT

CONNECT

AllowCONNECTport[port]...

AllowCONNECT443563

serverconfig,virtualhost(E)mod_proxy

AllowCONNECTCONNECT https http

https(443)snews(563) AllowCONNECT

mod_proxy_connect CONNECT

Page 1200: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

NoProxy

//NoProxyhost[host]...

serverconfig,virtualhost(E)mod_proxy

Apache NoProxyIP/ ProxyRemote

ProxyRemote*http://firewall.mycompany.com:81

NoProxy.mycompany.com192.168.112.0/21

NoProxyhost

DNSDNS""

.com

.apache.org.

(DNSDNS"A"!)

DNS .MyDomain.com.mydomain.com.()DNS

bit()bit8bit

192.168192.168.0.0

Page 1201: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

" 192.168.0.0"16bit( 255.255.0.0)

192.168.112.0/21

" 192.168.112.0/21"21bit( 255.255.248.0)32bit IPbit("0.0.0.0/0")" _Default_"IP

IPIPDNS

192.168.123.7

IPDNSapache

DNSDNS IP( ) IP( IP)

prep.ai.mit.edu

www.apache.org

IPDNSPPPApache

DNS WWW.MyDomain.comwww.mydomain.com.()

DNS

Page 1202: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Proxy>

<Proxywildcard-url>...</Proxy>

serverconfig,virtualhost(E)mod_proxy

<Proxy>shell

yournetwork.example.com

<Proxy*>

OrderDeny,Allow

Denyfromall

Allowfromyournetwork.example.com

</Proxy>

example.comfooINCLUDES

<Proxyhttp://example.com/foo/*>

SetOutputFilterINCLUDES

</Proxy>

Page 1203: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyBadHeader

ProxyBadHeaderIsError|Ignore|StartBody

ProxyBadHeaderIsError

serverconfig,virtualhost(E)mod_proxyApache2.0.44

ProxyBadHeadermod_proxy((:))

IsError

"502"(BadGateway)

Ignore

StartBody

Page 1204: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyBlock

ProxyBlock*|word|host|domain[word|host|domain]

...

serverconfig,virtualhost(E)mod_proxy

ProxyBlock//HTTPHTTPSFTP IP

ProxyBlockjoes-garage.comsome-host.co.uk

rocky.wotsamattau.edu

IP rocky.wotsamattau.edu

wotsamattauwotsamattau.edu

ProxyBlock*

Page 1205: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyDomain

ProxyDomainDomain

serverconfig,virtualhost(E)mod_proxy

Apache ProxyDomainapache Domain

ProxyRemote*http://firewall.mycompany.com:81

NoProxy.mycompany.com192.168.112.0/21

ProxyDomain.mycompany.com

Page 1206: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyErrorOverride

ProxyErrorOverrideOn|Off

ProxyErrorOverrideOff

serverconfig,virtualhost(E)mod_proxyApache2.0

( mod_includeSSI)("On"SSI)

Page 1207: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyIOBufferSize

ProxyIOBufferSizebytes

ProxyIOBufferSize8192

serverconfig,virtualhost(E)mod_proxy

ProxyIOBufferSize() 8192

Page 1208: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<ProxyMatch>

<ProxyMatchregex>...</ProxyMatch>

serverconfig,virtualhost(E)mod_proxy

<ProxyMatch><Proxy>

Page 1209: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyMaxForwards

ProxyMaxForwardsnumber

ProxyMaxForwards10

serverconfig,virtualhost(E)mod_proxyApache2.0

ProxyMaxForwardsDoS

ProxyMaxForwards15

Page 1210: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyPass

URLProxyPass[path]!|url[key=valuekey=value...]]

serverconfig,virtualhost,directory(E)mod_proxy

URL path urlURL

ProxyPass ProxyRequests off

http://example.com/

ProxyPass/mirror/foo/http://backend.example.com/

http://example.com/mirror/foo/bar

http://backend.example.com/bar

"!"

ProxyPass/mirror/foo/i!

ProxyPass/mirror/foohttp://backend.example.com

/mirror/foo/ibackend.example.com/mirror/foo

ProxyPass

AsofApache2.1,theabilitytousepooledconnectionstoabackendserverisavailable.Usingthekey=valueparametersitispossibletotunethisconnectionpooling.ThedefaultforaHardMaximumforthenumberofconnectionsisthenumberofthreadsperprocessinthe

Page 1211: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

activeMPM.InthePreforkMPM,thisisalways1,whilewiththeWorkerMPMitiscontrolledbytheThreadsPerChild.

Settingminwilldeterminehowmanyconnectionswillalwaysbeopentothebackendserver.UptotheSoftMaximumorsmaxnumberofconnectionswillbecreatedondemand.Anyconnectionsabovesmaxaresubjecttoatimetoliveorttl.ApachewillnevercreatemorethantheHardMaximumormaxconnectionstothebackendserver.

ProxyPass/examplehttp://backend.example.com

smax=5max=20ttl=120retry=300

Parameter Default Descriptionmin 0 Minumumnumberofconnectionsthatwill

alwaysbeopentothebackendserver.max 1...n HardMaximumnumberofconnectionsthat

willbeallowedtothebackendserver.ThedefaultforaHardMaximumforthenumberofconnectionsisthenumberofthreadsperprocessintheactiveMPM.InthePreforkMPM,thisisalways1,whilewiththeWorkerMPMitiscontrolledbytheThreadsPerChild.ApachewillnevercreatemorethantheHardMaximumconnectionstothebackendserver.

smax max UptotheSoftMaximumnumberofconnectionswillbecreatedondemand.Anyconnectionsabovesmaxaresubjecttoatimetoliveorttl.

ttl - TimeToLivefortheinactiveconnectionsabovethesmaxconnectionsinseconds.Apachewillcloseallconnectionsthathasnotbeenusedinsidethattimeperiod.

Page 1212: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

timeout Timeout Connectiontimeoutinseconds.IfnotsettheApachewillwaituntilthefreeconnectionisavailable.Thisdirectiveisusedforlimitingthenumberofconnectionstothebackendservertogetherwithmaxparameter.

acquire - Ifsetthiswillbethemaximumtimetowaitforafreeconnectionintheconnectionpool.IftherearenofreeconnectionsinthepooltheApachewillreturnSERVER_BUSYstatustotheclient.

keepalive Off ThisparametershouldbeusedwhenyouhaveafirewallbetweenyourApacheandthebackendserver,whotendtodropinactiveconnections.ThisflagwilltelltheOperatingSystemtosendKEEP_ALIVEmessagesoninactiveconnections(intervaldependsonglobalOSsettings,generally120ms),andthuspreventthefirewalltodroptheconnection.ToenablekeepalivesetthispropertyvaluetoOn.

retry 60 Connectionpoolworkerretrytimeoutinseconds.Iftheconnectionpoolworkertothebackendserverisintheerrorstate,Apachewillnotforwardanyrequeststothatserveruntilthetimeoutexpires.Thisenablestoshutdownthebackendserverformaintenance,andbringitbackonlinelater.

loadfactor 1 Workerloadfactor.UsedwithBalancerMember.Itisanumberbetween1and100anddefinesthenormalizedweightedloadappliedtotheworker.

route - Routeoftheworkerwhenusedinsideloadbalancer.Therouteisavalueappendedto

Page 1213: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

seesionid.

redirect - RedirectionRouteoftheworker.Thisvalueisusuallysetdynamicallytoenablesaferemovalofthenodefromthecluster.IfsetallrequestswithoutsessionidwillberedirectedtotheBalancerMemberthathasrouteparametarequalasthisvalue.

IftheProxydirectiveschemestartswiththebalancer://thenavirtualworkerthatdoesnotreallycommunicatewiththebackendserverwillbecreated.Insteaditisresponsibleforthemanagementofseveral"real"workers.Inthatcasethespecialsetofparameterscanbeaddtothisvirtualworker.

Parameter Default Descriptionlbmethod - Balancerload-balancemethod.Selectthe

load-balancingschedulermethodtouse.Eitherbyrequests,toperformweightedrequestcountingorbytraffic,toperformweightedtrafficbytecountbalancing.Defaultisbyrequests.

stickysession - Balancerstickysessionname.ThevalueisusuallysettosomethinglikeJSESSIONIDPHPSESSIONID,anditdependsonthebackendapplicationserverthatsupportsessions.

nofailover Off IfsettoOnthesessionwillbreakiftheworkerisinerrorstateordisabled.SetthisvaluetoOnifbackendserversdonotsupportsessionreplication.

timeout 0 Balancertimeoutinseconds.Ifsetthiswillbethemaximumtimetowaitforafreeworker.Defaultisnottowait.

Page 1214: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

maxattempts 1 Maximumnumberoffailoverattemptsbeforegivingup.

ProxyPass/special-area

http://special.example.com/smax=5max=10

ProxyPass/balancer://mycluster

stickysession=jsessionidnofailover=On

<Proxybalancer://mycluster>

BalancerMemberhttp://1.2.3.4:8009

BalancerMemberhttp://1.2.3.5:8009smax=10

#Lesspowerfulserver,don'tsendasmany

requeststhere

BalancerMemberhttp://1.2.3.6:8009smax=1

loadfactor=20

</Proxy>

Whenusedinsidea<Location>section,thefirstargumentisomittedandthelocaldirectoryisobtainedfromthe<Location>.

Ifyourequireamoreflexiblereverse-proxyconfiguration,seetheRewriteRuledirectivewiththe[P]flag.

Page 1215: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyPassReverse

HTTPURLProxyPassReverse[path]url

serverconfig,virtualhost,directory(E)mod_proxy

ApacheHTTPLocation,Content-Location,URIURLApacheHTTP

HTMLURLURLHTMLURLNickmod_proxy_html

path urlURL ProxyPass

http://example.com/

ProxyPass/mirror/foo/http://backend.example.com/

ProxyPassReverse/mirror/foo/

http://backend.example.com/

ProxyPassReverseCookieDomainbackend.example.com

public.example.com

ProxyPassReverseCookiePath//mirror/foo/

http://example.com/mirror/foo/bar

http://backend.example.com/bar( ProxyPass)backend.example.com http://backend.example.com/bar

http://backend.example.com/quuxApacheHTTPhttp://example.com/mirror/foo/quuxURLUseCanonicalName

ProxyPassReversemod_rewrite(RewriteRule...[P])ProxyPass

Page 1216: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<Location> <Location>

Page 1217: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyPassReverseCookieDomain

AdjuststheDomainstringinSet-Cookieheadersfromareverse-proxiedserverProxyPassReverseCookieDomaininternal-domain

public-domain

serverconfig,virtualhost,directory(E)mod_proxy

UsageisbasicallysimilartoProxyPassReverse,butinsteadofrewritingheadersthatareaURL,thisrewritesthedomainstringinSet-Cookieheaders.

Page 1218: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyPassReverseCookiePath

AdjuststhePathstringinSet-Cookieheadersfromareverse-proxiedserverProxyPassReverseCookiePathinternal-pathpublic-

path

serverconfig,virtualhost,directory(E)mod_proxy

UsageisbasicallysimilartoProxyPassReverse,butinsteadofrewritingheadersthatareaURL,thisrewritesthepathstringinSet-Cookieheaders.

Page 1219: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyPreserveHost

HTTPProxyPreserveHostOn|Off

ProxyPreserveHostOff

serverconfig,virtualhost(E)mod_proxyApache2.0.31

"Host:" ProxyPass

OffItismostly usefulinspecialconfigurationslikeproxiedmassname-basedvirtualhosting,wheretheoriginalHostheaderneedstobeevaluatedbythebackendserver.

Page 1220: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyReceiveBufferSize

HTTPFTP()ProxyReceiveBufferSizebytes

ProxyReceiveBufferSize0

serverconfig,virtualhost(E)mod_proxy

ProxyReceiveBufferSizeHTTPFTP(TCP/IP) 512" 0"

ProxyReceiveBufferSize2048

Page 1221: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyRemote

ProxyRemotematchremote-server

serverconfig,virtualhost(E)mod_proxy

matchURLURL" *" remote-serverURL

remote-server=scheme://hostname[:port]

scheme http

ProxyRemotehttp://goodguys.com/

http://mirrorguys.com:8000

ProxyRemote*http://cleversite.com

ProxyRemoteftphttp://ftpproxy.mydomain.com:8080

HTTPFTP

webURL

Page 1222: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyRemoteMatch

ProxyRemoteMatchregexremote-server

serverconfig,virtualhost(E)mod_proxy

ProxyRemoteMatchProxyRemoteURL

Page 1223: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyRequests

()ProxyRequestsOn|Off

ProxyRequestsOff

serverconfig,virtualhost(E)mod_proxy

Apache( OffProxyPass)

Off

HTTPFTP mod_proxy_httpmod_proxy_ftp

ProxyRequests

Page 1224: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyTimeout

ProxyTimeoutseconds

ProxyTimeout300

serverconfig,virtualhost(E)mod_proxyApache2.0.31

/

Page 1225: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ProxyVia

Via

ProxyViaOn|Off|Full|Block

ProxyViaOff

serverconfig,virtualhost(E)mod_proxy

" Via:" RFC2616(HTTP/1.1)14.45" Via:"

Off" Via:"On" Via:"Full" Via:"Apache" Via:"Block" Via:"" Via:"

Page 1226: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1227: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_proxy_ajp

mod_proxyApacheJServProtocol(E)proxy_ajp_moduleproxy_ajp.cApache2.1

Thismodulerequirestheserviceofmod_proxy.ItprovidessupportfortheApacheJServProtocolversion1.3(hereafterAJP13).

Thus,inordertogettheabilityofhandlingAJP13protocol,mod_proxymod_proxy_ajphavetobepresentintheserver.

Internet

Page 1228: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Overviewoftheprotocol

AJP13protocolispacket-oriented.Abinaryformatwaspresumablychosenoverthemorereadableplaintextforreasonsofperformance.ThewebservercommunicateswiththeservletcontaineroverTCPconnections.Tocutdownontheexpensiveprocessofsocketcreation,thewebserverwillattempttomaintainpersistentTCPconnectionstotheservletcontainer,andtoreuseaconnectionformultiplerequest/responsecycles.

Onceaconnectionisassignedtoaparticularrequest,itwillnotbeusedforanyothersuntiltherequest-handlingcyclehasterminated.Inotherwords,requestsarenotmultiplexedoverconnections.Thismakesformuchsimplercodeateitherendoftheconnection,althoughitdoescausemoreconnectionstobeopenatonce.

Oncethewebserverhasopenedaconnectiontotheservletcontainer,theconnectioncanbeinoneofthefollowingstates:

IdleNorequestisbeinghandledoverthisconnection.AssignedTheconnectonishandlingaspecificrequest.

Onceaconnectionisassignedtohandleaparticularrequest,thebasicrequestinformaton(e.g.HTTPheaders,etc)issentovertheconnectioninahighlycondensedform(e.g.commonstringsareencodedasintegers).DetailsofthatformatarebelowinRequestPacketStructure.Ifthereisabodytotherequest(content-length>0),thatissentinaseparatepacketimmediatelyafter.

Atthispoint,theservletcontainerispresumablyreadytostartprocessingtherequest.Asitdoesso,itcansendthefollowingmessagesbacktothewebserver:

SEND_HEADERS

Page 1229: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Sendasetofheadersbacktothebrowser.SEND_BODY_CHUNKSendachunkofbodydatabacktothebrowser.GET_BODY_CHUNKGetfurtherdatafromtherequestifithasn'tallbeentransferredyet.Thisisnecessarybecausethepacketshaveafixedmaximumsizeandarbitraryamountsofdatacanbeincludedthebodyofarequest(foruploadedfiles,forexample).(Note:thisisunrelatedtoHTTPchunkedtranfer).END_RESPONSEFinishtherequest-handlingcycle.

Eachmessageisaccompaniedbyadifferentlyformattedpacketofdata.SeeResponsePacketStructuresbelowfordetails.

Page 1230: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

BasicPacketStructure

ThereisabitofanXDRheritagetothisprotocol,butitdiffersinlotsofways(no4bytealignment,forexample).

Byteorder:Iamnotclearabouttheendian-nessoftheindividualbytes.I'mguessingthebytesarelittle-endian,becausethat'swhatXDRspecifies,andI'mguessingthatsys/socketlibraryismagicallymakingthatso(ontheCside).Ifanyonewithabetterknowledgeofsocketcallscanstepin,thatwouldbegreat.

Therearefourdatatypesintheprotocol:bytes,booleans,integersandstrings.

ByteAsinglebyte.

BooleanAsinglebyte,1=true,0=false.Usingothernon-zerovaluesastrue(i.e.C-style)mayworkinsomeplaces,butitwon'tinothers.

IntegerAnumberintherangeof0to2^16(32768).Storedin2byteswiththehigh-orderbytefirst.

StringAvariable-sizedstring(lengthboundedby2^16).Encodedwiththelengthpackedintotwobytesfirst,followedbythestring(includingtheterminating'\0').Notethattheencodedlengthdoesnotincludethetrailing'\0'--itislikestrlen.ThisisatouchconfusingontheJavaside,whichislitteredwithoddautoincrementstatementstoskipovertheseterminators.IbelievethereasonthiswasdonewastoallowtheCcodetobeextraefficientwhenreadingstringswhichtheservletcontainerissendingback--withtheterminating\0character,theCcodecanpassaroundreferencesintoasinglebuffer,withoutcopying.ifthe\0wasmissing,theCcodewouldhavetocopythingsoutin

Page 1231: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ordertogetitsnotionofastring.

PacketSizeAccordingtomuchofthecode,themaxpacketsizeis8*1024bytes(8K).Theactuallengthofthepacketisencodedintheheader.

PacketHeadersPacketssentfromtheservertothecontainerbeginwith0x1234.PacketssentfromthecontainertotheserverbeginwithAB(that'stheASCIIcodeforAfollowedbytheASCIIcodeforB).Afterthosefirsttwobytes,thereisaninteger(encodedasabove)withthelengthofthepayload.Althoughthismightsuggestthatthemaximumpayloadcouldbeaslargeas2^16,infact,thecodesetsthemaximumtobe8K.

PacketFormat(Server->Container)Byte 0 1 2 3 4...(n+3)Contents 0x12 0x34 DataLength(n) Data

PacketFormat(Container->Server)Byte 0 1 2 3 4...(n+3)Contents A B DataLength(n) Data

Formostpackets,thefirstbyteofthepayloadencodesthetypeofmessage.Theexceptionisforrequestbodypacketssentfromtheservertothecontainer--theyaresentwithastandardpacketheader(0x1234andthenlengthofthepacket),butwithoutanyprefixcodeafterthat.

Thewebservercansendthefollowingmessagestotheservletcontainer:

Page 1232: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Code TypeofPacket

Meaning

2 ForwardRequest

Begintherequest-processingcyclewiththefollowingdata

7 Shutdown Thewebserverasksthecontainertoshutitselfdown.

8 Ping Thewebserverasksthecontainertotakecontrol(secureloginphase).

10 CPing ThewebserverasksthecontainertorespondquicklywithaCPong.

none Data Size(2bytes)andcorrespondingbodydata.

Toensuresomebasicsecurity,thecontainerwillonlyactuallydotheShutdowniftherequestcomesfromthesamemachineonwhichit'shosted.

ThefirstDatapacketissendimmediatlyaftertheForwardRequestbythewebserver.

Theservletcontainercansendthefollowingtypesofmessagestothewebserver:

Code TypeofPacket

Meaning

3 SendBodyChunk

Sendachunkofthebodyfromtheservletcontainertothewebserver(andpresumably,ontothebrowser).

4 SendHeaders

Sendtheresponseheadersfromtheservletcontainertothewebserver(andpresumably,ontothebrowser).

5 EndResponse

Markstheendoftheresponse(andthustherequest-handlingcycle).

6 GetBody Getfurtherdatafromtherequestifithasn'tall

Page 1233: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Chunk beentransferredyet.9 CPong

ReplyThereplytoaCPingrequest

Eachoftheabovemessageshasadifferentinternalstructure,detailedbelow.

Page 1234: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RequestPacketStructure

FormessagesfromtheservertothecontaineroftypeForwardRequest:

AJP13_FORWARD_REQUEST:=

prefix_code(byte)0x02=JK_AJP13_FORWARD_REQUEST

method(byte)

protocol(string)

req_uri(string)

remote_addr(string)

remote_host(string)

server_name(string)

server_port(integer)

is_ssl(boolean)

num_headers(integer)

request_headers*(req_header_namereq_header_value)

attributes*(attribut_nameattribute_value)

request_terminator(byte)OxFF

request_headershavethefollowingstructure:

req_header_name:=

sc_req_header_name|(string)[seebelowforhowthisisparsed]

sc_req_header_name:=0xA0xx(integer)

req_header_value:=(string)

attributesareoptionalandhavethefollowingstructure:

attribute_name:=sc_a_name|(sc_a_req_attributestring)

attribute_value:=(string)

Page 1235: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Notthattheall-importantheaderiscontent-length,becauseitdetermineswhetherornotthecontainerlooksforanotherpacketimmediately.

DetaileddescriptionoftheelementsofForwardRequestRequestprefixForallrequests,thiswillbe2.SeeabovefordetailsonotherPrefixcodes.

MethodTheHTTPmethod,encodedasasinglebyte:

CommandName CodeOPTIONS 1GET 2HEAD 3POST 4PUT 5DELETE 6TRACE 7PROPFIND 8PROPPATCH 9MKCOL 10COPY 11MOVE 12LOCK 13UNLOCK 14ACL 15

Page 1236: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

REPORT 16VERSION-CONTROL 17CHECKIN 18CHECKOUT 19UNCHECKOUT 20SEARCH 21MKWORKSPACE 22UPDATE 23LABEL 24MERGE 25BASELINE_CONTROL 26MKACTIVITY 27

Laterversionofajp13,willtransportadditionalmethods,eveniftheyarenotinthislist.

protocol,req_uri,remote_addr,remote_host,server_name,server_port,is_sslTheseareallfairlyself-explanatory.Eachoftheseisrequired,andwillbesentforeveryrequest.

HeadersThestructureofrequest_headersisthefollowing:First,thenumberofheadersnum_headersisencoded.Then,aseriesofheadernamereq_header_name/valuereq_header_valuepairsfollows.Commonheadernamesareencodedasintegers,tosavespace.Iftheheadernameisnotinthelistofbasicheaders,itisencodednormally(asastring,withprefixedlength).Thelistofcommonheaderssc_req_header_nameandtheircodesisasfollows(allarecase-sensitive):

Page 1237: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Name Codevalue Codenameaccept 0xA001 SC_REQ_ACCEPTaccept-charset 0xA002 SC_REQ_ACCEPT_CHARSETaccept-encoding 0xA003 SC_REQ_ACCEPT_ENCODINGaccept-language 0xA004 SC_REQ_ACCEPT_LANGUAGEauthorization 0xA005 SC_REQ_AUTHORIZATIONconnection 0xA006 SC_REQ_CONNECTIONcontent-type 0xA007 SC_REQ_CONTENT_TYPEcontent-length 0xA008 SC_REQ_CONTENT_LENGTHcookie 0xA009 SC_REQ_COOKIEcookie2 0xA00A SC_REQ_COOKIE2host 0xA00B SC_REQ_HOSTpragma 0xA00C SC_REQ_PRAGMAreferer 0xA00D SC_REQ_REFERERuser-agent 0xA00E SC_REQ_USER_AGENT

TheJavacodethatreadsthisgrabsthefirsttwo-byteintegerandifitseesan'0xA0'inthemostsignificantbyte,itusestheintegerinthesecondbyteasanindexintoanarrayofheadernames.Ifthefirstbyteisnot0xA0,itassumesthatthetwo-byteintegeristhelengthofastring,whichisthenreadin.

Thisworksontheassumptionthatnoheadernameswillhavelengthgreaterthan0x9999(==0xA000-1),whichisperfectlyreasonable,thoughsomewhatarbitrary.

Thecontent-lengthheaderisextremelyimportant.Ifitispresentandnon-zero,thecontainerassumesthattherequesthasabody(aPOSTrequest,forexample),andimmediatelyreadsaseparatepacketofftheinputstreamtogetthatbody.

Page 1238: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AttributesTheattributesprefixedwitha?(e.g.?context)arealloptional.Foreach,thereisasinglebytecodetoindicatethetypeofattribute,andthenastringtogiveitsvalue.Theycanbesentinanyorder(thoghtheCcodealwayssendsthemintheorderlistedbelow).Aspecialterminatingcodeissenttosignaltheendofthelistofoptionalattributes.Thelistofbytecodesis:

Information CodeValue Note?context 0x01 Notcurrentlyimplemented?servlet_path 0x02 Notcurrentlyimplemented?remote_user 0x03?auth_type 0x04?query_string 0x05?jvm_route 0x06?ssl_cert 0x07?ssl_cipher 0x08?ssl_session 0x09?req_attribute 0x0A Name(thenameoftheattributefollows)?ssl_key_size 0x0Bare_done 0xFF request_terminator

contextservlet_patharenotcurrentlysetbytheCcode,andmostoftheJavacodecompletelyignoreswhateverissentoverforthosefields(andsomeofitwillactuallybreakifastringissentalongafteroneofthosecodes).Idon'tknowifthisisabugoranunimplementedfeatureorjustvestigialcode,butit'smissingfrombothsidesoftheconnection.

remote_userauth_typepresumablyrefertoHTTP-levelauthentication,andcommunicatetheremoteuser'susernameandthetypeofauthenticationusedtoestablishtheiridentity(e.g.Basic,

Page 1239: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Digest).

query_string,ssl_cert,ssl_cipher,andssl_sessionrefertothecorrespondingpiecesofHTTPandHTTPS.

jvm_route,isusedtosupportstickysessions--associatingauser'ssessonwithaparticularTomcatinstanceinthepresenceofmultiple,load-balancingservers.

Beyondthislistofbasicattributes,anynumberofotherattributescanbesentviathereq_attributecode0x0A.Apairofstringstorepresenttheattributenameandvaluearesentimmediatelyaftereachinstanceofthatcode.Environmentvaluesarepassedinviathismethod.

Finally,afteralltheattributeshavebeensent,theattributeterminator,0xFF,issent.ThissignalsboththeendofthelistofattributesandalsothenendoftheRequestPacket.

Page 1240: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ResponsePacketStructure

formessageswhichthecontainercansendbacktotheserver.

AJP13_SEND_BODY_CHUNK:=

prefix_code3

chunk_length(integer)

chunk*(byte)

AJP13_SEND_HEADERS:=

prefix_code4

http_status_code(integer)

http_status_msg(string)

num_headers(integer)

response_headers*(res_header_nameheader_value)

res_header_name:=

sc_res_header_name|(string)[seebelowforhowthisisparsed]

sc_res_header_name:=0xA0(byte)

header_value:=(string)

AJP13_END_RESPONSE:=

prefix_code5

reuse(boolean)

AJP13_GET_BODY_CHUNK:=

prefix_code6

requested_length(integer)

Details:SendBodyChunk

Page 1241: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Thechunkisbasicallybinarydata,andissentdirectlybacktothebrowser.

SendHeadersThestatuscodeandmessagearetheusualHTTPthings(e.g.200OK).Theresponseheadernamesareencodedthesamewaytherequestheadernamesare.Seeheader_encodingabovefordetailsabouthowthethecodesaredistinguishedfromthestrings.Thecodesforcommonheadersare:

Name CodevalueContent-Type 0xA001Content-Language 0xA002Content-Length 0xA003Date 0xA004Last-Modified 0xA005Location 0xA006Set-Cookie 0xA007Set-Cookie2 0xA008Servlet-Engine 0xA009Status 0xA00AWWW-Authenticate 0xA00B

Afterthecodeorthestringheadername,theheadervalueisimmediatelyencoded.

EndResponseSignalstheendofthisrequest-handlingcycle.Ifthereuseflagistrue(==1),thisTCPconnectioncannowbeusedtohandlenewincomingrequests.Ifreuseisfalse(anythingotherthan1intheactualCcode),theconnectionshouldbeclosed.

Page 1242: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

GetBodyChunkThecontainerasksformoredatafromtherequest(Ifthebodywastoolargetofitinthefirstpacketsentoverorwhentherequestischuncked).Theserverwillsendabodypacketbackwithanamountofdatawhichistheminimumoftherequest_length,themaximumsendbodysize(8186(8Kbytes-6)),andthenumberofbytesactuallylefttosendfromtherequestbody.Ifthereisnomoredatainthebody(i.e.theservletcontaineristryingtoreadpasttheendofthebody),theserverwillsendbackanemptypacket,whichisabodypacketwithapayloadlengthof0.(0x12,0x34,0x00,0x00)

Page 1243: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1244: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_proxy_balancer

mod_proxy

(E)proxy_balancer_moduleproxy_balancer.cApache2.1

Thismodulerequirestheserviceofmod_proxy.ItprovidesloadbalancingsupportforHTTP,FTPAJP13protocols

Thus,inordertogettheabilityofloadbalancing,mod_proxymod_proxy_balancerhavetobepresentintheserver.

Internet

Page 1245: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Loadbalancerscheduleralgorithm

Atpresent,thereare2loadbalancerscheduleralgorithmsavailableforuse:RequestCountingandWeightedTrafficCounting.ThesearecontrolledviathelbmethodvalueoftheBalancerdefinition.SeetheProxydirectiveformoreinformation.

Page 1246: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RequestCountingAlgorithm

Enabledvialbmethod=byrequests,theideabehindthisscheduleristhatwedistributetherequestsamongthevariousworkerstoensurethateachgetstheirconfiguredshareofthenumberofrequests.Itworksasfollows:

lbfactorishowmuchweexpectthisworkertowork,ortheworkers'sworkquota.Thisisanormalizedvaluerepresentingtheir"share"oftheamountofworktobedone.

lbstatusishowurgentthisworkerhastoworktofulfillitsquotaofwork.

workerisamemberoftheloadbalancer,usuallyaremotehostservingoneofthesupportedprotocols.

Wedistributeeachworker'sworkquotatotheworker,andthenlookwhichofthemneedstoworkmosturgently(biggestlbstatus).Thisworkeristhenselectedforwork,anditslbstatusreducedbythetotalworkquotawedistributedtoallworkers.Thusthesumofalllbstatusdoesnotchange(*)andwedistributetherequestsasdesired.

Ifsomeworkersaredisabled,theotherswillstillbescheduledcorrectly.

foreachworkerinworkers

workerlbstatus+=workerlbfactor

totalfactor+=workerlbfactor

ifworkerlbstatus>candidatelbstatus

candidate=worker

candidatelbstatus-=totalfactor

Ifabalancerisconfiguredasfollows:

worker a b c d

Page 1247: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

lbfactor 25 25 25 25

lbstatus 0 0 0 0

Andbgetsdisabled,thefollowingscheduleisproduced:

worker a b c dlbstatus -50 0 25 25

lbstatus -25 0 -25 50

lbstatus 0 0 0 0

(repeat)

Thatisitschedules:acdacdacd...Pleasenotethat:

worker a b c dlbfactor 25 25 25 25

Hastheexactsamebehavioras:

worker a b c dlbfactor 1 1 1 1

Thisisbecauseallvaluesoflbfactorarenormalizedwithrespecttotheothers.For:

worker a b clbfactor 1 4 1

workerbwill,onaverage,get4timestherequeststhatacwill.

Thefollowingasymmetricconfigurationworksasonewouldexpect:

worker a blbfactor 70 30

Page 1248: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

lbstatus -30 30

lbstatus 40 -40

lbstatus 10 -10

lbstatus -20 20

lbstatus -50 50

lbstatus 20 -20

lbstatus -10 10

lbstatus -40 40

lbstatus 30 -30

lbstatus 0 0

(repeat)

Thatisafter10schedules,theschedulerepeatsand7aareselectedwith3binterspersed.

Page 1249: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

WeightedTrafficCountingAlgorithm

Enabledvialbmethod=bytraffic,theideabehindthisschedulerisverysimilartotheRequestCountingmethod,withthefollowingchanges:

lbfactorishowmuchtraffic,inbytes,wewantthisworkertohandle.Thisisalsoanormalizedvaluerepresentingtheir"share"oftheamountofworktobedone,butinsteadofsimplycountingthenumberofrequests,wetakeintoaccounttheamountoftrafficthisworkerhasseen.

Ifabalancerisconfiguredasfollows:

worker a b clbfactor 1 2 1

Thenwemeanthatwewantbtoprocesstwicetheamountofbytesthanacshould.Itdoesnotnecessarilymeanthatbwouldhandletwiceasmanyrequests,butitwouldprocesstwicetheI/O.Thus,thesizeoftherequestandresponseareappliedtotheweightingandselectionalgorithm.

Page 1250: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

EnablingBalancerManagerSupport

Thismodulerequirestheserviceofmod_status.Balancermanagerenablesdynamicupdateofbalancermembers.Youcanusebalancermanagertochangethebalancefactororaparticularmember,orputitintheofflinemode.

Thus,inordertogettheabilityofloadbalancermanagement,mod_statusmod_proxy_balancerhavetobepresentintheserver.

Toenableloadbalancermanagementforbrowsersfromthefoo.comdomainaddthiscodetoyourhttpd.confconfigurationfile

<Location/balancer-manager>

SetHandlerbalancer-manager

OrderDeny,Allow

Denyfromall

Allowfrom.foo.com

</Location>

YoucannowaccessloadbalancermanagerbyusingaWebbrowsertoaccessthepagehttp://your.server.name/balancer-manager

Page 1251: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006128|

Page 1252: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Apachemod_proxy_connect

mod_proxyHTTP CONNECT

(E)proxy_connect_moduleproxy_connect.c

mod_proxyHTTP CONNECTSSL

CONNECT mod_proxymod_proxy_connect

Internet

Page 1253: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006128|

Page 1254: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_proxy_ftp

mod_proxyFTP(E)proxy_ftp_moduleproxy_ftp.c

FTP mod_proxyFTP mod_proxymod_proxy_ftp

FTPGET

Internet

Page 1255: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

xxxFTP

mimeapplication/octet-stream

application/octet-streambindmslhalzhexeclasstgztaz

DefaultTypeapplication/octet-stream

Page 1256: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

xxxFTPASCII

FTP ASCII( binary)" ;type=a" mod_proxyASCIIFTPASCII

Page 1257: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FTP

mod_proxyFTPGETFTPApacheHTTP(POSTPUT)

Page 1258: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

homeFTP

FTPURIhome"/../"(.)FTPApacheFTP" Squid%2fhack" SquidProxyCache" /%2f"FTP" /"(home)

/etc/motdURL

ftp://user@host/%2f/etc/motd

Page 1259: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

URLFTP

FTPApacheURLApacheFTP

user:anonymous

password:apache_proxy@

FTP

URL

ftp://username@host/myfile

FTP()Apache" 401"()/

ftp://username:password@host/myfile

Apachebase64ApacheFTPHTTPFTP(FTP)

Page 1260: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006128|

Page 1261: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Apachemod_proxy_http

mod_proxyHTTP(E)proxy_http_moduleproxy_http.c

mod_proxyHTTP mod_proxy_httpHTTP/0.9,HTTP/1.0,HTTP/1.1 mod_cache

HTTP mod_proxymod_proxy_http

Internet

Page 1262: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1263: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_rewrite

URL(E)rewrite_modulemod_rewrite.cApache1.3

URLURLURLHTTPURL

URL()( httpd.conf)(.htaccess)

URL

Page 1264: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache1.3.20 TestStringSubstitution(\)() Substitution" \$"mod_rewrite

Page 1265: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

()CGI/SSI SCRIPT_URLSCRIPT_URICGI/SSISCRIPT_NAMESCRIPT_FILENAME

URI/URL URI/URLURL

SCRIPT_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/

Page 1266: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URLURLURL

Page 1267: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteBase

URLRewriteBaseURL-path

directory,.htaccessFileInfo(E)mod_rewrite

RewriteBaseURL RewriteRule(.htaccess)" RewriteBasephysical-directory-path"

URLURLURLURL URL!RewriteBaseURL

URL RewriteBase .htaccessRewriteRule

#

#/abc/def/.htaccess--per-dirconfigfilefordirectory/abc/def

#Remember:/abc/defisthephysicalpathof/xyz,i.e.

#hasa'Alias/xyz/abc/def'directive

#

RewriteEngineOn

#lettheserverknowthatwewerereachedvia/xyzandnot

#viathephysicalpathprefix/abc/def

RewriteBase/xyz

#nowtherewritingrules

RewriteRule^oldstuff\.html$newstuff.html

Page 1268: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

/xyz/oldstuff.html/abc/def/newstuff.html

ForApacheHackers

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

()ApacheApacheApacheApache

Page 1269: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteCond

RewriteCondTestStringCondPattern

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_rewrite

RewriteCond RewriteRuleRewriteCondURIpattern

TestString

RewriteRule

$N

(0<=N<=9)( RewriteRule) RewriteCondpattern(!)RewriteCond

%N

(1<=N<=9)RewriteCond(!)RewriteMap

${mapname:key|default}

RewriteMap

%{NAME_OF_VARIABLE}

NAME_OF_VARIABLE

HTTPheaders: connection&request:

HTTP_USER_AGENT REMOTE_ADDR

Page 1270: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HTTP_REFERERHTTP_COOKIEHTTP_FORWARDEDHTTP_HOSTHTTP_PROXY_CONNECTIONHTTP_ACCEPT

REMOTE_HOSTREMOTE_PORTREMOTE_USERREMOTE_IDENTREQUEST_METHODSCRIPT_FILENAMEPATH_INFOQUERY_STRINGAUTH_TYPE

serverinternals: dateandtime: 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_rewriteinclude:

IS_SUBREQ

Willcontainthetext"true"iftherequestcurrentlybeingprocessedisasub-request,"false"otherwise.Sub-requestsmaybegeneratedbymodulesthatneedtoresolveadditionalfilesorURIsinordertocompletetheirtasks.

API_VERSION

ThisistheversionoftheApachemoduleAPI(theinternal

Page 1271: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

interfacebetweenserverandmodule)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.(Thisvariablecanbesafelyusedregardlessofwhethermod_sslisloaded).

SpecialNotes:

1. ThevariablesSCRIPT_FILENAMEandREQUEST_FILENAMEcontainthesamevalue,i.e.,thevalueofthefilenamefieldoftheinternalrequest_recstructureoftheApacheserver.ThefirstnameisjustthecommonlyknownCGIvariablenamewhilethesecondistheconsistentcounterparttoREQUEST_URI(whichcontainsthevalueoftheurifieldofrequest_rec).

2. Thereisthespecialformat:%{ENV:variable}wherevariablecanbeanyenvironmentvariable.Thisislooked-upviainternalApachestructuresand(ifnotfoundthere)viagetenv()fromtheApacheserverprocess.

Page 1272: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

3. Thereisthespecialformat:%{SSL:variable}wherevariableisthenameofanSSLenvironmentvariable;thiscanbeusedwhetherornotmod_sslisloaded,butwillalwaysexpandtotheemptystringifitisnot.Example:%{SSL:SSL_CIPHER_USEKEYSIZE}mayexpandto128.

4. Thereisthespecialformat:%{HTTP:header}whereheadercanbeanyHTTPMIME-headername.Thisislooked-upfromtheHTTPrequest.Example:%{HTTP:Proxy-Connection}isthevalueoftheHTTPheader"Proxy-Connection:".

5. Thereisthespecialformat%{LA-U:variable}forlook-aheadswhichperformaninternal(URL-based)sub-requesttodeterminethefinalvalueofvariable.UsethiswhenyouwanttouseavariableforrewritingwhichisactuallysetlaterinanAPIphaseandthusisnotavailableatthecurrentstage.ForinstancewhenyouwanttorewriteaccordingtotheREMOTE_USERvariablefromwithintheper-servercontext(httpd.conffile)youhavetouse%{LA-U:REMOTE_USER}becausethisvariableissetbytheauthorizationphaseswhichcomeaftertheURLtranslationphasewheremod_rewriteoperates.Ontheotherhand,becausemod_rewriteimplementsitsper-directorycontext(.htaccessfile)viatheFixupphaseoftheAPIandbecausetheauthorizationphasescomebeforethisphase,youjustcanuse%{REMOTE_USER}there.

6. Thereisthespecialformat:%{LA-F:variable}whichperformsaninternal(filename-based)sub-requesttodeterminethefinalvalueofvariable.MostofthetimethisisthesameasLA-Uabove.

CondPatternistheconditionpattern,i.e.,aregularexpressionwhichisappliedtothecurrentinstanceoftheTestString,i.e.,TestStringisevaluatedandthenmatchedagainstCondPattern.

Remember:CondPatternisaperlcompatibleregularexpressionwith

Page 1273: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

someadditions:

1. Youcanprefixthepatternstringwitha'!'character(exclamationmark)tospecifyanon-matchingpattern.

2. TherearesomespecialvariantsofCondPatterns.Insteadofrealregularexpressionstringsyoucanalsouseoneofthefollowing:

'<CondPattern'(islexicallylower)TreatstheCondPatternasaplainstringandcomparesitlexicallytoTestString.TrueifTestStringislexicallylowerthanCondPattern.

'>CondPattern'(islexicallygreater)TreatstheCondPatternasaplainstringandcomparesitlexicallytoTestString.TrueifTestStringislexicallygreaterthanCondPattern.

'=CondPattern'(islexicallyequal)TreatstheCondPatternasaplainstringandcomparesitlexicallytoTestString.TrueifTestStringislexicallyequaltoCondPattern,i.ethetwostringsareexactlyequal(characterbycharacter).IfCondPatternisjust""(twoquotationmarks)thiscomparesTestStringtotheemptystring.

'-d'(isdirectory)TreatstheTestStringasapathnameandtestsifitexistsandisadirectory.

'-f'(isregularfile)TreatstheTestStringasapathnameandtestsifitexistsandisaregularfile.

'-s'(isregularfilewithsize)TreatstheTestStringasapathnameandtestsifitexistsandisaregularfilewithsizegreaterthanzero.

'-l'(issymboliclink)TreatstheTestStringasapathnameandtestsifitexistsand

Page 1274: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

isasymboliclink.

'-x'(hasexecutablepermissions)TreatstheTestStringasapathnameandtestsifitexistsandhasexecutionpermissions.ThesepermissionsaredetermineddependingontheunderlyingOS.

'-F'(isexistingfileviasubrequest)ChecksifTestStringisavalidfileandaccessibleviaalltheserver'scurrently-configuredaccesscontrolsforthatpath.Thisusesaninternalsubrequesttodeterminethecheck,souseitwithcarebecauseitdecreasesyourserversperformance!

'-U'(isexistingURLviasubrequest)ChecksifTestStringisavalidURLandaccessibleviaalltheserver'scurrently-configuredaccesscontrolsforthatpath.Thisusesaninternalsubrequesttodeterminethecheck,souseitwithcarebecauseitdecreasesyourserver'sperformance!

Notice

Allofthesetestscanalsobeprefixedbyanexclamationmark('!')tonegatetheirmeaning.

AdditionallyyoucansetspecialflagsforCondPatternbyappending

[flags]

asthethirdargumenttotheRewriteConddirective.Flagsisacomma-separatedlistofthefollowingflags:

'nocase|NC'(nocase)Thismakesthetestcase-insensitive,i.e.,thereisnodifferencebetween'A-Z'and'a-z'bothintheexpandedTestStringandtheCondPattern.Thisflagiseffectiveonlyforcomparisonsbetween

Page 1275: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TestStringCondPattern.Ithasnoeffectonfilesystemandsubrequestchecks.'ornext|OR'(nextcondition)UsethistocombineruleconditionswithalocalORinsteadoftheimplicitAND.Typicalexample:

RewriteCond%{REMOTE_HOST}^host1.*[OR]

RewriteCond%{REMOTE_HOST}^host2.*[OR]

RewriteCond%{REMOTE_HOST}^host3.*

RewriteRule...somespecialstuffforanyofthesehosts...

Withoutthisflagyouwouldhavetowritethecond/rulethreetimes.

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]

Interpretation:IfyouuseNetscapeNavigatorasyourbrowser(whichidentifiesitselfas'Mozilla'),thenyougetthemaxhomepage,whichincludesFrames,etc.IfyouusetheLynxbrowser(whichisTerminal-based),thenyougettheminhomepage,whichcontainsnoimages,notables,etc.Ifyouuseanyotherbrowseryougetthestandardhomepage.

Page 1276: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteEngine

EnablesordisablesruntimerewritingengineRewriteEngineon|off

RewriteEngineoff

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_rewrite

RewriteEnginedirectiveenablesordisablestheruntimerewritingengine.Ifitissettooffthismoduledoesnoruntimeprocessingatall.ItdoesnotevenupdatetheSCRIPT_URxenvironmentvariables.

UsethisdirectivetodisablethemoduleinsteadofcommentingoutalltheRewriteRuledirectives!

Notethat,bydefault,rewriteconfigurationsarenotinherited.ThismeansthatyouneedtohaveaRewriteEngineondirectiveforeachvirtualhostinwhichyouwishtouseit.

Page 1277: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteLock

SetsthenameofthelockfileusedforRewriteMapsynchronizationRewriteLockfile-path

serverconfig(E)mod_rewrite

Thisdirectivesetsthefilenameforasynchronizationlockfilewhichmod_rewriteneedstocommunicatewithRewriteMapprograms.Setthislockfiletoalocalpath(notonaNFS-mounteddevice)whenyouwanttousearewritingmap-program.Itisnotrequiredforothertypesofrewritingmaps.

Page 1278: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteLog

SetsthenameofthefileusedforloggingrewriteengineprocessingRewriteLogfile-path

serverconfig,virtualhost(E)mod_rewrite

RewriteLogdirectivesetsthenameofthefiletowhichtheserverlogsanyrewritingactionsitperforms.Ifthenamedoesnotbeginwithaslash('/')thenitisassumedtoberelativetotheServerRoot.Thedirectiveshouldoccuronlyonceperserverconfig.

TodisabletheloggingofrewritingactionsitisnotrecommendedtosetFilenameto/dev/null,becausealthoughtherewritingenginedoesnotthenoutputtoalogfileitstillcreatesthelogfileoutputinternally.Thiswillslowdowntheserverwithnoadvantagetotheadministrator!TodisableloggingeitherremoveorcommentouttheRewriteLogdirectiveoruseRewriteLogLevel0!

SeetheApacheSecurityTipsdocumentfordetailsonwhyyoursecuritycouldbecompromisedifthedirectorywherelogfilesarestorediswritablebyanyoneotherthantheuserthatstartstheserver.

RewriteLog

"/usr/local/var/apache/logs/rewrite.log"

Page 1279: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteLogLevel

SetstheverbosityofthelogfileusedbytherewriteengineRewriteLogLevelLevel

RewriteLogLevel0

serverconfig,virtualhost(E)mod_rewrite

RewriteLogLeveldirectivesetstheverbosityleveloftherewritinglogfile.Thedefaultlevel0meansnologging,while9ormoremeansthatpracticallyallactionsarelogged.

TodisabletheloggingofrewritingactionssimplysetLevelto0.Thisdisablesallrewriteactionlogs.

UsingahighvalueforLevelwillslowdownyourApacheserverdramatically!UsetherewritinglogfileataLevelgreaterthan2onlyfordebugging!

RewriteLogLevel3

Page 1280: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteMap

Definesamappingfunctionforkey-lookupRewriteMapMapNameMapType:MapSource

serverconfig,virtualhost(E)mod_rewriteThechoiceofdifferentdbmtypesisavailableinApache2.0.41

RewriteMapdirectivedefinesaRewritingMapwhichcanbeusedinsiderulesubstitutionstringsbythemapping-functionstoinsert/substitutefieldsthroughakeylookup.Thesourceofthislookupcanbeofvarioustypes.

MapNameisthenameofthemapandwillbeusedtospecifyamapping-functionforthesubstitutionstringsofarewritingruleviaoneofthefollowingconstructs:

${MapName:LookupKey}${MapName:LookupKey|DefaultValue}

WhensuchaconstructoccursthemapMapNameisconsultedandthekeyLookupKeyislooked-up.Ifthekeyisfound,themap-functionconstructissubstitutedbySubstValue.IfthekeyisnotfoundthenitissubstitutedbyDefaultValueorbytheemptystringifnoDefaultValuewasspecified.

Forexample,youmightdefineaRewriteMapas:

RewriteMapexamplemaptxt:/path/to/file/map.txt

YouwouldthenbeabletousethismapinaRewriteRuleasfollows:

Page 1281: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteRule^/ex/(.*)${examplemap:$1}

ThefollowingcombinationsforMapTypeMapSourcecanbeused:

StandardPlainTextMapType:txt,MapSource:UnixfilesystempathtovalidregularfileThisisthestandardrewritingmapfeaturewheretheMapSourceisaplainASCIIfilecontainingeitherblanklines,commentlines(startingwitha'#'character)orpairslikethefollowing-oneperline.

MatchingKeySubstValue

##

##map.txt--rewritingmap

##

Ralf.S.Engelschallrse#BastardOperatorFromHell

Mr.Joe.Averagejoe#Mr.Average

RewriteMapreal-to-user

txt:/path/to/file/map.txt

RandomizedPlainTextMapType:rnd,MapSource:UnixfilesystempathtovalidregularfileThisisidenticaltotheStandardPlainTextvariantabovebutwithaspecialpost-processingfeature:Afterlookingupavalueitisparsedaccordingtocontained"|"characterswhichhavethemeaningof"or".Inotherwordstheyindicateasetofalternativesfromwhichtheactualreturnedvalueischosenrandomly.For

Page 1282: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

example,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.Ifthetypeisomitted,thecompile-timedefaultwillbechosen.YoucancreatesuchafilewithanyDBMtoolorwiththefollowingPerlscript.Besuretoadjustittocreatetheappropriate

Page 1283: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

typeofDBM.TheexamplecreatesanNDBMfile.

#!/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:InternalApachefunctionHerethesourceisaninternalApachefunction.Currentlyyoucannotcreateyourown,butthefollowingfunctionsalreadyexists:

toupper:Convertsthelookedupkeytoalluppercase.tolower:

Page 1284: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Convertsthelookedupkeytoalllowercase.escape:Translatesspecialcharactersinthelookedupkeytohex-encodings.unescape:Translateshex-encodingsinthelookedupkeybacktospecialcharacters.

ExternalRewritingProgramMapType:prg,MapSource:UnixfilesystempathtovalidregularfileHerethesourceisaprogram,notamapfile.Tocreateityoucanusethelanguageofyourchoice,buttheresulthastobeaexecutable(i.e.,eitherobject-codeorascriptwiththemagiccookietrick'#!/path/to/interpreter'asthefirstline).

ThisprogramisstartedonceatstartupoftheApacheserversandthencommunicateswiththerewritingengineoveritsstdinstdoutfile-handles.Foreachmap-functionlookupitwillreceivethekeytolookupasanewline-terminatedstringonstdin.Itthenhastogivebackthelooked-upvalueasanewline-terminatedstringonstdoutorthefour-characterstring"NULL"ifitfails(i.e.,thereisnocorrespondingvalueforthegivenkey).Atrivialprogramwhichwillimplementa1:1map(i.e.,key==value)couldbe:

#!/usr/bin/perl

$|=1;

while(<STDIN>){

#...puthereanytransformationsorlookups...

print$_;

}

Butbeverycareful:

Page 1285: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

1. "Keepitsimple,stupid"(KISS),becauseifthisprogramhangsitwillhangtheApacheserverwhentheruleoccurs.

2. Avoidonecommonmistake:neverdobufferedI/Oonstdout!Thiswillcauseadeadloop!Hencethe"$|=1"intheaboveexample...

3. UsetheRewriteLockdirectivetodefinealockfilemod_rewritecanusetosynchronizethecommunicationtotheprogram.Bydefaultnosuchsynchronizationtakesplace.

RewriteMapdirectivecanoccurmorethanonce.Foreachmapping-functionuseoneRewriteMapdirectivetodeclareitsrewritingmapfile.Whileyoucannotdeclareamapinper-directorycontextitisofcoursepossibletousethismapinper-directorycontext.

ForplaintextandDBMformatfilesthelooked-upkeysarecachedin-coreuntilthemtimeofthemapfilechangesortheserverdoesarestart.Thiswayyoucanhavemap-functionsinruleswhichareusedforeveryrequest.Thisisnoproblem,becausetheexternallookuponlyhappensonce!

Page 1286: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteOptions

SetssomespecialoptionsfortherewriteengineRewriteOptionsOptions

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_rewriteMaxRedirectsisnolongeravailableinversion2.1

RewriteOptionsdirectivesetssomespecialoptionsforthecurrentper-serverorper-directoryconfiguration.TheOptionstringcanbecurrentlyonlyone:

inherit

Thisforcesthecurrentconfigurationtoinherittheconfigurationoftheparent.Inper-virtual-servercontextthismeansthatthemaps,conditionsandrulesofthemainserverareinherited.Inper-directorycontextthismeansthatconditionsandrulesoftheparentdirectory's.htaccessconfigurationareinherited.

Page 1287: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteRule

DefinesrulesfortherewritingengineRewriteRulePatternSubstitution

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_rewriteThecookie-flagisavailableinApache2.0.40

RewriteRuledirectiveistherealrewritingworkhorse.Thedirectivecanoccurmorethanonce.Eachdirectivethendefinesonesinglerewritingrule.Thedefinitionorderoftheserulesisimportant,becausethisorderisusedwhenapplyingtherulesatrun-time.

PatternisaperlcompatibleregularexpressionwhichgetsappliedtothecurrentURL.Here"current"meansthevalueoftheURLwhenthisrulegetsapplied.ThismaynotbetheoriginallyrequestedURL,becauseanynumberofrulesmayalreadyhavematchedandmadealterationstoit.

Somehintsaboutthesyntaxofregularexpressions:

Text:

.Anysinglecharacter

[chars]Characterclass:Oneofchars

[^chars]Characterclass:Noneofchars

text1|text2Alternative:text1ortext2

Quantifiers:

?0or1oftheprecedingtext

*0orNoftheprecedingtext(N>0)

+1orNoftheprecedingtext(N>1)

Page 1288: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Grouping:

(text)Groupingoftext

(eithertosetthebordersofanalternativeor

formakingbackreferenceswheretheNthgroupcan

beusedontheRHSofaRewriteRulewith

Anchors:

^Startoflineanchor

$Endoflineanchor

Escaping:

\charescapethatparticularchar

(forinstancetospecifythechars".[]()

Formoreinformationaboutregularexpressionshavealookattheperlregularexpressionmanpage("perldocperlre").Ifyouareinterestedinmoredetailedinformationaboutregularexpressionsandtheirvariants(POSIXregexetc.)havealookatthefollowingdedicatedbookonthistopic:

MasteringRegularExpressions,2ndEditionJeffreyE.F.FriedlO'Reilly&Associates,Inc.2002ISBN0-596-00289-0

Additionallyinmod_rewritetheNOTcharacter('!')isapossiblepatternprefix.Thisgivesyoutheabilitytonegateapattern;tosay,forinstance:"ifthecurrentURLdoesNOTmatchthispattern".Thiscanbeusedforexceptionalcases,whereitiseasiertomatchthenegativepattern,orasalastdefaultrule.

NoticeWhenusingtheNOTcharactertonegateapatternyoucannot

Page 1289: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

havegroupedwildcardpartsinthepattern.ThisisimpossiblebecausewhenthepatterndoesNOTmatch,therearenocontentsforthegroups.Inconsequence,ifnegatedpatternsareused,youcannotuse$Ninthesubstitutionstring!

Substitutionofarewritingruleisthestringwhichissubstitutedfor(orreplaces)theoriginalURLforwhichPatternmatched.Besideplaintextyoucanuse

1. back-references$NtotheRewriteRulepattern

2. back-references%NtothelastmatchedRewriteCondpattern

3. server-variablesasinruleconditiontest-strings(%{VARNAME})

4. mapping-functioncalls(${mapname:key|default})

Back-referencesare$N(N=0..9)identifierswhichwillbereplacedbythecontentsoftheNthgroupofthematchedPattern.Theserver-variablesarethesameasfortheTestStringofaRewriteConddirective.Themapping-functionscomefromtheRewriteMapdirectiveandareexplainedthere.Thesethreetypesofvariablesareexpandedintheorderoftheabovelist.

Asalreadymentionedabove,alltherewritingrulesareappliedtotheSubstitution(intheorderofdefinitionintheconfigfile).TheURLiscompletelyreplacedbytheSubstitutionandtherewritingprocessgoesonuntiltherearenomorerulesunlessexplicitlyterminatedbyaLflag-seebelow.

Thereisaspecialsubstitutionstringnamed'-'whichmeans:NOsubstitution!Soundssilly?No,itisusefultoproviderewritingruleswhichonlymatchsomeURLsbutdonosubstitution,inconjunctionwiththeC(chain)flagtobeabletohavemorethanonepatterntobeappliedbeforeasubstitutionoccurs.

QueryString

Page 1290: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Patternwillnotmatchagainstthequerystring.Instead,youmustuseaRewriteCondwiththe%{QUERY_STRING}variable.Youcan,however,createURLsinthesubstitutionstringcontainingaquerystringpart.Justuseaquestionmarkinsidethesubstitutionstringtoindicatethatthefollowingstuffshouldbere-injectedintothequerystring.Whenyouwanttoeraseanexistingquerystring,endthesubstitutionstringwithjustthequestionmark.Tocombineanewquerystringwithanoldone,usethe[QSA]flag(seebelow).

SubstitutionofAbsoluteURLs

Thereisaspecialfeature:Whenyouprefixasubstitutionfieldwithhttp://thishost[:thisport]thenmod_rewriteautomaticallystripsitout.Thisauto-reductiononimplicitexternalredirectURLsisausefulandimportantfeaturewhenusedincombinationwithamapping-functionwhichgeneratesthehostnamepart.Havealookatthefirstexampleintheexamplesectionbelowtounderstandthis.

Remember:Anunconditionalexternalredirecttoyourownserverwillnotworkwiththeprefixhttp://thishostbecauseofthisfeature.Toachievesuchaself-redirect,youhavetousetheR-flag(seebelow).

AdditionallyyoucansetspecialflagsforSubstitutionbyappending

[flags]

asthethirdargumenttotheRewriteRuledirective.Flagsisacomma-separatedlistofthefollowingflags:

'chain|C'(chainedwithnextrule)Thisflagchainsthecurrentrulewiththenextrule(whichitselfcanbechainedwiththefollowingrule,etc.).Thishasthefollowingeffect:ifarulematches,thenprocessingcontinuesas

Page 1291: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

usual,i.e.,theflaghasnoeffect.Iftheruledoesnotmatch,thenallfollowingchainedrulesareskipped.Forinstance,useittoremovethe".www"partinsideaper-directoryrulesetwhenyouletanexternalredirecthappen(wherethe".www"partshouldnottooccur!).'cookie|CO=NAME:VAL:domain[:lifetime[:path]]'(setcookie)Thissetsacookieontheclient'sbrowser.Thecookie'snameisspecifiedbyNAMEandthevalueisVAL.Thedomainfieldisthedomainofthecookie,suchas'.apache.org',theoptionallifetimeisthelifetimeofthecookieinminutes,andtheoptionalpathisthepathofthecookie'env|E=VAR:VAL'(setenvironmentvariable)ThisforcesanenvironmentvariablenamedVARtobesettothevalueVAL,whereVALcancontainregexpbackreferences$N%Nwhichwillbeexpanded.Youcanusethisflagmorethanoncetosetmorethanonevariable.Thevariablescanbelaterdereferencedinmanysituations,butusuallyfromwithinXSSI(via<!--#echovar="VAR"-->)orCGI( $ENV{'VAR'}).AdditionallyyoucandereferenceitinafollowingRewriteCondpatternvia%{ENV:VAR}.UsethistostripbutrememberinformationfromURLs.'forbidden|F'(forceURLtobeforbidden)ThisforcesthecurrentURLtobeforbidden,i.e.,itimmediatelysendsbackaHTTPresponseof403(FORBIDDEN).UsethisflaginconjunctionwithappropriateRewriteCondstoconditionallyblocksomeURLs.'gone|G'(forceURLtobegone)ThisforcesthecurrentURLtobegone,i.e.,itimmediatelysendsbackaHTTPresponseof410(GONE).Usethisflagtomarkpageswhichnolongerexistasgone.'handler|H=Content-handler'(forceContenthandler)ForcetheContent-handlerofthetargetfiletobeContent-handler.Forinstance,thiscanbeusedtosimulatethemod_aliasdirectiveScriptAliaswhichinternallyforcesall

Page 1292: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

filesinsidethemappeddirectorytohaveahandlerof"cgi-script".'last|L'(lastrule)Stoptherewritingprocesshereanddon'tapplyanymorerewritingrules.ThiscorrespondstothePerllastcommandorthebreakcommandfromtheClanguage.UsethisflagtopreventthecurrentlyrewrittenURLfrombeingrewrittenfurtherbyfollowingrules.Forexample,useittorewritetheroot-pathURL('/')toarealone,' /e/www/'.'next|N'(nextround)Re-runtherewritingprocess(startingagainwiththefirstrewritingrule).HeretheURLtomatchisagainnottheoriginalURLbuttheURLfromthelastrewritingrule.ThiscorrespondstothePerlnextcommandorthecontinuecommandfromtheClanguage.Usethisflagtorestarttherewritingprocess,i.e.,toimmediatelygotothetopoftheloop.Butbecarefulnottocreateaninfiniteloop!'nocase|NC'(nocase)ThismakesthePatterncase-insensitive,i.e.,thereisnodifferencebetween'A-Z'and'a-z'whenPatternismatchedagainstthecurrentURL.'noescape|NE'(noURIescapingofoutput)Thisflagkeepsmod_rewritefromapplyingtheusualURIescapingrulestotheresultofarewrite.Ordinarily,specialcharacters(suchas'%','$',';',andsoon)willbeescapedintotheirhexcodeequivalents('%25','%24',and'%3B',respectively);thisflagpreventsthisfrombeingdone.Thisallowspercentsymbolstoappearintheoutput,asin

RewriteRule/foo/(.*)/bar?arg=P1\%3d$1[R,NE]

whichwouldturn'/foo/zed'intoasaferequestfor'/bar?arg=P1=zed'.

Page 1293: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

'nosubreq|NS'(usedonlyifnointernalsub-request)Thisflagforcestherewritingenginetoskiparewritingruleifthecurrentrequestisaninternalsub-request.Forinstance,sub-requestsoccurinternallyinApachewhenmod_includetriestofindoutinformationaboutpossibledirectorydefaultfiles(index.xxx).Onsub-requestsitisnotalwaysusefulandevensometimescausesafailuretoifthecompletesetofrulesareapplied.Usethisflagtoexcludesomerules.Usethefollowingruleforyourdecision:wheneveryouprefixsomeURLswithCGI-scriptstoforcethemtobeprocessedbytheCGI-script,thechanceishighthatyouwillrunintoproblems(orevenoverhead)onsub-requests.Inthesecases,usethisflag.

'proxy|P'(forceproxy)Thisflagforcesthesubstitutionparttobeinternallyforcedasaproxyrequestandimmediately(i.e.,rewritingruleprocessingstopshere)putthroughtheproxymodule.YouhavetomakesurethatthesubstitutionstringisavalidURI(typicallystartingwithhttp://hostname)whichcanbehandledbytheApacheproxymodule.Ifnotyougetanerrorfromtheproxymodule.UsethisflagtoachieveamorepowerfulimplementationoftheProxyPassdirective,tomapsomeremotestuffintothenamespaceofthelocalserver.

mod_proxymustbeenabledinordertousethisflag.

'passthrough|PT'(passthroughtonexthandler)Thisflagforcestherewritingenginetosettheurifieldoftheinternalrequest_recstructuretothevalueofthefilenamefield.Thisflagisjustahacktobeabletopost-processtheoutputofRewriteRuledirectivesbyAlias,ScriptAlias,Redirect,etc.directivesfromotherURI-to-filenametranslators.Atrivialexampletoshowthesemantics:Ifyouwanttorewrite/abcto/defviatherewritingengineofmod_rewriteandthen

Page 1294: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

/defto/ghiwithmod_alias:

RewriteRule^/abc(.*)/def$1[PT]

Alias/def/ghi

IfyouomitthePTflagthenmod_rewritewilldoitsjobfine,i.e.,itrewritesuri=/abc/...tofilename=/def/...asafullAPI-compliantURI-to-filenametranslatorshoulddo.Thenmod_aliascomesandtriestodoaURI-to-filenametransitionwhichwillnotwork.Note:YouhavetousethisflagifyouwanttointermixdirectivesofdifferentmoduleswhichcontainURL-to-filenametranslators.Thetypicalexampleistheuseofmod_aliasmod_rewrite..

'qsappend|QSA'(querystringappend)Thisflagforcestherewritingenginetoappendaquerystringpartinthesubstitutionstringtotheexistingoneinsteadofreplacingit.Usethiswhenyouwanttoaddmoredatatothequerystringviaarewriterule.'redirect|R[=code]'(forceredirect)PrefixSubstitutionwithhttp://thishost[:thisport]/(whichmakesthenewURLaURI)toforceaexternalredirection.IfnocodeisgivenaHTTPresponseof302(MOVEDTEMPORARILY)isused.Ifyouwanttouseotherresponsecodesintherange300-400justspecifythemasanumberoruseoneofthefollowingsymbolicnames:temp(default),permanent,seeother.UseitforruleswhichshouldcanonicalizetheURLandgiveitbacktotheclient,translate"/~"into"/u/"oralwaysappendaslashto/u/user,etc.Note:Whenyouusethisflag,makesurethatthesubstitutionfieldisavalidURL!Ifnot,youareredirectingtoaninvalidlocation!AndrememberthatthisflagitselfonlyprefixestheURLwithhttp://thishost[:thisport]/,rewritingcontinues.

Page 1295: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Usuallyyoualsowanttostopanddotheredirectionimmediately.Tostoptherewritingyoualsohavetoprovidethe'L'flag.

'skip|S=num'(skipnextrule(s))Thisflagforcestherewritingenginetoskipthenextnumrulesinsequencewhenthecurrentrulematches.Usethistomakepseudoif-then-elseconstructs:Thelastruleofthethen-clausebecomesskip=NwhereNisthenumberofrulesintheelse-clause.(Thisisnotthesameasthe'chain|C'flag!)'type|T=MIME-type'(forceMIMEtype)ForcetheMIME-typeofthetargetfiletobeMIME-type.Forinstance,thiscanbeusedtosetupthecontent-typebasedonsomeconditions.Forexample,thefollowingsnippetallows.phpfilestobedisplayedbymod_phpiftheyarecalledwiththe.phpsextension:

RewriteRule^(.+\.php)s$$1[T=application/x-

httpd-php-source]

NeverforgetthatPatternisappliedtoacompleteURLinper-serverconfigurationfiles.Butinper-directoryconfigurationfiles,theper-directoryprefix(whichalwaysisthesameforaspecificdirectory!)isautomaticallyremovedforthepatternmatchingandautomaticallyaddedafterthesubstitutionhasbeendone.Thisfeatureisessentialformanysortsofrewriting,becausewithoutthisprefixstrippingyouhavetomatchtheparentdirectorywhichisnotalwayspossible.

Thereisoneexception:Ifasubstitutionstringstartswith"http://"thenthedirectoryprefixwillnotbeaddedandanexternalredirectorproxythroughput(ifflagPisused!)isforced!

Page 1296: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Toenabletherewritingengineforper-directoryconfigurationfilesyouneedtoset"RewriteEngineOn"inthesefiles"OptionsFollowSymLinks"mustbeenabled.IfyouradministratorhasdisabledoverrideofFollowSymLinksforauser'sdirectory,thenyoucannotusetherewritingengine.Thisrestrictionisneededforsecurityreasons.

Hereareallpossiblesubstitutioncombinationsandtheirmeanings:

Insideper-serverconfiguration(httpd.conf)forrequest"GET/somepath/pathinfo":

GivenRuleResultingSubstitution

--------------------------------------------------------------------------------

^/somepath(.*)otherpath$1notsupported,becauseinvalid!

^/somepath(.*)otherpath$1[R]notsupported,becauseinvalid!

^/somepath(.*)otherpath$1[P]notsupported,becauseinvalid!

--------------------------------------------------------------------------------

^/somepath(.*)/otherpath$1/otherpath/pathinfo

^/somepath(.*)/otherpath$1[R]http://thishost/otherpath/pathinfo

viaexternalredirection

^/somepath(.*)/otherpath$1[P]notsupported,becausesilly!

--------------------------------------------------------------------------------

^/somepath(.*)http://thishost/otherpath$1/otherpath/pathinfo

^/somepath(.*)http://thishost/otherpath$1[R]http://thishost/otherpath/pathinfo

viaexternalredirection

^/somepath(.*)http://thishost/otherpath$1[P]notsupported,becausesilly!

--------------------------------------------------------------------------------

^/somepath(.*)http://otherhost/otherpath$1http://otherhost/otherpath/pathinfo

Page 1297: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Insideper-directoryconfigurationfor/somepath(i.e.,file.htaccessindir/physical/path/to/somepathcontainingRewriteBase/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]notsupported,becausesilly!

--------------------------------------------------------------------------------

^localpath(.*)/otherpath$1/otherpath/pathinfo

^localpath(.*)/otherpath$1[R]http://thishost/otherpath/pathinfo

viaexternalredirection

^localpath(.*)/otherpath$1[P]notsupported,becausesilly!

--------------------------------------------------------------------------------

^localpath(.*)http://thishost/otherpath$1/otherpath/pathinfo

^localpath(.*)http://thishost/otherpath$1[R]http://thishost/otherpath/pathinfo

viaexternalredirection

Page 1298: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

^localpath(.*)http://thishost/otherpath$1[P]notsupported,becausesilly!

--------------------------------------------------------------------------------

^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

Example:

WewanttorewriteURLsoftheform

/Language/~Realname/.../File

into

/u/Username/.../File.Language

Wetaketherewritemapfilefromaboveandsaveitunder/path/to/file/map.txt.ThenweonlyhavetoaddthefollowinglinestotheApacheserverconfigurationfile:

RewriteLog/path/to/file/rewrite.log

RewriteMapreal-to-usertxt:/path/to/file/map.txt

RewriteRule^/([^/]+)/~([^/]+)/(.*)$/u/${real-to-user:$2|nobody}/$3.$1

Page 1299: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006129|

Page 1300: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_setenvif

(B)setenvif_modulemod_setenvif.c

mod_setenvif

mozillaMSIE netscape

BrowserMatch^Mozillanetscape

BrowserMatchMSIE!netscape

Page 1301: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

BrowserMatch

User-AgentBrowserMatchregex[!]env-variable[=value]

[[!]env-variable[=value]]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_setenvif

BrowserMatchSetEnvIf User-Agent

BrowserMatchNoCaseRobotis_a_robot

SetEnvIfNoCaseUser-AgentRobotis_a_robot

BrowserMatch^Mozillaformsjpeg=yes

browser=netscape

BrowserMatch"^Mozilla/[2-3]"tablesagifframes

javascript

BrowserMatchMSIE!javascript

Page 1302: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

BrowserMatchNoCase

User-AgentBrowserMatchNoCaseregex[!]env-variable[=value]

[[!]env-variable[=value]]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_setenvif

BrowserMatchNoCaseBrowserMatch

BrowserMatchNoCasemacplatform=macintosh

BrowserMatchNoCasewinplatform=windows

BrowserMatchBrowserMatchNoCaseSetEnvIf

SetEnvIfNoCase

BrowserMatchNoCaseRobotis_a_robot

SetEnvIfNoCaseUser-AgentRobotis_a_robot

Page 1303: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SetEnvIf

SetEnvIfattributeregex[!]env-variable[=value]

[[!]env-variable[=value]]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_setenvif

SetEnvIf attribute

1. HTTP( RFC2616) Host,User-Agent,Referer,Accept-Language

2.

Remote_Host()

Remote_AddrIP

Server_AddrIP(2.0.43)

Request_Method(GET,POST)

Request_Protocol("HTTP/0.9","HTTP/1.0","HTTP/1.1")

Request_URIHTTP(URL)

3. SetEnvIf SetEnvIf[NoCase]""()attribute

regexPerlregexattribute

1. varname

2. !varname

3. varname=value

Page 1304: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

varname"1" varname() varnamevalue2.0.51Apache value$1..$9regex

SetEnvIfRequest_URI"\.gif$"object_is_image=gif

SetEnvIfRequest_URI"\.jpg$"object_is_image=jpg

SetEnvIfRequest_URI"\.xbm$"object_is_image=xbm

:

SetEnvIfRefererwww\.mydomain\.com

intra_site_referral

:

SetEnvIfobject_is_imagexbmXBIT_PROCESSING=1

:

SetEnvIf^TS*^[a-z].*HAVE_TS

object_is_image() intra_site_referral(Refererwww.mydomain.com)

HAVE_TS("TS"[a-z])

Apache

Page 1305: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

SetEnvIfNoCase

SetEnvIfNoCaseattributeregex[!]env-

variable[=value][[!]env-variable[=value]]...

serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_setenvif

SetEnvIfNoCaseSetEnvIf

SetEnvIfNoCaseHostApache\.Orgsite=apache

site" apache"(" Host:"" Apache.Org"" apache.org")

Page 1306: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006129|

Page 1307: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_so

DSO(E)so_modulemod_so.cWindows()

ApacheDSO

Unix( .so)Windows .so.dll

Apache1.3Apache2.0

Page 1308: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Windows

Apache1.3.15Windowsmod_foo.so

ApacheAPIUnixWindowsUnixWindows

UnixWindowsApacheUnix ConfigureApacheCore(symbols) os\win32\modules.c

(DLL) LoadModuleDLLApache

DLL(modulerecord)DLL()AP_MODULE_DECLARE_DATA(Apache)(modulerecord)

modulefoo_module;

moduleAP_MODULE_DECLARE_DATAfoo_module;

WindowsUnix .DEF

DLLlibhttpd.dlllibhttpd.libApache"modules".dsp.dsp

DLL modules LoadModule

Page 1309: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LoadFile

LoadFilefilename[filename]...

serverconfig(E)mod_so

FilenameServerRoot

LoadFilelibexec/libxmlparse.so

Page 1310: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

LoadModule

LoadModulemodulefilename

serverconfig(E)mod_so

filenamemodule modulemodule (ModuleIdentifier)

LoadModulestatus_modulemodules/mod_status.so

ServerRoot

Page 1311: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1312: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_speling

URL(E)speling_modulemod_speling.c

Requeststodocumentssometimescannotbeservedbythecoreapacheserverbecausetherequestwasmisspelledormiscapitalized.Thismoduleaddressesthisproblembytryingtofindamatchingdocument,evenafterallothermodulesgaveup.Itdoesitsworkbycomparingeachdocumentnameintherequesteddirectoryagainsttherequesteddocumentnamewithoutregardtocase,andallowinguptoonemisspelling(characterinsertion/omission/transpositionorwrongcharacter).Alistisbuiltwithalldocumentnameswhichwerematchedusingthisstrategy.

If,afterscanningthedirectory,

nomatchingdocumentwasfound,Apachewillproceedasusualandreturna"documentnotfound"error.onlyonedocumentisfoundthat"almost"matchestherequest,thenitisreturnedintheformofaredirectionresponse.morethanonedocumentwithaclosematchwasfound,thenthelistofthematchesisreturnedtotheclient,andtheclientcanselectthecorrectcandidate.

Page 1313: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CheckSpelling

EnablesthespellingmoduleCheckSpellingon|off

CheckSpellingOff

serverconfig,virtualhost,directory,.htaccessOptions(E)mod_spelingCheckSpellingwasavailableasaseparatelyavailablemoduleforApache1.1,butwaslimitedtomiscapitalizations.AsofApache1.3,itispartoftheApachedistribution.PriortoApache1.3.2,theCheckSpellingdirectivewasonlyavailableinthe"server"and"virtualhost"contexts.

Thisdirectiveenablesordisablesthespellingmodule.Whenenabled,keepinmindthat

thedirectoryscanwhichisnecessaryforthespellingcorrectionwillhaveanimpactontheserver'sperformancewhenmanyspellingcorrectionshavetobeperformedatthesametime.thedocumenttreesshouldnotcontainsensitivefileswhichcouldbematchedinadvertentlybyaspelling"correction".themoduleisunabletocorrectmisspelledusernames(asinhttp://my.host/~apahce/),justfilenamesordirectorynames.spellingcorrectionsapplystrictlytoexistingfiles,soarequestforthe<Location/status>maygetincorrectlytreatedasthenegotiatedfile"/stats.html".

mod_spelingshouldnotbeenabledinDAVenableddirectories,becauseitwilltryto"spellfix"newlycreatedresourcenamesagainstexistingfilenames,e.g.,whentryingtouploadanewdocumentdoc43.htmlitmightredirecttoanexistingdocumentdoc34.html,

Page 1314: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

whichisnotwhatwasintended.

Page 1315: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1316: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_ssl

(SSL)(TLS)(E)ssl_modulemod_ssl.c

ThismoduleprovidesSSLv2/v3andTLSv1supportfortheApacheHTTPServer.ItwascontributedbyRalfS.Engeschallbasedonhismod_sslprojectandoriginallyderivedfromworkbyBenLaurie.

ThismodulereliesonOpenSSLtoprovidethecryptographyengine.

Furtherdetails,discussion,andexamplesareprovidedintheSSLdocumentation.

Page 1317: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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 trueifcipherisanexport

cipherSSL_CIPHER_USEKEYSIZE number Numberofcipherbits

(actuallyused)SSL_CIPHER_ALGKEYSIZE number Numberofcipherbits

(possible)SSL_COMPRESS_METHOD string SSLcompressionmethod

negotiatedSSL_VERSION_INTERFACE string Themod_sslprogram

versionSSL_VERSION_LIBRARY string TheOpenSSLprogram

versionSSL_CLIENT_M_VERSION string Theversionoftheclient

certificateSSL_CLIENT_M_SERIAL string Theserialoftheclient

certificate

Page 1318: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSL_CLIENT_S_DN string SubjectDNinclient'scertificate

SSL_CLIENT_S_DN_x509 string Componentofclient'sSubjectDN

SSL_CLIENT_I_DN string IssuerDNofclient'scertificate

SSL_CLIENT_I_DN_x509 string Componentofclient'sIssuerDN

SSL_CLIENT_V_START string Validityofclient'scertificate(starttime)

SSL_CLIENT_V_END string Validityofclient'scertificate(endtime)

SSL_CLIENT_V_REMAIN string Numberofdaysuntilclient'scertificateexpires

SSL_CLIENT_A_SIG string Algorithmusedforthesignatureofclient'scertificate

SSL_CLIENT_A_KEY string Algorithmusedforthepublickeyofclient'scertificate

SSL_CLIENT_CERT string PEM-encodedclientcertificate

SSL_CLIENT_CERT_CHAIN_n string PEM-encodedcertificatesinclientcertificatechain

SSL_CLIENT_VERIFY string NONE,SUCCESS,GENEROUSFAILED:reason

SSL_SERVER_M_VERSION string Theversionoftheservercertificate

SSL_SERVER_M_SERIAL string Theserialoftheservercertificate

SSL_SERVER_S_DN string SubjectDNinserver's

Page 1319: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

certificateSSL_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

x509specifiesacomponentofanX.509DN;oneofC,ST,L,O,OU,CN,T,I,G,S,D,UID,Email.InApache2.1andlater,x509mayalsoincludeanumeric_nsuffix.IftheDNinquestioncontainsmultipleattributesofthesamename,thissuffixisusedasanindextoselectaparticularattribute.Forexample,wheretheservercertificatesubjectDNincludedtwoOUfields,SSL_SERVER_S_DN_OU_0SSL_SERVER_S_DN_OU_1couldbeusedtoreferenceeach.

SSL_CLIENT_V_REMAINisonlyavailableinversion2.1andlater.

Page 1320: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CustomLogFormats

Whenmod_sslisbuiltintoApacheoratleastloaded(underDSOsituation)additionalfunctionsexistfortheCustomLogFormatofmod_log_config.Firstthereisanadditional"%{varname}x"eXtensionformatfunctionwhichcanbeusedtoexpandanyvariablesprovidedbyanymodule,especiallythoseprovidedbymod_sslwhichcanyoufindintheabovetable.

Forbackwardcompatibilitythereisadditionallyaspecial"%{name}c"cryptographyformatfunctionprovided.InformationaboutthisfunctionisprovidedintheCompatibilitychapter.

CustomLoglogs/ssl_request_log\"%t%h%

{SSL_PROTOCOL}x%{SSL_CIPHER}x\"%r\"%b"

Page 1321: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCACertificateFile

FileofconcatenatedPEM-encodedCACertificatesforClientAuthSSLCACertificateFilefile-path

serverconfig,virtualhost(E)mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoucanassembletheCertificatesofCertificationAuthorities(CA)whoseclientsyoudealwith.TheseareusedforClientAuthentication.SuchafileissimplytheconcatenationofthevariousPEM-encodedCertificatefiles,inorderofpreference.Thiscanbeusedalternativelyand/oradditionallytoSSLCACertificatePath.

SSLCACertificateFile

/usr/local/apache2/conf/ssl.crt/ca-bundle-

client.crt

Page 1322: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCACertificatePath

DirectoryofPEM-encodedCACertificatesforClientAuthSSLCACertificatePathdirectory-path

serverconfig,virtualhost(E)mod_ssl

ThisdirectivesetsthedirectorywhereyoukeeptheCertificatesofCertificationAuthorities(CAs)whoseclientsyoudealwith.TheseareusedtoverifytheclientcertificateonClientAuthentication.

ThefilesinthisdirectoryhavetobePEM-encodedandareaccessedthroughhashfilenames.Sousuallyyoucan'tjustplacetheCertificatefilesthere:youalsohavetocreatesymboliclinksnamedhash-value.N.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.UsetheMakefilewhichcomeswithmod_ssltoaccomplishthistask.

SSLCACertificatePath

/usr/local/apache2/conf/ssl.crt/

Page 1323: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCADNRequestFile

FileofconcatenatedPEM-encodedCACertificatesfordefiningacceptableCAnamesSSLCADNRequestFilefile-path

serverconfig,virtualhost(E)mod_ssl

Whenaclientcertificateisrequestedbymod_ssl,alistofacceptableCertificateAuthoritynamesissenttotheclientintheSSLhandshake.TheseCAnamescanbeusedbytheclienttoselectanappropriateclientcertificateoutofthoseithasavailable.

IfneitherofthedirectivesSSLCADNRequestPathSSLCADNRequestFilearegiven,thenthesetofacceptableCAnamessenttotheclientisthenamesofalltheCAcertificatesgivenbytheSSLCACertificateFileSSLCACertificatePathdirectives;inotherwords,thenamesoftheCAswhichwillactuallybeusedtoverifytheclientcertificate.

Insomecircumstances,itisusefultobeabletosendasetofacceptableCAnameswhichdiffersfromtheactualCAsusedtoverifytheclientcertificate-forexample,iftheclientcertificatesaresignedbyintermediateCAs.Insuchcases,SSLCADNRequestPathand/orSSLCADNRequestFilecanbeused;theacceptableCAnamesarethentakenfromthecompletesetofcertificatesinthedirectoryand/orfilespecifiedbythispairofdirectives.

SSLCADNRequestFilemustspecifyanall-in-onefilecontainingaconcatenationofPEM-encodedCAcertificates.

SSLCADNRequestFile/usr/local/apache2/conf/ca-

names.crt

Page 1324: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 1325: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCADNRequestPath

DirectoryofPEM-encodedCACertificatesfordefiningacceptableCAnamesSSLCADNRequestPathdirectory-path

serverconfig,virtualhost(E)mod_ssl

ThisoptionaldirectivecanbeusedtospecifythesetofacceptableCAnameswhichwillbesenttotheclientwhenaclientcertificateisrequested.SeetheSSLCADNRequestFiledirectiveformoredetails.

ThefilesinthisdirectoryhavetobePEM-encodedandareaccessedthroughhashfilenames.Sousuallyyoucan'tjustplacetheCertificatefilesthere:youalsohavetocreatesymboliclinksnamedhash-value.N.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.UsetheMakefilewhichcomeswithmod_ssltoaccomplishthistask.

SSLCADNRequestPath/usr/local/apache2/conf/ca-

names.crt/

Page 1326: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCARevocationFile

FileofconcatenatedPEM-encodedCACRLsforClientAuthSSLCARevocationFilefile-path

serverconfig,virtualhost(E)mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoucanassembletheCertificateRevocationLists(CRL)ofCertificationAuthorities(CA)whoseclientsyoudealwith.TheseareusedforClientAuthentication.SuchafileissimplytheconcatenationofthevariousPEM-encodedCRLfiles,inorderofpreference.Thiscanbeusedalternativelyand/oradditionallytoSSLCARevocationPath.

SSLCARevocationFile

/usr/local/apache2/conf/ssl.crl/ca-bundle-

client.crl

Page 1327: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCARevocationPath

DirectoryofPEM-encodedCACRLsforClientAuthSSLCARevocationPathdirectory-path

serverconfig,virtualhost(E)mod_ssl

ThisdirectivesetsthedirectorywhereyoukeeptheCertificateRevocationLists(CRL)ofCertificationAuthorities(CAs)whoseclientsyoudealwith.TheseareusedtorevoketheclientcertificateonClientAuthentication.

ThefilesinthisdirectoryhavetobePEM-encodedandareaccessedthroughhashfilenames.SousuallyyouhavenotonlytoplacetheCRLfilesthere.Additionallyyouhavetocreatesymboliclinksnamedhash-value.rN.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.UsetheMakefilewhichcomeswithmod_ssltoaccomplishthistask.

SSLCARevocationPath

/usr/local/apache2/conf/ssl.crl/

Page 1328: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCertificateChainFile

FileofPEM-encodedServerCACertificatesSSLCertificateChainFilefile-path

serverconfig,virtualhost(E)mod_ssl

Thisdirectivesetstheoptionalall-in-onefilewhereyoucanassemblethecertificatesofCertificationAuthorities(CA)whichformthecertificatechainoftheservercertificate.ThisstartswiththeissuingCAcertificateofoftheservercertificateandcanrangeuptotherootCAcertificate.SuchafileissimplytheconcatenationofthevariousPEM-encodedCACertificatefiles,usuallyincertificatechainorder.

Thisshouldbeusedalternativelyand/oradditionallytoSSLCACertificatePathforexplicitlyconstructingtheservercertificatechainwhichissenttothebrowserinadditiontotheservercertificate.ItisespeciallyusefultoavoidconflictswithCAcertificateswhenusingclientauthentication.BecausealthoughplacingaCAcertificateoftheservercertificatechainintoSSLCACertificatePathhasthesameeffectforthecertificatechainconstruction,ithastheside-effectthatclientcertificatesissuedbythissameCAcertificatearealsoacceptedonclientauthentication.That'susuallynotoneexpect.

Butbecareful:Providingthecertificatechainworksonlyifyouareusingasingle(eitherRSADSA)basedservercertificate.IfyouareusingacoupledRSA+DSAcertificatepair,thiswillworkonlyifactuallybothcertificatesusethesamecertificatechain.Elsethebrowserswillbeconfusedinthissituation.

SSLCertificateChainFile

/usr/local/apache2/conf/ssl.crt/ca.crt

Page 1329: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 1330: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCertificateFile

ServerPEM-encodedX.509CertificatefileSSLCertificateFilefile-path

serverconfig,virtualhost(E)mod_ssl

ThisdirectivepointstothePEM-encodedCertificatefilefortheserverandoptionallyalsotothecorrespondingRSAorDSAPrivateKeyfileforit(containedinthesamefile).IfthecontainedPrivateKeyisencryptedthePassPhrasedialogisforcedatstartuptime.Thisdirectivecanbeuseduptotwotimes(referencingdifferentfilenames)whenbothaRSAandaDSAbasedservercertificateisusedinparallel.

SSLCertificateFile

/usr/local/apache2/conf/ssl.crt/server.crt

Page 1331: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCertificateKeyFile

ServerPEM-encodedPrivateKeyfileSSLCertificateKeyFilefile-path

serverconfig,virtualhost(E)mod_ssl

ThisdirectivepointstothePEM-encodedPrivateKeyfilefortheserver.IfthePrivateKeyisnotcombinedwiththeCertificateintheSSLCertificateFile,usethisadditionaldirectivetopointtothefilewiththestand-alonePrivateKey.WhenSSLCertificateFileisusedandthefilecontainsboththeCertificateandthePrivateKeythisdirectiveneednotbeused.Butwestronglydiscouragethispractice.InsteadwerecommendyoutoseparatetheCertificateandthePrivateKey.IfthecontainedPrivateKeyisencrypted,thePassPhrasedialogisforcedatstartuptime.Thisdirectivecanbeuseduptotwotimes(referencingdifferentfilenames)whenbothaRSAandaDSAbasedprivatekeyisusedinparallel.

SSLCertificateKeyFile

/usr/local/apache2/conf/ssl.key/server.key

Page 1332: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCipherSuite

CipherSuiteavailablefornegotiationinSSLhandshakeSSLCipherSuitecipher-spec

SSLCipherSuite

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

serverconfig,virtualhost,directory,.htaccessAuthConfig(E)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).Tospecifywhichcipherstouse,onecaneitherspecifyalltheCiphers,oneata

Page 1333: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

time,orusealiasestospecifythepreferenceandorderfortheciphers(seeTable1).

Tag DescriptionKeyExchangeAlgorithm:kRSA RSAkeyexchangekDHr Diffie-HellmankeyexchangewithRSAkeykDHd Diffie-HellmankeyexchangewithDSAkeykEDH Ephemeral(temp.key)Diffie-Hellmankeyexchange(no

cert)AuthenticationAlgorithm:aNULL NoauthenticationaRSA RSAauthenticationaDSS DSSauthenticationaDH Diffie-HellmanauthenticationCipherEncodingAlgorithm:eNULL NoencodingDES DESencoding3DES Triple-DESencodingRC4 RC4encodingRC2 RC2encodingIDEA IDEAencodingMACDigestAlgorithm:MD5 MD5hashfunctionSHA1 SHA1hashfunctionSHA SHAhashfunctionAliases:SSLv2 allSSLversion2.0ciphersSSLv3 allSSLversion3.0ciphersTLSv1

Page 1334: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

allTLSversion1.0ciphersEXP allexportciphersEXPORT40 all40-bitexportciphersonlyEXPORT56 all56-bitexportciphersonlyLOW alllowstrengthciphers(noexport,singleDES)MEDIUM allcipherswith128bitencryptionHIGH allciphersusingTriple-DESRSA allciphersusingRSAkeyexchangeDH allciphersusingDiffie-HellmankeyexchangeEDH allciphersusingEphemeralDiffie-HellmankeyexchangeADH allciphersusingAnonymousDiffie-Hellmankey

exchangeDSS allciphersusingDSSauthenticationNULL allciphersusingnoencryption

Nowwherethisbecomesinterestingisthatthesecanbeputtogethertospecifytheorderandciphersyouwishtouse.Tospeedthisuptherearealsoaliases(SSLv2,SSLv3,TLSv1,EXP,LOW,MEDIUM,HIGH)forcertaingroupsofciphers.Thesetagscanbejoinedtogetherwithprefixestoformthecipher-spec.Availableprefixesare:

none:addciphertolist+:addcipherstolistandpullthemtocurrentlocationinlist-:removecipherfromlist(canbeaddedlateragain)!:killcipherfromlistcompletely(cannotbeaddedlateragain)

Asimplerwaytolookatallofthisistousethe"opensslciphers-v"commandwhichprovidesanicewaytosuccessivelycreatethecorrectcipher-specstring.Thedefaultcipher-specstringis"ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP"whichmeansthefollowing:first,removefromconsiderationany

Page 1335: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ciphersthatdonotauthenticate,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.

SSLCipherSuiteRSA:!EXP:!NULL:+HIGH:+MEDIUM:-LOW

Cipher-Tag Protocol KeyEx. Auth. Enc. MAC TypeRSACiphers: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) SHA1RC4-MD5 SSLv3 RSA RSA RC4(128) MD5IDEA-CBC-

MD5

SSLv2 RSA RSA IDEA(128) MD5

RC2-CBC- SSLv2 RSA RSA RC2(128) MD5

Page 1336: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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) MD5DES-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- SSLv3 DH RSA DES(56) SHA1

Page 1337: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DES-CBC-

SHA

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

Page 1338: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLCryptoDevice

EnableuseofacryptographichardwareacceleratorSSLCryptoDeviceengine

SSLCryptoDevicebuiltin

serverconfig(E)mod_sslAvailableifmod_sslisbuiltusing-DSSL_ENGINE_EXPERIMENTAL

ThisdirectiveenablesuseofacryptographichardwareacceleratorboardtooffloadsomeoftheSSLprocessingoverhead.ThisdirectivecanonlybeusediftheSSLtoolkitisbuiltwith"engine"support;OpenSSL0.9.7andlaterreleaseshave"engine"supportbydefault,theseparate"-engine"releasesofOpenSSL0.9.6mustbeused.

Todiscoverwhichenginenamesaresupported,runthecommand"opensslengine".

#ForaBroadcomaccelerator:

SSLCryptoDeviceubsec

Page 1339: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLEngine

SSLEngineOperationSwitchSSLEngineon|off|optional

SSLEngineoff

serverconfig,virtualhost(E)mod_ssl

ThisdirectivetogglestheusageoftheSSL/TLSProtocolEngine.Thisisusuallyusedinsidea<VirtualHost>sectiontoenableSSL/TLSforaparticularvirtualhost.BydefaulttheSSL/TLSProtocolEngineisdisabledforboththemainserverandallconfiguredvirtualhosts.

<VirtualHost_default_:443>

SSLEngineon

...

</VirtualHost>

InApache2.1andlater,SSLEnginecanbesettooptional.ThisenablessupportforRFC2817,UpgradingtoTLSWithinHTTP/1.1.AtthistimenowebbrowserssupportRFC2817.

Page 1340: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLHonorCipherOrder

Optiontoprefertheserver'scipherpreferenceorderSSLHonorCiperOrderflag

serverconfig,virtualhost(E)mod_sslApache2.1andlater,ifusingOpenSSL0.9.7orlater

WhenchoosingacipherduringanSSLv3orTLSv1handshake,normallytheclient'spreferenceisused.Ifthisdirectiveisenabled,theserver'spreferencewillbeusedinstead.

SSLHonorCipherOrderon

Page 1341: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLMutex

SemaphoreforinternalmutualexclusionofoperationsSSLMutextype

SSLMutexnone

serverconfig(E)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"SysVsemaphoresifprocessescrashbeforethesemaphoreis

Page 1342: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

removed.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,choosingbetweenfcntlflock,inthatorder.Itisonlyavailablewhentheunderlyingplatformand

Page 1343: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

APRsupportsatleastoneofthe2.

default|yes

ThisdirectivetellstheSSLModuletopickthedefaultlockingimplementationasdeterminedbytheplatformandAPR.

SSLMutexfile:/usr/local/apache/logs/ssl_mutex

Page 1344: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLOptions

ConfigurevariousSSLenginerun-timeoptionsSSLOptions[+|-]option...

serverconfig,virtualhost,directory,.htaccessOptions(E)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

Page 1345: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

variablesarecreated:SSL_SERVER_CERT,SSL_CLIENT_CERTSSL_CLIENT_CERT_CHAIN_n(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

ThisforcesforbiddenaccesswhenSSLRequireSSLSSLRequiresuccessfullydecidedthataccessshouldbeforbidden.Usuallythedefaultisthatinthecasewherea"Satisfyany"directiveisused,andotheraccessrestrictionsarepassed,denialofaccessduetoSSLRequireSSLSSLRequireisoverridden(becausethat'showtheApacheSatisfymechanismshouldwork.)ButforstrictaccessrestrictionyoucanuseSSLRequireSSLand/orSSLRequirein

Page 1346: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

combinationwithan"SSLOptions+StrictRequire".Thenanadditional"SatisfyAny"hasnochanceoncemod_sslhasdecidedtodenyaccess.

OptRenegotiate

ThisenablesoptimizedSSLconnectionrenegotiationhandlingwhenSSLdirectivesareusedinper-directorycontext.Bydefaultastrictschemeisenabledwhereeveryper-directoryreconfigurationofSSLparameterscausesafullSSLrenegotiationhandshake.Whenthisoptionisusedmod_ssltriestoavoidunnecessaryhandshakesbydoingmoregranular(butstillsafe)parameterchecks.Neverthelessthesegranularcheckssometimesmaybenotwhattheuserexpects,soenablethisonaper-directorybasisonly,please.

SSLOptions+FakeBasicAuth-StrictRequire

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

SSLOptions+StdEnvVars+CompatEnvVars-

ExportCertData

<Files>

Page 1347: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLPassPhraseDialog

TypeofpassphrasedialogforencryptedprivatekeysSSLPassPhraseDialogtype

SSLPassPhraseDialogbuiltin

serverconfig(E)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-butthenyouhavetoenterallofthem,ofcourse)whileminimizingtheterminaldialog(i.e.whenyouuseasinglePassPhraseforallNPrivateKeyfilesthisPassPhraseisqueriedonly

Page 1348: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

once).

|/path/to/program[args...]

Thismodeallowsanexternalprogramtobeusedwhichactsasapipetoaparticularinputdevice;theprogramissentthestandardprompttextusedforthebuiltinmodeonstdin,andisexpectedtowritepasswordstringsonstdout.Ifseveralpasswordsareneeded(oranincorrectpasswordisentered),additionalprompttextwillbewrittensubsequenttothefirstpasswordbeingreturned,andmorepasswordsmustthenbewrittenback.

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.

Page 1349: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLPassPhraseDialog

exec:/usr/local/apache/sbin/pp-filter

Page 1350: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProtocol

ConfigureusableSSLprotocolflavorsSSLProtocol[+|-]protocol...

SSLProtocolall

serverconfig,virtualhostOptions(E)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"andaconvinientwayforenablingallprotocolsexceptonewhenusedin

Page 1351: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

combinationwiththeminussignonaprotocolastheexampleaboveshows.

#enableSSLv3andTLSv1,butnotSSLv2

SSLProtocolall-SSLv2

Page 1352: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyCACertificateFile

FileofconcatenatedPEM-encodedCACertificatesforRemoteServerAuthSSLProxyCACertificateFilefile-path

serverconfig,virtualhost(E)mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoucanassembletheCertificatesofCertificationAuthorities(CA)whoseremoteserversyoudealwith.TheseareusedforRemoteServerAuthentication.SuchafileissimplytheconcatenationofthevariousPEM-encodedCertificatefiles,inorderofpreference.Thiscanbeusedalternativelyand/oradditionallytoSSLProxyCACertificatePath.

SSLProxyCACertificateFile

/usr/local/apache2/conf/ssl.crt/ca-bundle-remote-

server.crt

Page 1353: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyCACertificatePath

DirectoryofPEM-encodedCACertificatesforRemoteServerAuthSSLProxyCACertificatePathdirectory-path

serverconfig,virtualhost(E)mod_ssl

ThisdirectivesetsthedirectorywhereyoukeeptheCertificatesofCertificationAuthorities(CAs)whoseremoteserversyoudealwith.TheseareusedtoverifytheremoteservercertificateonRemoteServerAuthentication.

ThefilesinthisdirectoryhavetobePEM-encodedandareaccessedthroughhashfilenames.Sousuallyyoucan'tjustplacetheCertificatefilesthere:youalsohavetocreatesymboliclinksnamedhash-value.N.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.UsetheMakefilewhichcomeswithmod_ssltoaccomplishthistask.

SSLProxyCACertificatePath

/usr/local/apache2/conf/ssl.crt/

Page 1354: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyCARevocationFile

FileofconcatenatedPEM-encodedCACRLsforRemoteServerAuthSSLProxyCARevocationFilefile-path

serverconfig,virtualhost(E)mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoucanassembletheCertificateRevocationLists(CRL)ofCertificationAuthorities(CA)whoseremoteserversyoudealwith.TheseareusedforRemoteServerAuthentication.SuchafileissimplytheconcatenationofthevariousPEM-encodedCRLfiles,inorderofpreference.Thiscanbeusedalternativelyand/oradditionallytoSSLProxyCARevocationPath.

SSLProxyCARevocationFile

/usr/local/apache2/conf/ssl.crl/ca-bundle-remote-

server.crl

Page 1355: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyCARevocationPath

DirectoryofPEM-encodedCACRLsforRemoteServerAuthSSLProxyCARevocationPathdirectory-path

serverconfig,virtualhost(E)mod_ssl

ThisdirectivesetsthedirectorywhereyoukeeptheCertificateRevocationLists(CRL)ofCertificationAuthorities(CAs)whoseremoteserversyoudealwith.TheseareusedtorevoketheremoteservercertificateonRemoteServerAuthentication.

ThefilesinthisdirectoryhavetobePEM-encodedandareaccessedthroughhashfilenames.SousuallyyouhavenotonlytoplacetheCRLfilesthere.Additionallyyouhavetocreatesymboliclinksnamedhash-value.rN.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.UsetheMakefilewhichcomeswithmod_ssltoaccomplishthistask.

SSLProxyCARevocationPath

/usr/local/apache2/conf/ssl.crl/

Page 1356: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyCipherSuite

CipherSuiteavailablefornegotiationinSSLproxyhandshakeSSLProxyCipherSuitecipher-spec

SSLProxyCipherSuite

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

serverconfig,virtualhost,directory,.htaccessAuthConfig(E)mod_ssl

EquivalenttoSSLCipherSuite,butfortheproxyconnection.PleaserefertoSSLCipherSuiteforadditionalinformation.

Page 1357: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyEngine

SSLProxyEngineOperationSwitchSSLProxyEngineon|off

SSLProxyEngineoff

serverconfig,virtualhost(E)mod_ssl

ThisdirectivetogglestheusageoftheSSL/TLSProtocolEngineforproxy.Thisisusuallyusedinsidea<VirtualHost>sectiontoenableSSL/TLSforproxyusageinaparticularvirtualhost.BydefaulttheSSL/TLSProtocolEngineisdisabledforproxyimagebothforthemainserverandallconfiguredvirtualhosts.

<VirtualHost_default_:443>

SSLProxyEngineon

...

</VirtualHost>

Page 1358: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyMachineCertificateFile

FileofconcatenatedPEM-encodedclientcertificatesandkeystobeusedbytheproxySSLProxyMachineCertificateFilefilename

serverconfigNotapplicable(E)mod_ssl

Thisdirectivesetstheall-in-onefilewhereyoukeepthecertificatesandkeysusedforauthenticationoftheproxyservertoremoteservers.

ThisreferencedfileissimplytheconcatenationofthevariousPEM-encodedcertificatefiles,inorderofpreference.UsethisdirectivealternativelyoradditionallytoSSLProxyMachineCertificatePath.

Currentlythereisnosupportforencryptedprivatekeys

SSLProxyMachineCertificateFile

/usr/local/apache2/conf/ssl.crt/proxy.pem

Page 1359: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyMachineCertificatePath

DirectoryofPEM-encodedclientcertificatesandkeystobeusedbytheproxySSLProxyMachineCertificatePathdirectory

serverconfigNotapplicable(E)mod_ssl

Thisdirectivesetsthedirectorywhereyoukeepthecertificatesandkeysusedforauthenticationoftheproxyservertoremoteservers.

ThefilesinthisdirectorymustbePEM-encodedandareaccessedthroughhashfilenames.Additionally,youmustcreatesymboliclinksnamedhash-value.N.Andyoushouldalwaysmakesurethisdirectorycontainstheappropriatesymboliclinks.UsetheMakefilewhichcomeswithmod_ssltoaccomplishthistask.

Currentlythereisnosupportforencryptedprivatekeys

SSLProxyMachineCertificatePath

/usr/local/apache2/conf/proxy.crt/

Page 1360: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyProtocol

ConfigureusableSSLprotocolflavorsforproxyusageSSLProxyProtocol[+|-]protocol...

SSLProxyProtocolall

serverconfig,virtualhostOptions(E)mod_ssl

ThisdirectivecanbeusedtocontroltheSSLprotocolflavorsmod_sslshouldusewhenestablishingitsserverenvironmentforproxy.Itwillonlyconnecttoserversusingoneoftheprovidedprotocols.

PleaserefertoSSLProtocolforadditionalinformation.

Page 1361: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyVerify

TypeofremoteserverCertificateverificationSSLProxyVerifylevel

SSLProxyVerifynone

serverconfig,virtualhost,directory,.htaccessAuthConfig(E)mod_ssl

WhenaproxyisconfiguredtoforwardrequeststoaremoteSSLserver,thisdirectivecanbeusedtoconfigurecertificateverificationoftheremoteserver.Noticethatthisdirectivecanbeusedbothinper-serverandper-directorycontext.Inper-servercontextitappliestotheremoteserverauthenticationprocessusedinthestandardSSLhandshakewhenaconnectionisestablishedbytheproxy.Inper-directorycontextitforcesaSSLrenegotationwiththereconfiguredremoteserververificationlevelaftertheHTTPrequestwasreadbutbeforetheHTTPresponseissent.

Notethatevenwhencertificateverificationisenabled,mod_ssldoesnotcheckwhetherthecommonName(hostname)attributeoftheservercertificatematchesthehostnameusedtoconnecttotheserver.Inotherwords,theproxydoesnotguaranteethattheSSLconnectiontothebackendserveris"secure"beyondthefactthatthecertificateissignedbyoneoftheCAsconfiguredusingtheSSLProxyCACertificatePathand/orSSLProxyCACertificateFiledirectives.

Thefollowinglevelsareavailableforlevel:

none:noremoteserverCertificateisrequiredatalloptional:theremoteservermaypresentavalidCertificate

Page 1362: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

require:theremoteserverhastopresentavalidCertificateoptional_no_ca:theremoteservermaypresentavalidCertificatebutitneednottobe(successfully)verifiable.

Inpracticeonlylevelsnonerequirearereallyinteresting,becauseleveloptionaldoesn'tworkwithallserversandleveloptional_no_caisactuallyagainsttheideaofauthentication(butcanbeusedtoestablishSSLtestpages,etc.)

SSLProxyVerifyrequire

Page 1363: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLProxyVerifyDepth

MaximumdepthofCACertificatesinRemoteServerCertificateverificationSSLProxyVerifyDepthnumber

SSLProxyVerifyDepth1

serverconfig,virtualhost,directory,.htaccessAuthConfig(E)mod_ssl

Thisdirectivesetshowdeeplymod_sslshouldverifybeforedecidingthattheremoteserverdoesnothaveavalidcertificate.Noticethatthisdirectivecanbeusedbothinper-serverandper-directorycontext.Inper-servercontextitappliestotheclientauthenticationprocessusedinthestandardSSLhandshakewhenaconnectionisestablished.Inper-directorycontextitforcesaSSLrenegotationwiththereconfiguredremoteserververificationdepthaftertheHTTPrequestwasreadbutbeforetheHTTPresponseissent.

Thedepthactuallyisthemaximumnumberofintermediatecertificateissuers,i.e.thenumberofCAcertificateswhicharemaxallowedtobefollowedwhileverifyingtheremoteservercertificate.Adepthof0meansthatself-signedremoteservercertificatesareacceptedonly,thedefaultdepthof1meanstheremoteservercertificatecanbeself-signedorhastobesignedbyaCAwhichisdirectlyknowntotheserver(i.e.theCA'scertificateisunderSSLProxyCACertificatePath),etc.

SSLProxyVerifyDepth10

Page 1364: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLRandomSeed

PseudoRandomNumberGenerator(PRNG)seedingsourceSSLRandomSeedcontextsource[bytes]

serverconfig(E)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/sourceasthefirstargument).Whenbytesisnotspecifiedthewholefileformstheentropy(and0isgivento/path/to/sourceasthefirstargument).Usethis

Page 1365: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

especiallyatstartuptime,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.Usethisonlyatstartuptimewhenyouneedaverystrongseedingwiththehelpofanexternalprogram(forinstanceasintheexampleabovewiththetruerandutilityyoucanfindinthemod_ssldistributionwhichisbasedontheAT&Ttruerandlibrary).Usingthisintheconnectioncontextslowsdowntheservertoodramatically,ofcourse.Sousuallyyoushouldavoidusingexternalprogramsinthatcontext.

Page 1366: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

egd:/path/to/egd-socket(Unixonly)ThisvariantusestheUnixdomainsocketoftheexternalEntropyGatheringDaemon(EGD)(seehttp://www.lothar.com/tech/crypto/)toseedthePRNG.Usethisifnorandomdeviceexistsonyourplatform.

SSLRandomSeedstartupbuiltin

SSLRandomSeedstartupfile:/dev/random

SSLRandomSeedstartupfile:/dev/urandom1024

SSLRandomSeedstartupexec:/usr/local/bin/truerand

16

SSLRandomSeedconnectbuiltin

SSLRandomSeedconnectfile:/dev/random

SSLRandomSeedconnectfile:/dev/urandom1024

Page 1367: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLRequire

AllowaccessonlywhenanarbitrarilycomplexbooleanexpressionistrueSSLRequireexpression

directory,.htaccessAuthConfig(E)mod_ssl

Thisdirectivespecifiesageneralaccessrequirementwhichhastobefulfilledinordertoallowaccess.Itisaverypowerfuldirectivebecausetherequirementspecificationisanarbitrarilycomplexbooleanexpressioncontaininganynumberofaccesschecks.

TheimplementationofSSLRequireisnotthreadsafe.UsingSSLRequireinside.htaccessfilesonathreadedMPMmaycauserandomcrashes.

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

Page 1368: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

|word"in""{"wordlist"}"

|word"in""OID("word")"

|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.

SSLRequire(%{SSL_CIPHER}!~m/^(EXP|NULL)-/\

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

Page 1369: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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]+$/

OID()functionexpectstofindzeroormoreinstancesofthegivenOIDintheclientcertificate,andcomparestheleft-handsidestringagainstthevalueofmatchingOIDattributes.EverymatchingOIDischecked,untilamatchisfound.

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

Page 1370: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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_CHAIN_n

SSL_CLIENT_VERIFY

Page 1371: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLRequireSSL

DenyaccesswhenSSLisnotusedfortheHTTPrequestSSLRequireSSL

directory,.htaccessAuthConfig(E)mod_ssl

ThisdirectiveforbidsaccessunlessHTTPoverSSL(i.e.HTTPS)isenabledforthecurrentconnection.ThisisveryhandyinsidetheSSL-enabledvirtualhostordirectoriesfordefendingagainstconfigurationerrorsthatexposestuffthatshouldbeprotected.WhenthisdirectiveispresentallrequestsaredeniedwhicharenotusingSSL.

SSLRequireSSL

Page 1372: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLSessionCache

Typeoftheglobal/inter-processSSLSessionCacheSSLSessionCachetype

SSLSessionCachenone

serverconfig(E)mod_ssl

Thisconfiguresthestoragetypeoftheglobal/inter-processSSLSessionCache.Thiscacheisanoptionalfacilitywhichspeedsupparallelrequestprocessing.Forrequeststothesameserverprocess(viaHTTPkeep-alive),OpenSSLalreadycachestheSSLsessioninformationlocally.Butbecausemodernclientsrequestinlinedimagesandotherdataviaparallelrequests(usuallyuptofourparallelrequestsarecommon)thoserequestsareservedbydifferentpre-forkedserverprocesses.Hereaninter-processcachehelpstoavoidunneccessarysessionhandshakes.

Thefollowingfourstoragetypesarecurrentlysupported:

none

Thisdisablestheglobal/inter-processSessionCache.Thiswillincuranoticeablespeedpenaltyandmaycauseproblemsifusingcertainbrowsers,particularlyifclientcertificatesareenabled.Thissettingisnotrecommended.

nonenotnull

Thisdisablesanyglobal/inter-processSessionCache.HoweveritdoesforceOpenSSLtosendanon-nullsessionIDtoaccommodatebuggyclientsthatrequireone.

dbm:/path/to/datafile

ThismakesuseofaDBMhashfileonthelocaldisktosynchronizethelocalOpenSSLmemorycachesoftheserver

Page 1373: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

processes.Thissessioncachemaysufferreliabilityissuesunderhighload.

shm:/path/to/datafile[(size)]Thismakesuseofahigh-performancecyclicbuffer(approx.sizebytesinsize)insideasharedmemorysegmentinRAM(establishedvia/path/to/datafile)tosynchronizethelocalOpenSSLmemorycachesoftheserverprocesses.Thisistherecommendedsessioncache.

dc:UNIX:/path/to/socket

Thismakesuseofthedistcachedistributedsessioncachinglibraries.Theargumentshouldspecifythelocationoftheserverorproxytobeusedusingthedistcacheaddresssyntax;forexample,UNIX:/path/to/socketspecifiesaUNIXdomainsocket(typicallyalocaldc_clientproxy);IP:server.example.com:9001specifiesanIPaddress.

SSLSessionCache

dbm:/usr/local/apache/logs/ssl_gcache_data

SSLSessionCache

shm:/usr/local/apache/logs/ssl_gcache_data(512000)

Page 1374: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLSessionCacheTimeout

NumberofsecondsbeforeanSSLsessionexpiresintheSessionCacheSSLSessionCacheTimeoutseconds

SSLSessionCacheTimeout300

serverconfig,virtualhost(E)mod_ssl

Thisdirectivesetsthetimeoutinsecondsfortheinformationstoredintheglobal/inter-processSSLSessionCacheandtheOpenSSLinternalmemorycache.Itcanbesetaslowas15fortesting,butshouldbesettohighervalueslike300inreallife.

SSLSessionCacheTimeout600

Page 1375: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLUserName

VariablenametodetermineusernameSSLUserNamevarname

serverconfig,directory,.htaccessAuthConfig(E)mod_sslApache2.0.51

Thisdirectivesetsthe"user"fieldintheApacherequestobject.Thisisusedbylowermodulestoidentifytheuserwithacharacterstring.Inparticular,thismaycausetheenvironmentvariableREMOTE_USERtobeset.ThevarnamecanbeanyoftheSSLenvironmentvariables.

NotethatthisdirectivehasnoeffectiftheFakeBasicoptionisused(seeSSLOptions).

SSLUserNameSSL_CLIENT_S_DN_CN

Page 1376: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLVerifyClient

TypeofClientCertificateverificationSSLVerifyClientlevel

SSLVerifyClientnone

serverconfig,virtualhost,directory,.htaccessAuthConfig(E)mod_ssl

ThisdirectivesetstheCertificateverificationlevelfortheClientAuthentication.Noticethatthisdirectivecanbeusedbothinper-serverandper-directorycontext.Inper-servercontextitappliestotheclientauthenticationprocessusedinthestandardSSLhandshakewhenaconnectionisestablished.Inper-directorycontextitforcesaSSLrenegotationwiththereconfiguredclientverificationlevelaftertheHTTPrequestwasreadbutbeforetheHTTPresponseissent.

Thefollowinglevelsareavailableforlevel:

none:noclientCertificateisrequiredatalloptional:theclientmaypresentavalidCertificaterequire:theclienthastopresentavalidCertificateoptional_no_ca:theclientmaypresentavalidCertificatebutitneednottobe(successfully)verifiable.

Inpracticeonlylevelsnonerequirearereallyinteresting,becauseleveloptionaldoesn'tworkwithallbrowsersandleveloptional_no_caisactuallyagainsttheideaofauthentication(butcanbeusedtoestablishSSLtestpages,etc.)

SSLVerifyClientrequire

Page 1377: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 1378: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

SSLVerifyDepth

MaximumdepthofCACertificatesinClientCertificateverificationSSLVerifyDepthnumber

SSLVerifyDepth1

serverconfig,virtualhost,directory,.htaccessAuthConfig(E)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.

SSLVerifyDepth10

Page 1379: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1380: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_status

Web(B)status_modulemod_status.c

TheStatusmoduleallowsaserveradministratortofindouthowwelltheirserverisperforming.AHTMLpageispresentedthatgivesthecurrentserverstatisticsinaneasilyreadableform.Ifrequiredthispagecanbemadetoautomaticallyrefresh(givenacompatiblebrowser).Anotherpagegivesasimplemachine-readablelistofthecurrentserverstate.

Thedetailsgivenare:

ThenumberofworkerservingrequestsThenumberofidleworkerThestatusofeachworker,thenumberofrequeststhatworkerhasperformedandthetotalnumberofbytesservedbytheworker(*)Atotalnumberofaccessesandbytecountserved(*)Thetimetheserverwasstarted/restartedandthetimeithasbeenrunningforAveragesgivingthenumberofrequestspersecond,thenumberofbytesservedpersecondandtheaveragenumberofbytesperrequest(*)ThecurrentpercentageCPUusedbyeachworkerandintotalbyApache(*)Thecurrenthostsandrequestsbeingprocessed(*)

Acompile-timeoptionmustbeusedtodisplaythedetailsmarked"

Page 1381: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(*)"astheinstrumentationrequiredforobtainingthesestatisticsdoesnotexistwithinstandardApache.

Page 1382: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

EnablingStatusSupport

Toenablestatusreportsonlyforbrowsersfromthefoo.comdomainaddthiscodetoyourhttpd.confconfigurationfile

<Location/server-status>

SetHandlerserver-status

OrderDeny,Allow

Denyfromall

Allowfrom.foo.com

</Location>

YoucannowaccessserverstatisticsbyusingaWebbrowsertoaccessthepagehttp://your.server.name/server-status

Page 1383: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AutomaticUpdates

Youcangetthestatuspagetoupdateitselfautomaticallyifyouhaveabrowserthatsupports"refresh".Accessthepagehttp://your.server.name/server-status?refresh=NtorefreshthepageeveryNseconds.

Page 1384: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MachineReadableStatusFile

Amachine-readableversionofthestatusfileisavailablebyaccessingthepagehttp://your.server.name/server-status?auto.Thisisusefulwhenautomaticallyrun,seethePerlprograminthe/supportdirectoryofApache,log_server_status.

Itshouldbenotedthatifmod_statusiscompiledintotheserver,itshandlercapabilityisavailableinallconfigurationfiles,includingper-directoryfiles( .htaccess).Thismayhavesecurity-relatedramificationsforyoursite.

Page 1385: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ExtendedStatus

KeeptrackofextendedstatusinformationforeachrequestExtendedStatusOn|Off

ExtendedStatusOff

serverconfig(B)mod_statusExtendedStatusisonlyavailableinApache1.3.2

Thissettingappliestotheentireserver,andcannotbeenabledordisabledonavirtualhost-by-virtualhostbasis.Thecollectionofextendedstatusinformationcanslowdowntheserver.

Page 1386: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006129|

Page 1387: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_suexec

webCGISSI(E)suexec_modulemod_suexec.cApache2.0

suexecCGI

Page 1388: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

SuexecUserGroup

CGISuexecUserGroupUserGroup

serverconfig,virtualhost(E)mod_suexecApache2.0

SuexecUserGroupCGICGIUserApache1.3VirtualHostsUserGroup

SuexecUserGroupnobodynogroup

Page 1389: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1390: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_unique_id

(E)unique_id_modulemod_unique_id.c

Thismoduleprovidesamagictokenforeachrequestwhichisguaranteedtobeuniqueacross"all"requestsunderveryspecificconditions.Theuniqueidentifierisevenuniqueacrossmultiplemachinesinaproperlyconfiguredclusterofmachines.TheenvironmentvariableUNIQUE_IDissettotheidentifierforeachrequest.Uniqueidentifiersareusefulforvariousreasonswhicharebeyondthescopeofthisdocument.

Page 1391: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Theory

FirstabriefrecapofhowtheApacheserverworksonUnixmachines.Thisfeaturecurrentlyisn'tsupportedonWindowsNT.OnUnixmachines,Apachecreatesseveralchildren,thechildrenprocessrequestsoneatatime.Eachchildcanservemultiplerequestsinitslifetime.Forthepurposeofthisdiscussion,thechildrendon'tshareanydatawitheachother.We'llrefertothechildrenashttpdprocesses.

Yourwebsitehasoneormoremachinesunderyouradministrativecontrol,togetherwe'llcallthemaclusterofmachines.EachmachinecanpossiblyrunmultipleinstancesofApache.Allofthesecollectivelyareconsidered"theuniverse",andwithcertainassumptionswe'llshowthatinthisuniversewecangenerateuniqueidentifiersforeachrequest,withoutextensivecommunicationbetweenmachinesinthecluster.

Themachinesinyourclustershouldsatisfytheserequirements.(EvenifyouhaveonlyonemachineyoushouldsynchronizeitsclockwithNTP.)

Themachines'timesaresynchronizedviaNTPorothernetworktimeprotocol.Themachines'hostnamesalldiffer,suchthatthemodulecandoahostnamelookuponthehostnameandreceiveadifferentIPaddressforeachmachineinthecluster.

Asfarasoperatingsystemassumptionsgo,weassumethatpids(processids)fitin32-bits.Iftheoperatingsystemusesmorethan32-bitsforapid,thefixistrivialbutmustbeperformedinthecode.

Giventhoseassumptions,atasinglepointintimewecanidentifyanyhttpdprocessonanymachineintheclusterfromallotherhttpdprocesses.Themachine'sIPaddressandthepidofthehttpdprocessaresufficienttodothis.Soinordertogenerateuniqueidentifiersfor

Page 1392: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

requestsweneedonlydistinguishbetweendifferentpointsintime.

TodistinguishtimewewilluseaUnixtimestamp(secondssinceJanuary1,1970UTC),anda16-bitcounter.Thetimestamphasonlyonesecondgranularity,sothecounterisusedtorepresentupto65536valuesduringasinglesecond.Thequadruple(ip_addr,pid,time_stamp,counter)issufficienttoenumerate65536requestspersecondperhttpdprocess.Thereareissueshoweverwithpidreuseovertime,andthecounterisusedtoalleviatethisissue.

Whenanhttpdchildiscreated,thecounterisinitializedwith(currentmicrosecondsdividedby10)modulo65536(thisformulawaschosentoeliminatesomevarianceproblemswiththeloworderbitsofthemicrosecondtimersonsomesystems).Whenauniqueidentifierisgenerated,thetimestampusedisthetimetherequestarrivedatthewebserver.Thecounterisincrementedeverytimeanidentifierisgenerated(andallowedtorollover).

Thekernelgeneratesapidforeachprocessasitforkstheprocess,andpidsareallowedtorollover(they're16-bitsonmanyUnixes,butnewersystemshaveexpandedto32-bits).Soovertimethesamepidwillbereused.Howeverunlessitisreusedwithinthesamesecond,itdoesnotdestroytheuniquenessofourquadruple.Thatis,weassumethesystemdoesnotspawn65536processesinaonesecondinterval(itmayevenbe32768processesonsomeUnixes,buteventhisisn'tlikelytohappen).

Supposethattimerepeatsitselfforsomereason.Thatis,supposethatthesystem'sclockisscrewedupanditrevisitsapasttime(oritistoofarforward,isresetcorrectly,andthenrevisitsthefuturetime).Inthiscasewecaneasilyshowthatwecangetpidandtimestampreuse.Thechoiceofinitializerforthecounterisintendedtohelpdefeatthis.Notethatwereallywantarandomnumbertoinitializethecounter,buttherearen'tanyreadilyavailablenumbersonmostsystems(i.e.,youcan'tuserand()becauseyouneedtoseedthe

Page 1393: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

generator,andcan'tseeditwiththetimebecausetime,atleastatonesecondresolution,hasrepeateditself).Thisisnotaperfectdefense.

Howgoodadefenseisit?Supposethatoneofyourmachinesservesatmost500requestspersecond(whichisaveryreasonableupperboundatthiswriting,becausesystemsgenerallydomorethanjustshoveloutstaticfiles).Todothatitwillrequireanumberofchildrenwhichdependsonhowmanyconcurrentclientsyouhave.Butwe'llbepessimisticandsupposethatasinglechildisabletoserve500requestspersecond.Thereare1000possiblestartingcountervaluessuchthattwosequencesof500requestsoverlap.Sothereisa1.5%chancethatiftime(atonesecondresolution)repeatsitselfthischildwillrepeatacountervalue,anduniquenesswillbebroken.Thiswasaverypessimisticexample,andwithrealworldvaluesit'sevenlesslikelytooccur.Ifyoursystemissuchthatit'sstilllikelytooccur,thenperhapsyoushouldmakethecounter32bits(byeditingthecode).

Youmaybeconcernedabouttheclockbeing"setback"duringsummerdaylightsavings.Howeverthisisn'tanissuebecausethetimesusedhereareUTC,which"always"goforward.Notethatx86basedUnixesmayneedproperconfigurationforthistobetrue--theyshouldbeconfiguredtoassumethatthemotherboardclockisonUTCandcompensateappropriately.Butevenstill,ifyou'rerunningNTPthenyourUTCtimewillbecorrectveryshortlyafterreboot.

UNIQUE_IDenvironmentvariableisconstructedbyencodingthe112-bit(32-bitIPaddress,32bitpid,32bittimestamp,16bitcounter)quadrupleusingthealphabet[A-Za-z0-9@-]inamannersimilartoMIMEbase64encoding,producing19characters.TheMIMEbase64alphabetisactually[A-Za-z0-9+/]however+/needtobespeciallyencodedinURLs,whichmakesthemlessdesirable.Allvaluesareencodedinnetworkbyteorderingsothattheencodingiscomparableacrossarchitecturesofdifferentbyteordering.Theactualorderingoftheencodingis:timestamp,IPaddress,pid,counter.Thisorderinghasapurpose,butitshouldbeemphasizedthatapplications

Page 1394: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

shouldnotdissecttheencoding.ApplicationsshouldtreattheentireencodedUNIQUE_IDasanopaquetoken,whichcanbecomparedagainstotherUNIQUE_IDsforequalityonly.

Theorderingwaschosensuchthatit'spossibletochangetheencodinginthefuturewithoutworryingaboutcollisionwithanexistingdatabaseofUNIQUE_IDs.Thenewencodingsshouldalsokeepthetimestampasthefirstelement,andcanotherwiseusethesamealphabetandbitlength.Sincethetimestampsareessentiallyanincreasingsequence,it'ssufficienttohaveaflagsecondinwhichallmachinesintheclusterstopservingandrequest,andstopusingtheoldencodingformat.Afterwardstheycanresumerequestsandbeginissuingthenewencodings.

Thiswebelieveisarelativelyportablesolutiontothisproblem.ItcanbeextendedtomultithreadedsystemslikeWindowsNT,andcangrowwithfutureneeds.Theidentifiersgeneratedhaveessentiallyaninfinitelife-timebecausefutureidentifierscanbemadelongerasrequired.Essentiallynocommunicationisrequiredbetweenmachinesinthecluster(onlyNTPsynchronizationisrequired,whichislowoverhead),andnocommunicationbetweenhttpdprocessesisrequired(thecommunicationisimplicitinthepidvalueassignedbythekernel).Inveryspecificsituationstheidentifiercanbeshortened,butmoreinformationneedstobeassumed(forexamplethe32-bitIPaddressisoverkillforanysite,butthereisnoportableshorterreplacementforit).

Page 1395: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006129|

Page 1396: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_userdir

("/~username")(B)userdir_modulemod_userdir.c

http://example.com/~user/

Page 1397: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UserDir

UserDirdirectory-filename

serverconfig,virtualhost(B)mod_userdir

UserDir Directory-filename

disabled enabled()disabled( enabled )enabled disabled disabled

Userdir enableddisabled

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

" UserDir./"" /~root" /"" UserDir

Page 1398: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

disabledroot" Directory

UserDir

UserDirdisabled

UserDirenableduser1user2user3

UserDir

UserDirenabled

UserDirdisableduser4user5user6

(alternative)

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.html"http://www.foo.com/bob/one/two.html

Apache

2.1.4 UserDir" UserDirpublic_html"

Page 1399: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1400: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_usertrack

Session(Cookie)(E)usertrack_modulemod_usertrack.c

PreviousreleasesofApachehaveincludedamodulewhichgeneratesa'clickstream'logofuseractivityonasiteusingcookies.Thiswascalledthe"cookies"module,mod_cookies.InApache1.2andlaterthismodulehasbeenrenamedthe"usertracking"module,mod_usertrack.Thismodulehasbeensimplifiedandnewdirectivesadded.

Page 1401: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Logging

Previously,thecookiesmodule(nowtheusertrackingmodule)diditsownlogging,usingtheCookieLogdirective.Inthisrelease,thismoduledoesnologgingatall.Instead,aconfigurablelogformatfileshouldbeusedtologuserclick-streams.Thisispossiblebecausetheloggingmodulenowallowsmultiplelogfiles.Thecookieitselfisloggedbyusingthetext%{cookie}ninthelogfileformat.Forexample:

CustomLoglogs/clickstream"%{cookie}n%r%t"

ForbackwardcompatibilitytheconfigurablelogmoduleimplementstheoldCookieLogdirective,butthisshouldbeupgradedtotheaboveCustomLogdirective.

Page 1402: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

2-digitor4-digitdatesforcookies?

(thefollowingisfrommessage<[email protected]>inthenew-httpdarchives)

From:"ChristianAllen"<[email protected]>

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".

Page 1403: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CookieDomain

ThedomaintowhichthetrackingcookieappliesCookieDomaindomain

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_usertrack

Thisdirectivecontrolsthesettingofthedomaintowhichthetrackingcookieapplies.Ifnotpresent,nodomainisincludedinthecookieheaderfield.

Thedomainstringmustbeginwithadot,andmustincludeatleastoneembeddeddot.Thatis,".foo.com"islegal,but"foo.bar.com"and".com"arenot.

Page 1404: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CookieExpires

ExpirytimeforthetrackingcookieCookieExpiresexpiry-period

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_usertrack

Whenused,thisdirectivesetsanexpirytimeonthecookiegeneratedbytheusertrackmodule.Theexpiry-periodcanbegiveneitherasanumberofseconds,orintheformatsuchas"2weeks3days7hours".Validdenominationsare:years,months,weeks,days,hours,minutesandseconds.Iftheexpirytimeisinanyformatotherthanonenumberindicatingthenumberofseconds,itmustbeenclosedbydoublequotes.

Ifthisdirectiveisnotused,cookieslastonlyforthecurrentbrowsersession.

Page 1405: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CookieName

NameofthetrackingcookieCookieNametoken

CookieNameApache

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_usertrack

Thisdirectiveallowsyoutochangethenameofthecookiethismoduleusesforitstrackingpurposes.Bydefaultthecookieisnamed"Apache".

Youmustspecifyavalidcookiename;resultsareunpredictableifyouuseanamecontainingunusualcharacters.ValidcharactersincludeA-Z,a-z,0-9,"_",and"-".

Page 1406: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CookieStyle

FormatofthecookieheaderfieldCookieStyle

Netscape|Cookie|Cookie2|RFC2109|RFC2965

CookieStyleNetscape

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_usertrack

Thisdirectivecontrolstheformatofthecookieheaderfield.Thethreeformatsallowedare:

Netscape,whichistheoriginalbutnowdeprecatedsyntax.Thisisthedefault,andthesyntaxApachehashistoricallyused.CookieRFC2109,whichisthesyntaxthatsupersededtheNetscapesyntax.Cookie2RFC2965,whichisthemostcurrentcookiesyntax.

Notallclientscanunderstandalloftheseformats.butyoushouldusethenewestonethatisgenerallyacceptabletoyourusers'browsers.

Page 1407: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

CookieTracking

EnablestrackingcookieCookieTrackingon|off

CookieTrackingoff

serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_usertrack

Whentheusertrackmoduleiscompiledin,and"CookieTrackingon"isset,Apachewillstartsendingauser-trackingcookieforallnewrequests.Thisdirectivecanbeusedtoturnthisbehavioronoroffonaper-serverorper-directorybasis.Bydefault,compilingmod_usertrackwillnotactivatecookies.

Page 1408: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1409: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_version

(E)version_modulemod_version.cApache2.0.56

Thismoduleisdesignedfortheuseintestsuitesandlargenetworkswhichhavetodealwithdifferenthttpdversionsanddifferentconfigurations.Itprovidesanewcontainer--<IfVersion>,whichallowsaflexibleversioncheckingincludingnumericcomparisonsandregularexpressions.

<IfVersion2.1.0>

#currenthttpdversionisexactly2.1.0

</IfVersion>

<IfVersion>=2.2>

#usereallynewfeatures:-)

</IfVersion>

Seebelowforfurtherpossibilities.

Page 1410: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<IfVersion>

containsversiondependentconfiguration<IfVersion[[!]operator]version>...</IfVersion>

serverconfig,virtualhost,directory,.htaccessAll(E)mod_version

<IfVersion>sectionenclosesconfigurationdirectiveswhichareexecutedonlyifthehttpdversionmatchesthedesiredcriteria.Fornormal(numeric)comparisonstheversionargumenthastheformatmajor[.minor[.patch]],e.g.2.1.02.2.minorpatchareoptional.Ifthesenumbersareomitted,theyareassumedtobezero.Thefollowingnumericaloperatorsarepossible:

operator description=== httpdversionisequal> httpdversionisgreaterthan>= httpdversionisgreaterorequal< httpdversionislessthan<= httpdversionislessorequal

<IfVersion>=2.1>

#thishappensonlyinversionsgreateror

#equal2.1.0.

</IfVersion>

Besidesthenumericalcomparisonitispossibletomatcharegularexpressionagainstthehttpdversion.Therearetwowaystowriteit:

operator description

Page 1411: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

=== versionhastheform/regex/~ versionhastheformregex

<IfVersion=/^2.1.[01234]$/>

#e.g.workaroundforbuggyversions

</IfVersion>

Inordertoreversethemeaning,alloperatorscanbeprecededbyanexclamationmark(!):

<IfVersion!~^2.1.[01234]$>

#notforthoseversions

</IfVersion>

Iftheoperatorisomitted,itisassumedtobe=.

Page 1412: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006129|

Page 1413: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_vhost_alias

(E)vhost_alias_modulemod_vhost_alias.c

HTTPIP/" Host:"

mod_aliasmod_userdirURI mod_vhost_alias

/cgi-bin/script.pl/usr/local/apache2/cgi-bin/script.pl

ScriptAlias/cgi-bin/

/usr/local/apache2/cgi-bin/

VirtualScriptAlias/never/found/%0/cgi-

bin/

Page 1414: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

("name")( UseCanonicalName)""IP printf

%% (%)%p

%N.M ()

NMname Nname MN M"0" M

0 name1

2

-1

-2

2+

-2+

1+-1+ 0

NM

Page 1415: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

UseCanonicalNameOff

VirtualDocumentRoot/usr/local/apache/vhosts/%0

http://www.example.com/directory/file.html

/usr/local/apache/vhosts/www.example.com/directory/file.html

vhosts

UseCanonicalNameOff

VirtualDocumentRoot

/usr/local/apache/vhosts/%3+/%2.1/%2.2/%2.3/%2

http://www.domain.example.com/directory/file.html

/usr/local/apache/vhosts/example.com/d/o/m/domain/directory/file.html

name(hashing)

VirtualDocumentRoot

/usr/local/apache/vhosts/%3+/%2.-1/%2.-2/%2.-3/%2

/usr/local/apache/vhosts/example.com/n/i/a/domain/directory/file.html

VirtualDocumentRoot

/usr/local/apache/vhosts/%3+/%2.1/%2.2/%2.3/%2.4+

/usr/local/apache/vhosts/example.com/d/o/m/ain/directory/file.html

Page 1416: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IP

UseCanonicalNameDNS

VirtualDocumentRootIP

/usr/local/apache/vhosts/%1/%2/%3/%4/docs

VirtualScriptAliasIP

/usr/local/apache/vhosts/%1/%2/%3/%4/cgi-bin

http://www.domain.example.com/directory/file.html

/usr/local/apache/vhosts/10/20/30/40/docs/directory/file.html

www.domain.example.comIP10.20.30.40http://www.domain.example.com/cgi-bin/script.pl

/usr/local/apache/vhosts/10/20/30/40/cgi-

bin/script.pl

VirtualDocumentRoot(.) %

VirtualDocumentRoot

/usr/local/apache/vhosts/%2.0.%3.0

http://www.domain.example.com/directory/file.html

/usr/local/apache/vhosts/domain.example/directory/file.html

LogFormat%V%A

Page 1417: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

VirtualDocumentRoot

VirtualDocumentRootinterpolated-directory|none

VirtualDocumentRootnone

serverconfig,virtualhost(E)mod_vhost_alias

VirtualDocumentRootApache interpolated-directoryDocumentRoot interpolated-directorynoneVirtualDocumentRoot VirtualDocumentRootIP

Page 1418: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

VirtualDocumentRootIP

IPVirtualDocumentRootIPinterpolated-directory|none

VirtualDocumentRootIPnone

serverconfig,virtualhost(E)mod_vhost_alias

VirtualDocumentRootIPVirtualDocumentRootIP

Page 1419: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

VirtualScriptAlias

CGIVirtualScriptAliasinterpolated-directory|none

VirtualScriptAliasnone

serverconfig,virtualhost(E)mod_vhost_alias

VirtualScriptAliasApacheCGI VirtualDocumentRoot

/cgi-bin/URI" ScriptAlias/cgi-bin/"

Page 1420: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

VirtualScriptAliasIP

IPCGIVirtualScriptAliasIPinterpolated-directory|none

VirtualScriptAliasIPnone

serverconfig,virtualhost(E)mod_vhost_alias

VirtualScriptAliasIPVirtualScriptAliasIP

Page 1421: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1422: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 1423: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Handlingrequests,declining,andreturningerrorcodesSpecialconsiderationsforresponsehandlersSpecialconsiderationsforauthenticationhandlersSpecialconsiderationsforlogginghandlers

ResourceallocationandresourcepoolsConfiguration,commandsandthelike

Per-directoryconfigurationstructuresCommandhandlingSidenotes---per-serverconfiguration,virtualservers,etc.

Page 1424: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 1425: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 1426: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

containspointerstoafunctionswhichbuildsthesestructures,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},

Page 1427: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

{NULL}

};

/*Declarationsofroutinestomanipulatethe

*module'sconfigurationinfo.Notethatthese

are

*returned,andpassedin,asvoid*'s;the

server

*corekeepstrackofthem,butitdoesn't,and

can't,

*knowtheirinternalstructure.

*/

void*make_cgi_server_config(pool*);

void*merge_cgi_server_config(pool*,void*,

void*);

/*Declarationsofroutinestohandleconfig-file

commands*/

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*/

Page 1428: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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*/

};

Page 1429: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Howhandlerswork

Thesoleargumenttohandlersisarequest_recstructure.Thisstructuredescribesaparticularrequestwhichhasbeenmadetotheserver,onbehalfofaclient.Inmostcases,eachconnectiontotheclientgeneratesonlyonerequest_recstructure.

Abrieftouroftherequest_recrequest_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.

r->content_type="text/html";

Page 1430: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.

*

Page 1431: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

*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,and

clients

*shouldbetoldnottocacheit.

*/

intno_cache;

/*Variousotherconfiginfowhichmaychange

*with.htaccessfiles

*Theseareconfigvectors,withonevoid*

*pointerforeachmodule(thethingpointed

*tobeingthemodule'sbusiness).

Page 1432: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

*/

void*per_dir_config;/*Optionssetinconfigfiles,

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-request

Page 1433: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

isforafileinthesamedirectoryastheoriginalrequest).

(Server-sideincludesworkbybuildingsub-requestsandthenactuallyinvokingtheresponsehandlerforthem,viathefunctionap_run_sub_req).

Handlingrequests,declining,andreturningerrorcodesAsdiscussedabove,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.

Page 1434: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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("filepermissionsdenyserver

access",r->filename,r);

returnFORBIDDEN;

}

Page 1435: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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,thereareafewwaysoutofit.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).

Page 1436: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SpecialconsiderationsforlogginghandlersWhenarequesthasinternallyredirected,thereisthequestionofwhattolog.Apachehandlesthisbybundlingtheentirechainofredirectsintoalistofrequest_recstructureswhicharethreadedthroughther->prevandr->nextpointers.Therequest_recwhichispassedtothelogginghandlersinsuchcasesistheonewhichwasoriginallybuiltfortheinitialrequestfromtheclient;notethatthebytes_sentfieldwillonlybecorrectinthelastrequestinthechain(theoneforwhicharesponsewasactuallysent).

Page 1437: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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,whereyoureallyneedtoregistercleanupstomakesurethatthelogfilegetsclosedwhentheserverrestarts(thisismosteasilydonebyusingthe

Page 1438: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

functionap_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,

Page 1439: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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:

Page 1440: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

ptrans

shouldbeasubpoolofpchild,butcurrentlyisasubpoolofpermanent_pool,seeabove

Page 1441: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

clearedbythechildbeforegoingintotheaccept()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.Ifitwereregisteredinr->pool,thenthecodewouldwait()forthechildwhenthesubrequestfinishes.Withmod_includethiscouldbeanyold#include,andthedelaycanbeupto3seconds...andhappenedquitefrequently.Insteadthesubprocessisregisteredinr->main->poolwhichcausesittobecleanedupwhentheentirerequestisdone--i.e.,aftertheoutputhasbeensenttotheclientandlogginghashappened.

Page 1442: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Trackingopenfiles,etc.Asindicatedabove,resourcepoolsarealsousedtotrackothersortsofresourcesbesidesmemory.Themostcommonareopenfiles.Theroutinewhichistypicallyusedforthisisap_pfopen,whichtakesaresourcepoolandtwostringsasarguments;thestringsarethesameasthetypicalargumentstofopen,

...

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,sincethefilewilleventuallybeclosedregardless,butyoushouldconsideritincaseswhereyourmoduleisopening,orcouldopen,alotoffiles).

Othersortsofresources--cleanupfunctionsMoretextgoeshere.Describethethecleanupprimitivesintermsofwhichthefilestuffisimplemented;also,spawn_process.

Page 1443: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 1444: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ap_destroy_sub_req,whichfreestheresourcepool.Beforecallingthisfunction,besuretocopyanythingthatyoucareaboutwhichmightbeallocatedinthesub-request'sresourcepoolintosomeplacealittlelessvolatile(forinstance,thefilenameinitsrequest_recstructure).

(Again,undermostcircumstances,youshouldn'tfeelobligedtocallthisfunction;only2Kofmemoryorsoareallocatedforatypicalsubrequest,anditwillbefreedanywaywhenthemainrequestpooliscleared.Itisonlywhenyouareallocatingmany,manysub-requestsforasinglemainrequestthatyoushouldseriouslyconsidertheap_destroy_...functions).

Page 1445: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.Theinformationwhichisreadinthenhastobemergedwiththeapplicableinformationfromthe

Page 1446: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

server'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:thenameofthedirectorytowhichthisconfigurationinformationapplies(orNULLforsrm.conf),andapointertoaresourcepoolinwhichtheallocationshouldhappen.

Page 1447: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(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,allthatneedstobedoneisoverlaythetablesfromthenewper-directoryconfigstructurewiththosefrom

Page 1448: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

theparent:

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(for theincludesmodule,whoseper-directoryconfigurationinformationconsistssolelyofthestateoftheXBITHACK),andforthosemodules,youcanjustnotdeclareone,andleavethecorrespondingstructureslotinthemoduleitselfNULL.

CommandhandlingNowthatwehavethesestructures,weneedtobeabletofigureouthowtofillthem.ThatinvolvesprocessingtheactualAddTypeandAddEncodingcommands.Tofindcommands,theserverlooksinthe

Page 1449: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

module'scommandtable.Thattablecontainsinformationonhowmanyargumentsthecommandstake,andinwhatformats,whereitispermitted,andsoforth.Thatinformationissufficienttoallowtheservertoinvokemostcommand-handlingfunctionswithpre-parsedarguments.Withoutfurtherado,let'slookattheAddTypecommandhandler,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).

Page 1450: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TheMIMEmodule'scommandtablehasentriesforthesecommands,whichlooklikethis:

command_recmime_cmds[]={

{"AddType",add_type,NULL,OR_FILEINFO,

TAKE2,

"amimetypefollowedbyafileextension"},

{"AddEncoding",add_encoding,NULL,

OR_FILEINFO,TAKE2,

"anencoding(gzip),followedbyafile

extension"},

{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,whichmeansthat

Page 1451: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

thehandlerlooksthesameasTAKE1,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,

Page 1452: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

&fn[i])))

{

r->content_encoding=type;

/*gobacktopreviousextensiontotryto

useitasatype*/

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;

}

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

Page 1453: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

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

}

Page 1454: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1455: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DebuggingMemoryAllocationinAPR

TheallocationmechanismswithinAPRhaveanumberofdebuggingmodesthatcanbeusedtoassistinfindingmemoryproblems.Thisdocumentdescribesthemodesavailableandgivesinstructionsonactivatingthem.

Page 1456: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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're

Page 1457: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

beingplacedin.Itcurrentlyonlyworkswiththeunixmultiprocessmodel,butcouldbeextendedtoothers.

TableDebugging-MAKE_TABLE_PROFILE

Providediagnosticinformationaboutmake_table()callswhicharepossiblytoosmall.

Thisrequiresarecentgccwhichsupports__builtin_return_address().Theerror_logoutputwillbeamessagesuchas:

table_push:apr_table_tcreatedby0x804d874hit

limitof10

Usel*0x804d874tofindthesourcethatcorrespondsto.Itindicatesthataapr_table_tallocatedbyacallatthataddresshaspossiblytoosmallaninitialapr_table_tsizeguess.

AllocationStatistics-ALLOC_STATS

Providesomestatisticsonthecostofallocations.

Thisrequiresabitofanunderstandingofhowalloc.cworks.

Page 1458: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.

Page 1459: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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#define

Page 1460: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ALLOC_DEBUGabovethestartofthecommentsblockandrebuildtheserver.

Note

Inordertousethevariousoptionstheservermustberebuiltaftereditingtheheaderfile.

Page 1461: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1462: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DocumentingApache2.0

Apache2.0usesDoxygentodocumenttheAPIsandglobalvariablesinthethecode.ThiswillexplainthebasicsofhowtodocumentusingDoxygen.

Page 1463: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

BriefDescription

Tostartadocumentationblock,use/**Toendadocumentationblock,use*/

Inthemiddleoftheblock,therearemultipletagswecanuse:

Descriptionofthisfunctionspurpose

@paramparameter_namedescription

@returndescription

@deffuncsignatureofthefunction

deffuncisnotalwaysnecessary.DoxyGendoesnothaveafullparserinit,soanyprototypethatuseamacrointhereturntypedeclarationistoocomplexforscandoc.Thosefunctionsrequireadeffunc.Anexample(using&gt;ratherthan>):

/**

*returnthefinalelementofthepathname

*@parampathnameThepathtogetthefinal

elementof

*@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:

/**

Page 1464: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

*@packageNameoflibraryheader

*/

DoxygenusesanewHTMLfileforeachpackage.TheHTMLfilesarenamed{Name_of_library_header}.html,sotrytobeconcisewithyournames.

ForafurtherdiscussionofthepossibilitiespleaserefertotheDoxygensite.

Page 1465: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1466: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.0HookFunctions

Warning

Thisdocumentisstillindevelopmentandmaybepartiallyoutofdate.

Ingeneral,ahookfunctionisonethatApachewillcallatsomepointduringtheprocessingofarequest.Modulescanprovidefunctionsthatarecalled,andspecifywhentheygetcalledincomparisontoothermodules.

Page 1467: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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().

Voidhooks

Page 1468: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Ifthereturnvalueofahookisvoid,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:

Page 1469: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AP_IMPLEMENT_HOOK_RUN_ALL(int,do_something,

(request_rec*r,intn),(r,n),OK,DECLINED)

Again,OKDECLINEDarethetraditionalvalues.Youcanusewhatyouwant.

CallthehookcallersAtappropriatemomentsinthecode,callthehookcaller,likeso:

intn,ret;

request_rec*r;

ret=ap_run_do_something(r,n);

Page 1470: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Hookingthehook

Amodulethatwantsahooktobecalledneedstodotwothings.

ImplementthehookfunctionIncludetheappropriateheader,anddefineastaticfunctionofthecorrecttype:

staticintmy_something_doer(request_rec*r,int

n)

{

...

returnOK;

}

AddahookregisteringfunctionDuringinitialisation,Apachewillcalleachmoduleshookregisteringfunction,whichisincludedinthemodulestructure:

staticvoidmy_register_hooks()

{

ap_hook_do_something(my_something_doer,NULL,

NULL,APR_HOOK_MIDDLE);

}

modeMODULE_VAR_EXPORTmy_module=

{

...

my_register_hooks/*registerhooks*/

};

ControllinghookcallingorderIntheexampleabove,wedidn'tusethethreeargumentsinthehookregistrationfunctionthatcontrolcallingorder.Therearetwo

Page 1471: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mechanismsfordoingthis.Thefirst,rathercrude,method,allowsustospecifyroughlywherethehookisrunrelativetoothermodules.Thefinalargumentcontrolthis.Therearethreepossiblevalues:APR_HOOK_FIRST,APR_HOOK_MIDDLEAPR_HOOK_LAST.

Allmodulesusinganyparticularvaluemayberuninanyorderrelativetoeachother,but,ofcourse,allmodulesusingAPR_HOOK_FIRSTwillberunbeforeAPR_HOOK_MIDDLEwhicharebeforeAPR_HOOK_LAST.Modulesthatdon'tcarewhentheyarerunshoulduseAPR_HOOK_MIDDLE.(IspacedtheseoutsopeoplecoulddostufflikeAPR_HOOK_FIRST-2togetinslightlyearlier,butisthiswise?-Ben)

Notethattherearetwomorevalues,APR_HOOK_REALLY_FIRSTAPR_HOOK_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,APR_HOOK_MIDDLE);

}

Notethatthesortusedtoachievethisisstable,soorderingsetby

Page 1472: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

APR_HOOK_ORDERispreserved,asfarasispossible.

BenLaurie,15thAugust1999

Page 1473: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1474: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ConvertingModulesfromApache1.3toApache2.0

ThisisafirstattemptatwritingthelessonsIlearnedwhentryingtoconvertthemod_mmap_staticmoduletoApache2.0.It'sbynomeansdefinitiveandprobablywon'tevenbecorrectinsomeways,butit'sastart.

Page 1475: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Theeasierchanges...

CleanupRoutinesThesenowneedtobeoftypeapr_status_tandreturnavalueofthattype.NormallythereturnvaluewillbeAPR_SUCCESSunlessthereissomeneedtosignalanerrorinthecleanup.Beawarethateventhoughyousignalanerrornotallcodeyetchecksandactsupontheerror.

InitialisationRoutinesTheseshouldnowberenamedtobettersignifywheretheysitintheoverallprocess.Sothenamegetsasmallchangefrommmap_inittommap_post_config.Theargumentspassedhaveundergonearadicalchangeandnowlooklike

apr_pool_t*p

apr_pool_t*plog

apr_pool_t*ptemp

server_rec*s

DataTypesAlotofthedatatypeshavebeenmovedintotheAPR.Thismeansthatsomehavehadanamechange,suchastheoneshownabove.Thefollowingisabrieflistofsomeofthechangesthatyouarelikelytohavetomake.

poolbecomesapr_pool_ttablebecomesapr_table_t

Page 1476: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Themessierchanges...

RegisterHooksThenewarchitectureusesaseriesofhookstoprovideforcallingyourfunctions.Theseyou'llneedtoaddtoyourmodulebywayofanewfunction,staticvoidregister_hooks(void).Thefunctionisreallyreasonablystraightforwardonceyouunderstandwhatneedstobedone.Eachfunctionthatneedscallingatsomestageintheprocessingofarequestneedstoberegistered,handlersdonot.Thereareanumberofphaseswherefunctionscanbeadded,andforeachyoucanspecifywithahighdegreeofcontroltherelativeorderthatthefunctionwillbecalledin.

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

};

Thisregisters2functionsthatneedtobecalled,oneinthepost_configstage(virtuallyeverymodulewillneedthisone)andoneforthetranslate_namephase.notethatwhiletherearedifferentfunctionnamestheformatofeachisidentical.Sowhatistheformat?

ap_hook_phase_name(function_name,predecessors,

successors,position);

Thereare3hookpositionsdefined...

HOOK_FIRST

Page 1477: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HOOK_MIDDLE

HOOK_LAST

Todefinethepositionyouusethepositionandthenmodifyitwiththepredecessorsandsuccessors.Eachofthemodifierscanbealistoffunctionsthatshouldbecalled,eitherbeforethefunctionisrun(predecessors)orafterthefunctionhasrun(successors).

Inthemod_mmap_staticcaseIdidn'tcareaboutthepost_configstage,butthemmap_static_xlatmustbecalledafterthecoremodulehaddoneit'snametranslation,hencetheuseoftheaszPretodefineamodifiertothepositionHOOK_LAST.

ModuleDefinitionTherearenowalotfewerstagestoworryaboutwhencreatingyourmoduledefinition.Theolddefintionlookedlike

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*/

Page 1478: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

/*child_init*/

/*child_exit*/

/*postread-request*/

};

Thenewstructureisagreatdealsimpler...

moduleMODULE_VAR_EXPORTmodule_name_module=

{

STANDARD20_MODULE_STUFF,

/*createper-directoryconfigstructures*/

/*mergeper-directoryconfigstructures*/

/*createper-serverconfigstructures*/

/*mergeper-serverconfigstructures*/

/*commandhandlers*/

/*handlers*/

/*registerhooks*/

};

Someofthesereaddirectlyacross,somedon't.I'lltrytosummarisewhatshouldbedonebelow.

Thestagesthatreaddirectlyacross:

/*dirconfigcreater*/

/*createper-directoryconfigstructures*/

/*serverconfig*/

/*createper-serverconfigstructures*/

/*dirmerger*/

/*mergeper-directoryconfigstructures*/

/*mergeserverconfig*/

/*mergeper-serverconfigstructures*/

/*commandtable*/

/*commandapr_table_t*/

Page 1479: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

/*handlers*/

/*handlers*/

Theremainderoftheoldfunctionsshouldberegisteredashooks.Therearethefollowinghookstagesdefinedsofar...

ap_hook_post_config

thisiswheretheold_initroutinesgetregistered

ap_hook_http_method

retrievethehttpmethodfromarequest.(legacy)

ap_hook_open_logs

openanyspecifiedlogs

ap_hook_auth_checker

checkiftheresourcerequiresauthorization

ap_hook_access_checker

checkformodule-specificrestrictions

ap_hook_check_user_id

checktheuser-idandpassword

ap_hook_default_port

retrievethedefaultportfortheserver

ap_hook_pre_connection

doanysetuprequiredjustbeforeprocessing,butafteraccepting

ap_hook_process_connection

runthecorrectprotocol

ap_hook_child_init

callassoonasthechildisstarted

ap_hook_create_request

??

ap_hook_fixups

lastchancetomodifythingsbeforegeneratingcontent

ap_hook_handler

Page 1480: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

generatethecontent

ap_hook_header_parser

letsmoduleslookattheheaders,notusedbymostmodules,becausetheyusepost_read_requestforthis

ap_hook_insert_filter

toinsertfiltersintothefilterchain

ap_hook_log_transaction

loginformationabouttherequest

ap_hook_optional_fn_retrieve

retrieveanyfunctionsregisteredasoptional

ap_hook_post_read_request

calledafterreadingtherequest,beforeanyotherphase

ap_hook_quick_handler

calledbeforeanyrequestprocessing,usedbycachemodules.

ap_hook_translate_name

translatetheURIintoafilename

ap_hook_type_checker

determineand/orsetthedoctype

Page 1481: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1482: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.

Page 1483: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TheRequestProcessingCycle

Allrequestspassthroughap_process_request_internal()inrequest.c,includingsubrequestsandredirects.Ifamoduledoesn'tpassgeneratedrequeststhroughthiscode,theauthoriscautionedthatthemodulemaybebrokenbyfuturechangestorequestprocessing.

Tostreamlinerequests,themoduleauthorcantakeadvantageofthehooksofferedtodropoutoftherequestcycleearly,ortobypasscoreApachehookswhichareirrelevant(andcostlyintermsofCPU.)

Page 1484: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TheRequestParsingPhase

UnescapestheURLTherequest'sparsed_uripathisunescaped,onceandonlyonce,atthebeginningofinternalrequestprocessing.

Thisstepisbypassediftheproxyreqflagisset,ortheparsed_uri.pathelementisunset.Themodulehasnofurthercontrolofthisone-timeunescapeoperation,eitherfailingtounescapeormultiplyunescapingtheURLleadstosecurityreprecussions.

StripsParentandThisElementsfromtheURIAll/..//./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,theDocumentRootisprependedtotherequestresource.

Page 1485: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IfallmodulesDECLINEthisphase,anerror500isreturnedtothebrowser,anda"couldn'ttranslatename"errorisloggedautomatically.

Hook:map_to_storageAfterthefileorcorrectURIwasdetermined,theappropriateper-dirconfigurationsaremergedtogether.Forexample,mod_proxycomparesandmergestheappropriate<Proxy>sections.IftheURIisnothingmorethanalocal(non-proxy)TRACErequest,thecorehandlestherequestandreturnsDONE.IfnomoduleanswersthishookwithOKDONE,thecorewillruntherequestfilenameagainstthe<Directory><Files>sections.Iftherequest'filename'isn'tanabsolute,legalfilename,anoteissetforlatertermination.

URILocationWalkEveryrequestishardenedbyasecondap_location_walk()call.Thisreassuresthatatranslatedrequestisstillsubjectedtotheconfigured<Location>sections.Therequestagainborrowssomeoralloftheprocessingfromitspreviouslocation_walkabove,sothisstepisalmostalwaysveryefficientunlessthetranslatedURImappedtoasubstantiallydifferentpathorVirtualHost.

Hook:header_parserThemainrequestthenparsestheclient'sheaders.Thispreparestheremainingrequestprocessingstepstobetterservetheclient'srequest.

Page 1486: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 1487: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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;

}

Page 1488: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ThePreparationPhase

Hook:type_checkerThemoduleshaveanopportunitytotesttheURIorfilenameagainstthetargetresource,andsetmimeinformationfortherequest.Bothmod_mimemod_mime_magicusethisphasetocomparethefilenameorcontentsagainsttheadministrator'sconfigurationandsetthecontenttype,language,charactersetandrequesthandler.Somemodulesmaysetuptheirfiltersorotherrequesthandlingparametersatthistime.

IfallmodulesDECLINEthisphase,anerror500isreturnedtothebrowser,anda"couldn'tfindtypes"errorisloggedautomatically.

Hook:fixupsManymodulesare'trounced'bysomephaseabove.Thefixupsphaseisusedbymodulesto'reassert'theirownershiporforcetherequest'sfieldstotheirappropriatevalues.Itisn'talwaysthecleanestmechanism,butoccasionallyit'stheonlyoption.

Page 1489: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

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.

Page 1490: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1491: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HowfiltersworkinApache2.0

Warning

Thisisacut'npastejobfromanemail(<022501c1c529$f63a9550$7f00000a@KOJ>)andonlyreformattedforbetterreadability.It'snotuptodatebutmaybeagoodstartforfurtherresearch.

Page 1492: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.Becausethisfilterisactiveatthebeginning

Page 1493: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ofallrequests,itcannotberemovedifitisredirected,sothisisaprotocolfilter.

http_headerThisfilteractuallywritestheheaderstothenetwork.Thisisobviouslyarequiredfilter(exceptintheasiscasewhichisspecialandwillbedealtwithbelow)andsoitisaprotocolfilter.

DeflateTheadministratorconfiguresthisfilterbasedonwhichfilehasbeenrequested.Ifwedoaninternalredirectfromanautoindexpagetoanindex.htmlpage,thedeflatefiltermaybeaddedorremovedbasedonconfig,sothisisaresourcefilter.

Thefurtherbreakdownofeachcategoryintotwomorefiltertypesisstrictlyforordering.Wecouldremoveit,andonlyallowforonefiltertype,buttheorderwouldtendtobewrong,andwewouldneedtohackthingstomakeitwork.Currently,theRESOURCEfiltersonlyhaveonefiltertype,butthatshouldchange.

Page 1494: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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-->...

Page 1495: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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,thesolutionIchosewastomakethepreviouspointeralwaysstayontheoriginalrequest.

Page 1496: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Thiscausessomemorecomplexlogic,butitworksforallcases.Myconcerninhavingitmovetothesub-request,isthatforthemorecommoncase(whereasub-requestisusedtoadddatatoaresponse),themainfilterchainwouldbewrong.Thatdidn'tseemlikeagoodideatome.

Page 1497: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Asis

Thefinaltopic.:-)Mod_Asisisabitofahack,butthehandlerneedstoremoveallfiltersexceptforconnectionfilters,andsendthedata.Ifyouareusingmod_asis,allotherbetsareoff.

Page 1498: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Explanations

Theabsolutelylastpointisthatthereasonthiscodewassohardtogetright,wasbecausewehadhackedsomuchtoforceittowork.Iwrotemostofthehacksoriginally,soIamverymuchtoblame.However,nowthatthecodeisright,Ihavestartedtoremovesomehacks.Mostpeopleshouldhaveseenthatthereset_filtersadd_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.

Page 1499: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200613|

Page 1500: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Page 1501: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(AccessControl)Apache URL

(Algorithm)(Cipher)

Apache(APacheeXtensionTool)(apxs)perl (module)(DSO)Apacheweb

apxs

Apache(ApachePortableRuntime)(APR)APRApacheHTTPServer

ApachePortableRuntimeProject

(Authentication)

(Certificate)X.509([subject]) (CertificationAuthority)([issuer])

(publickey)(CA)CASSL/TLS

(CertificateSigningRequest)(CSR)(CertificationAuthority)CA(PrivateKey)(certificate)CSR

SSL/TLS

(CertificationAuthority)(CA)CA

SSL/TLS

(Cipher)DESIDEARC4

SSL/TLS

(Ciphertext)(Plaintext)(Cipher)

SSL/TLS

Page 1502: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(CommonGatewayInterface)(CGI)web ()(NCSA) RFC

CGI

(ConfigurationDirective)(Directive)

(ConfigurationFile)Apache(Directives)

(CONNECT)HTTPHTTP(method)SSL

(Context)(Directives)

(DigitalSignature)(CertificationAuthority)(PublicKey)(Certificate) (Private

Key)(CA) CASSL/TLS

(Directive)(ConfigurationFile)Apache

(DynamicSharedObject)(DSO)Apachehttpd(Modules)

(EnvironmentVariable)(env-variable)shellApacheApacheshell

Apache

(Export-Crippled)()(EAR)

SSL/TLS

(Filter)

Page 1503: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

INCLUDES(ServerSideIncludes)

(Fully-QualifiedDomain-Name)(FQDN)IP www example.com www.example.com

(Handler)Apache"" cgi-scriptCGI

Apache

/(Hash)(hash)

(Header)HTTP(meta-information)

.htaccess(configurationfile)(Directive)

httpd.confApache(configurationfile)/usr/local/apache2/conf/httpd.conf

(HyperTextTransferProtocol)(HTTP)WWWApache1.1 RFC2616HTTP/1.1

HTTPS(Secure)WWW SSLHTTP

SSL/TLS

(Method)HTTPHTTP GETPOSTPUT

(MessageDigest)

SSL/TLS

MIME(MIME-type)(MIME) text/html,image/gif,

Page 1504: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

application/octet-streamHTTPMIME Content-

Type(header)mod_mime

(Module)ApacheApache httpd(staticmodule)(dynamicmodule)DSO(basemodule)ApacheApacheHTTPtar(tarball) (third-partymodule)

(ModuleMagicNumber)(MMN)ApacheApacheAPIMMNApache

OpenSSLSSL/TLS

http://www.openssl.org/

(PassPhrase)(Cipher)/

SSL/TLS

(Plaintext)

(PrivateKey)

SSL/TLS

(Proxy)(originserver)

mod_proxy

(PublicKey)

SSL/TLS

(PublicKeyCryptography)""(AsymmetricCryptography)

SSL/TLS

Page 1505: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(RegularExpression)(Regex)"A""10""Q"Apache"images".gif.jpg" /images/.*(jpg|gif)$"ApachePCREPerl

(ReverseProxy)(originserver)(proxy)

(SecureSocketsLayer)(SSL)NetscapeTCP/IP HTTPSSSL

SSL/TLS

(ServerSideIncludes)(SSI)HTML

(Session)

SSLeayEricA.YoungSSL/TLS

(SymmetricCryptography)

SSL/TLS

Tar(Tarball)tarApachetarpkzip

(TransportLayerSecurity)(TLS)Internet(IETF)SSLTCP/IPTLS1SSL3

SSL/TLS

(UniformResourceLocator)(URL)Internet/ (UniformResourceIdentifier)URL http

httpsURLhttp://httpd.apache.org/docs/2.2/glossary.html

(UniformResourceIdentifier)(URI)RFC2396URI URL

Page 1506: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

(VirtualHosting)Apache IP(IPvirtualhosting)IP (name-basedvirtualhosting)IP

Apache

X.509(ITU)SSL/TLS

SSL/TLS

Page 1507: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006121|

Page 1508: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

A|B|C|D|E|F|G|H|I|K|L|M|N|O|P|R|S|T|U|V|W|X

AcceptFilterAcceptMutexAcceptPathInfoAccessFileNameActionAddAltAddAltByEncodingAddAltByTypeAddCharsetAddDefaultCharsetAddDescriptionAddEncodingAddHandlerAddIconAddIconByEncodingAddIconByTypeAddInputFilterAddLanguageAddModuleInfoAddOutputFilterAddOutputFilterByTypeAddTypeAliasAliasMatchAllow

Page 1509: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AllowCONNECTAllowEncodedSlashesAllowOverrideAnonymousAnonymous_LogEmailAnonymous_MustGiveEmailAnonymous_NoUserIDAnonymous_VerifyEmailAuthBasicAuthoritativeAuthBasicProviderAuthDBDUserPWQueryAuthDBDUserRealmQueryAuthDBMGroupFileAuthDBMTypeAuthDBMUserFileAuthDefaultAuthoritativeAuthDigestAlgorithmAuthDigestDomainAuthDigestNcCheckAuthDigestNonceFormatAuthDigestNonceLifetimeAuthDigestProviderAuthDigestQopAuthDigestShmemSizeAuthGroupFileAuthLDAPBindDNAuthLDAPBindPasswordAuthLDAPCharsetConfigAuthLDAPCompareDNOnServerAuthLDAPDereferenceAliasesAuthLDAPGroupAttributeAuthLDAPGroupAttributeIsDNAuthLDAPRemoteUserIsDNAuthLDAPUrl

Page 1510: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthName<AuthnProviderAlias>AuthTypeAuthUserFileAuthzDBMAuthoritativeAuthzDBMTypeAuthzDefaultAuthoritativeAuthzGroupFileAuthoritativeAuthzLDAPAuthoritativeAuthzOwnerAuthoritativeAuthzUserAuthoritativeBrowserMatchBrowserMatchNoCaseBufferedLogsCacheDefaultExpireCacheDirLengthCacheDirLevelsCacheDisableCacheEnableCacheFileCacheIgnoreCacheControlCacheIgnoreHeadersCacheIgnoreNoLastModCacheLastModifiedFactorCacheMaxExpireCacheMaxFileSizeCacheMinFileSizeCacheNegotiatedDocsCacheRootCacheStoreNoStoreCacheStorePrivateCGIMapExtensionCharsetDefaultCharsetOptions

Page 1511: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CharsetSourceEncCheckSpellingContentDigestCookieDomainCookieExpiresCookieLogCookieNameCookieStyleCookieTrackingCoreDumpDirectoryCustomLogDavDavDepthInfinityDavGenericLockDBDavLockDBDavMinTimeoutDBDExptimeDBDKeepDBDMaxDBDMinDBDParamsDBDPersistDBDPrepareSQLDBDriverDefaultIconDefaultLanguageDefaultTypeDeflateBufferSizeDeflateCompressionLevelDeflateFilterNoteDeflateMemLevelDeflateWindowSizeDeny<Directory>

Page 1512: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DirectoryIndex<DirectoryMatch>DirectorySlashDocumentRootDumpIOInputDumpIOOutputEnableExceptionHookEnableMMAPEnableSendfileErrorDocumentErrorLogExampleExpiresActiveExpiresByTypeExpiresDefaultExtendedStatusExtFilterDefineExtFilterOptionsFileETag<Files><FilesMatch>FilterChainFilterDeclareFilterProtocolFilterProviderFilterTraceForceLanguagePriorityForceTypeForensicLogGracefulShutdownTimeoutGroupHeaderHeaderNameHostnameLookups

Page 1513: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IdentityCheckIdentityCheckTimeout<IfDefine><IfModule><IfVersion>ImapBaseImapDefaultImapMenuIncludeIndexIgnoreIndexOptionsIndexOrderDefaultIndexStyleSheetISAPIAppendLogToErrorsISAPIAppendLogToQueryISAPICacheFileISAPIFakeAsyncISAPILogNotSupportedISAPIReadAheadBufferKeepAliveKeepAliveTimeoutLanguagePriorityLDAPCacheEntriesLDAPCacheTTLLDAPConnectionTimeoutLDAPOpCacheEntriesLDAPOpCacheTTLLDAPSharedCacheFileLDAPSharedCacheSizeLDAPTrustedClientCertLDAPTrustedGlobalCertLDAPTrustedModeLDAPVerifyServerCert<Limit>

Page 1514: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<LimitExcept>LimitInternalRecursionLimitRequestBodyLimitRequestFieldsLimitRequestFieldSizeLimitRequestLineLimitXMLRequestBodyListenListenBackLogLoadFileLoadModule<Location><LocationMatch>LockFileLogFormatLogLevelMaxClientsMaxKeepAliveRequestsMaxMemFreeMaxRequestsPerChildMaxRequestsPerThreadMaxSpareServersMaxSpareThreadsMaxThreadsMCacheMaxObjectCountMCacheMaxObjectSizeMCacheMaxStreamingBufferMCacheMinObjectSizeMCacheRemovalAlgorithmMCacheSizeMetaDirMetaFilesMetaSuffixMimeMagicFile

Page 1515: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MinSpareServersMinSpareThreadsMMapFileModMimeUsePathInfoMultiviewsMatchNameVirtualHostNoProxyNWSSLTrustedCertsNWSSLUpgradeableOptionsOrderPassEnvPidFileProtocolEcho<Proxy>ProxyBadHeaderProxyBlockProxyDomainProxyErrorOverrideProxyIOBufferSize<ProxyMatch>ProxyMaxForwardsProxyPassProxyPassReverseProxyPassReverseCookieDomainProxyPassReverseCookiePathProxyPreserveHostProxyReceiveBufferSizeProxyRemoteProxyRemoteMatchProxyRequestsProxyTimeoutProxyViaReadmeName

Page 1516: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ReceiveBufferSizeRedirectRedirectMatchRedirectPermanentRedirectTempRemoveCharsetRemoveEncodingRemoveHandlerRemoveInputFilterRemoveLanguageRemoveOutputFilterRemoveTypeRequestHeaderRequireRewriteBaseRewriteCondRewriteEngineRewriteLockRewriteLogRewriteLogLevelRewriteMapRewriteOptionsRewriteRuleRLimitCPURLimitMEMRLimitNPROCSatisfyScoreBoardFileScriptScriptAliasScriptAliasMatchScriptInterpreterSourceScriptLogScriptLogBuffer

Page 1517: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ScriptLogLengthScriptSockSecureListenSendBufferSizeServerAdminServerAliasServerLimitServerNameServerPathServerRootServerSignatureServerTokensSetEnvSetEnvIfSetEnvIfNoCaseSetHandlerSetInputFilterSetOutputFilterSSIEndTagSSIErrorMsgSSIStartTagSSITimeFormatSSIUndefinedEchoSSLCACertificateFileSSLCACertificatePathSSLCADNRequestFileSSLCADNRequestPathSSLCARevocationFileSSLCARevocationPathSSLCertificateChainFileSSLCertificateFileSSLCertificateKeyFileSSLCipherSuiteSSLCryptoDevice

Page 1518: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SSLEngineSSLHonorCipherOrderSSLMutexSSLOptionsSSLPassPhraseDialogSSLProtocolSSLProxyCACertificateFileSSLProxyCACertificatePathSSLProxyCARevocationFileSSLProxyCARevocationPathSSLProxyCipherSuiteSSLProxyEngineSSLProxyMachineCertificateFileSSLProxyMachineCertificatePathSSLProxyProtocolSSLProxyVerifySSLProxyVerifyDepthSSLRandomSeedSSLRequireSSLRequireSSLSSLSessionCacheSSLSessionCacheTimeoutSSLUserNameSSLVerifyClientSSLVerifyDepthStartServersStartThreadsSuexecUserGroupThreadLimitThreadsPerChildThreadStackSizeTimeOutTraceEnableTransferLog

Page 1519: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

TypesConfigUnsetEnvUseCanonicalNameUseCanonicalPhysicalPortUserUserDirVirtualDocumentRootVirtualDocumentRootIP<VirtualHost>VirtualScriptAliasVirtualScriptAliasIPWin32DisableAcceptExXBitHack

Page 1520: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |???|

Page 1521: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

()"+"

A|B|C|D|E|F|G|H|I|K|L|M|N|O|P|R|S|T|

U|V|W|X

s serverconfig

v virtualhost

d directory

h .htaccess

CM MPMBEX

AcceptFilterprotocolaccept_filterSocket

AcceptMutexDefault|method DefaultApache()(socket)

AcceptPathInfoOn|Off|Default Default

AccessFileNamefilename[filename]... .htaccess

Actionaction-typecgi-script[virtual]CGI

AddAltstringfile[file]...Alternatetexttodisplayforafile,insteadofaniconselectedbyfilename

AddAltByEncodingstringMIME-encoding[MIME-encoding]...AlternatetexttodisplayforafileinsteadofaniconselectedbyMIME-encoding

AddAltByTypestringMIME-type[MIME-type]...Alternatetexttodisplayforafile,insteadofaniconselectedbyMIMEcontent-

Page 1522: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

typeAddCharsetcharsetextension[extension]...

AddDefaultCharsetOn|Off|charset Offtext/plaintext/htmlHTTP

AddDescriptionstringfile[file]...Descriptiontodisplayforafile

AddEncodingMIME-encextension[extension]...

AddHandlerhandler-nameextension[extension]...

AddIconiconname[name]...Icontodisplayforafileselectedbyname

AddIconByEncodingiconMIME-encoding[MIME-encoding]...IcontodisplaynexttofilesselectedbyMIMEcontent-encoding

AddIconByTypeiconMIME-type[MIME-type]...IcontodisplaynexttofilesselectedbyMIMEcontent-type

AddInputFilterfilter[;filter...]extension[extension]...

AddLanguageMIME-langextension[extension]...

AddModuleInfomodule-namestringserver-info

AddOutputFilterfilter[;filter...]extension[extension]...

Page 1523: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AddOutputFilterByTypefilter[;filter...]MIME-type[MIME-type]...MIME

AddTypeMIME-typeextension[extension]...

AliasURL-pathfile-path|directory-pathURL

AliasMatchregexfile-path|directory-pathURL

Allowfromall|host|env=env-variable[host|env=env-variable]...

AllowCONNECTport[port]... 443563CONNECT

AllowEncodedSlashesOn|Off OffURL

AllowOverrideAll|None|directive-type[directive-type]...

All

.htaccessAnonymoususer[user]...SpecifiesuserIDsthatareallowedaccesswithoutpasswordverification

Anonymous_LogEmailOn|Off OnSetswhetherthepasswordenteredwillbeloggedintheerrorlog

Anonymous_MustGiveEmailOn|Off OnSpecifieswhetherblankpasswordsareallowed

Anonymous_NoUserIDOn|Off OffSetswhethertheuserIDfieldmaybeempty

Anonymous_VerifyEmailOn|Off OffSetswhethertocheckthepasswordfieldforacorrectlyformattedemailaddress

Page 1524: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

AuthBasicAuthoritativeOn|Off On()

AuthBasicProviderprovider-name[provider-name]...

file

()(Provider)AuthDBDUserPWQueryquerySQLquerytolookupapasswordforauser

AuthDBDUserRealmQueryquerySQLquerytolookupapasswordhashforauserandrealm.

AuthDBMGroupFilefile-pathSetsthenameofthedatabasefilecontainingthelistofusergroupsforauthorization

AuthDBMTypedefault|SDBM|GDBM|NDBM|DB

default

SetsthetypeofdatabasefilethatisusedtostorepasswordsAuthDBMUserFilefile-pathSetsthenameofadatabasefilecontainingthelistofusersandpasswordsforauthentication

AuthDefaultAuthoritativeOn|Off On

AuthDigestAlgorithmMD5|MD5-sess MD5

AuthDigestDomainURI[URI]...URI

AuthDigestNcCheckOn|Off OffEnablesordisablescheckingofthenonce-countsentbytheserver

AuthDigestNonceFormatformatDetermineshowthenonceisgenerated

AuthDigestNonceLifetimeseconds 300nonce()

AuthDigestProviderprovider-name[provider- file

Page 1525: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

name]...()(Provider)

AuthDigestQopnone|auth|auth-int[auth|auth-int]

auth

AuthDigestShmemSizesize 1000

AuthGroupFilefile-path

AuthLDAPBindDNdistinguished-nameOptionalDNtouseinbindingtotheLDAPserver

AuthLDAPBindPasswordpasswordPasswordusedinconjuctionwiththebindDN

AuthLDAPCharsetConfigfile-pathLanguagetocharsetconversionconfigurationfile

AuthLDAPCompareDNOnServeron|off onUsetheLDAPservertocomparetheDNs

AuthLDAPDereferenceAliasesnever|searching|finding|always

Always

Whenwillthemodulede-referencealiasesAuthLDAPGroupAttributeattributeLDAPattributesusedtocheckforgroupmembership

AuthLDAPGroupAttributeIsDNon|off onUsetheDNoftheclientusernamewhencheckingforgroupmembership

AuthLDAPRemoteUserIsDNon|off offUsetheDNoftheclientusernametosettheREMOTE_USERenvironmentvariable

AuthLDAPUrlurl[NONE|SSL|TLS|STARTTLS]URLspecifyingtheLDAPsearchparameters

AuthNameauth-domainHTTP

Page 1526: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

<AuthnProviderAliasbaseProviderAlias>...</AuthnProviderAlias>

AuthTypeBasic|Digest

AuthUserFilefile-path/

AuthzDBMAuthoritativeOn|Off OnSetswhetherauthorizationwillbepassedontolowerlevelmodules

AuthzDBMTypedefault|SDBM|GDBM|NDBM|DB

default

SetsthetypeofdatabasefilethatisusedtostorelistofusergroupsAuthzDefaultAuthoritativeOn|Off On

AuthzGroupFileAuthoritativeOn|Off On

AuthzLDAPAuthoritativeon|off onPreventotherauthenticationmodulesfromauthenticatingtheuserifthisonefails

AuthzOwnerAuthoritativeOn|Off On

AuthzUserAuthoritativeOn|Off On

BrowserMatchregex[!]env-variable[=value][[!]env-variable[=value]]...User-Agent

BrowserMatchNoCaseregex[!]env-variable[=value][[!]env-variable[=value]]...User-Agent

BufferedLogsOn|Off Off

Page 1527: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheDefaultExpireseconds 3600(onehour)Thedefaultdurationtocacheadocumentwhennoexpirydateisspecified.

CacheDirLengthlength 2Thenumberofcharactersinsubdirectorynames

CacheDirLevelslevels 3Thenumberoflevelsofsubdirectoriesinthecache.

CacheDisableurl-stringDisablecachingofspecifiedURLs

CacheEnablecache_typeurl-stringEnablecachingofspecifiedURLsusingaspecifiedstoragemanager

CacheFilefile-path[file-path]...Cachealistoffilehandlesatstartuptime

CacheIgnoreCacheControlOn|Off OffIgnorerequesttonotservecachedcontenttoclient

CacheIgnoreHeadersheader-string[header-string]...

None

DonotstorethegivenHTTPheader(s)inthecache.CacheIgnoreNoLastModOn|Off OffIgnorethefactthataresponsehasnoLastModifiedheader.

CacheLastModifiedFactorfloat 0.1ThefactorusedtocomputeanexpirydatebasedontheLastModifieddate.

CacheMaxExpireseconds 86400(oneday)Themaximumtimeinsecondstocacheadocument

CacheMaxFileSizebytes 1000000Themaximumsize(inbytes)ofadocumenttobeplacedinthecache

CacheMinFileSizebytes 1Theminimumsize(inbytes)ofadocumenttobeplacedinthecache

CacheNegotiatedDocsOn|Off Off

CacheRootdirectoryThedirectoryrootunderwhichcachefilesarestored

Page 1528: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CacheStoreNoStoreOn|Off OffAttempttocacherequestsorresponsesthathavebeenmarkedasno-store.

CacheStorePrivateOn|Off OffAttempttocacheresponsesthattheserverhasmarkedasprivate

CGIMapExtensioncgi-path.extensionCGI

CharsetDefaultcharsetCharsettotranslateinto

CharsetOptionsoption[option]... DebugLevel=0NoImpl+Configurescharsettranslationbehavior

CharsetSourceEnccharsetSourcecharsetoffiles

CheckSpellingon|off OffEnablesthespellingmodule

ContentDigestOn|Off OffContent-MD5

CookieDomaindomainThedomaintowhichthetrackingcookieapplies

CookieExpiresexpiry-periodExpirytimeforthetrackingcookie

CookieLogfilenamecookies

CookieNametoken ApacheNameofthetrackingcookie

CookieStyleNetscape|Cookie|Cookie2|RFC2109|RFC2965

Netscape

FormatofthecookieheaderfieldCookieTrackingon|off offEnablestrackingcookie

CoreDumpDirectorydirectoryApache

Page 1529: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CustomLogfile|pipeformat|nickname[env=[!]environment-variable]

DavOn|Off|provider-name OffEnableWebDAVHTTPmethods

DavDepthInfinityon|off offAllowPROPFIND,Depth:Infinityrequests

DavGenericLockDBfile-pathLocationoftheDAVlockdatabase

DavLockDBfile-pathLocationoftheDAVlockdatabase

DavMinTimeoutseconds 0MinimumamountoftimetheserverholdsalockonaDAVresource

DBDExptimetime-in-secondsKeepalivetimeforidleconnections

DBDKeepnumberMaximumsustainednumberofconnections

DBDMaxnumberMaximumnumberofconnections

DBDMinnumberMinimumnumberofconnections

DBDParamsparam1=value1[,param2=value2]Parametersfordatabaseconnection

DBDPersist0|1Whethertousepersistentconnections

DBDPrepareSQL"SQLstatement"labelDefineanSQLpreparedstatement

DBDrivernameSpecifyanSQLdriver

DefaultIconurl-pathIcontodisplayforfileswhennospecificiconisconfigured

Page 1530: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DefaultLanguageMIME-lang

DefaultTypeMIME-type text/plainMIME

DeflateBufferSizevalue 8096zlib()

DeflateCompressionLevelvalue

DeflateFilterNote[type]notename

DeflateMemLevelvalue 9zlib

DeflateWindowSizevalue 15Zlib(compressionwindow)

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 Off

DumpIOOutputOn|Off Off

Page 1531: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

EnableExceptionHookOn|Off Off

EnableMMAPOn|Off On(memory-mapping)

EnableSendfileOn|Off Onsendfile

ErrorDocumenterror-codedocument

ErrorLogfile-path|syslog[:facility] logs/error_log(Uni+

ExampleDemonstrationdirectivetoillustratetheApachemoduleAPI

ExpiresActiveOn|Off"Expires:""Cache-Control:"

ExpiresByTypeMIME-type<code>secondsMIMEExpires

ExpiresDefault<code>seconds

ExtendedStatusOn|Off OffKeeptrackofextendedstatusinformationforeachrequest

ExtFilterDefinefilternameparametersDefineanexternalfilter

ExtFilterOptionsoption[option]... DebugLevel=0NoLogS+

Configuremod_ext_filteroptionsFileETagcomponent... INodeMTimeSizeETag

<Filesfilename>...</Files>

<FilesMatchregex>...</FilesMatch>

Page 1532: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FilterChain[+=-@!]filter-name...Configurethefilterchain

FilterDeclarefilter-name[type]Declareasmartfilter

FilterProtocolfilter-name[provider-name]proto-flagsDealwithcorrectHTTPprotocolhandling

FilterProviderfilter-nameprovider-name[req|resp|env]=dispatchmatchRegisteracontentfilter

FilterTracefilter-namelevelGetdebug/diagnosticinformationfrommod_filter

ForceLanguagePriorityNone|Prefer|Fallback[Prefer|Fallback]

Prefer

ForceTypeMIME-type|NoneMIME

ForensicLogfilename|pipeSetsfilenameoftheforensiclog

GracefulShutDownTimeoutseconds

Groupunix-group #-1Apache

Header[condition]set|append|add|unset|echoheader[value][early|env=[!]variable]HTTP

HeaderNamefilenameNameofthefilethatwillbeinsertedatthetopoftheindexlisting

HostnameLookupsOn|Off|Double OffIPDNS

IdentityCheckOn|Off Off

Page 1533: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RFC1413IdentityCheckTimeoutseconds 30Determinesthetimeoutdurationforidentrequests

<IfDefine[!]parameter-name>...</IfDefine>

<IfModule[!]module-file|module-identifier>...</IfModule>

<IfVersion[[!]operator]version>...</IfVersion>containsversiondependentconfiguration

ImapBasemap|referer|URL http://servername/Defaultbaseforimagemapfiles

ImapDefaulterror|nocontent|map|referer|URL nocontentDefaultactionwhenanimagemapiscalledwithcoordinatesthatarenotexplicitlymapped

ImapMenunone|formatted|semiformatted|unformattedActionifnocoordinatesaregivenwhencallinganimagemap

Includefile-path|directory-path

IndexIgnorefile[file]...Addstothelistoffilestohidewhenlistingadirectory

IndexOptions[+|-]option[[+|-]option]...Variousconfigurationsettingsfordirectoryindexing

IndexOrderDefaultAscending|DescendingName|Date|Size|Description

AscendingName

SetsthedefaultorderingofthedirectoryindexIndexStyleSheeturl-pathAddsaCSSstylesheettothedirectoryindex

ISAPIAppendLogToErrorson|off off

Page 1534: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ISAPIHSE_APPEND_LOG_PARAMETERISAPIAppendLogToQueryon|off onISAPIHSE_APPEND_LOG_PARAMETER

ISAPICacheFilefile-path[file-path]...ISAPI

ISAPIFakeAsyncon|off offISAPI

ISAPILogNotSupportedon|off offISAPI

ISAPIReadAheadBuffersize 49152ISAPI

KeepAliveOn|Off OnHTTP

KeepAliveTimeoutseconds 5

LanguagePriorityMIME-lang[MIME-lang]...

LDAPCacheEntriesnumber 1024LDAP

LDAPCacheTTLseconds 600search/bind

LDAPConnectionTimeoutseconds

LDAPOpCacheEntriesnumber 1024LDAPcompare

LDAPOpCacheTTLseconds 600

LDAPSharedCacheFiledirectory-path/filename

LDAPSharedCacheSizebytes 102400

Page 1535: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

LDAPTrustedClientCerttypedirectory-path/filename/nickname[password]Setsthefilecontainingornicknamereferringtoaperconnectionclientcertificate.NotallLDAPtoolkitssupportperconnectionclientcertificates.

LDAPTrustedGlobalCerttypedirectory-path/filename[password]SetsthefileordatabasecontainingglobaltrustedCertificateAuthorityorglobalclientcertificates

LDAPTrustedModetypeSpecifiestheSSL/TLSmodetobeusedwhenconnectingtoanLDAPserver.

LDAPVerifyServerCertOn|Off OnForceservercertificateverification

<Limitmethod[method]...>...</Limit>HTTP

<LimitExceptmethod[method]...>...</LimitExcept>HTTP

LimitInternalRecursionnumber[number] 10

LimitRequestBodybytes 0HTTP

LimitRequestFieldsnumber 100HTTP

LimitRequestFieldsizebytes

LimitRequestLinebytes 8190HTTP

LimitXMLRequestBodybytes 1000000XML

Listen[IP-address:]portnumber[protocol]

Page 1536: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

IPListenBacklogbacklog(pendingconnection)

LoadFilefilename[filename]...

LoadModulemodulefilename

<LocationURL-path|URL>...</Location>URL

<LocationMatchregex>...</LocationMatch>URL

LockFilefilename logs/accept.lock

LogFormatformat|nickname[nickname] "%h%l%u%t\"%r\"+

LogLevellevel warn

MaxClientsnumber

MaxKeepAliveRequestsnumber 100

MaxMemFreeKBytes 0free()(KB)

MaxRequestsPerChildnumber 10000

MaxRequestsPerThreadnumber 0Limitonthenumberofrequeststhatanindividualthreadwillhandleduringitslife

MaxSpareServersnumber 10

MaxSpareThreadsnumber

Page 1537: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MaxThreadsnumber 2048Setthemaximumnumberofworkerthreads

MCacheMaxObjectCountvalue 1009

MCacheMaxObjectSizebytes 10000()

MCacheMaxStreamingBuffersize_in_bytes thesmallerof1000+

MCacheMinObjectSizebytes 0()

MCacheRemovalAlgorithmLRU|GDSF GDSF

MCacheSizeKBytes 100KB

MetaDirdirectory .webNameofthedirectorytofindCERN-stylemetainformationfiles

MetaFileson|off offActivatesCERNmeta-fileprocessing

MetaSuffixsuffix .metaFilenamesuffixforthefilecontaingCERN-stylemetainformation

MimeMagicFilefile-pathMagicMIME

MinSpareServersnumber 5

MinSpareThreadsnumber

MMapFilefile-path[file-path]...Mapalistoffilesintomemoryatstartuptime

ModMimeUsePathInfoOn|Off Offpath_info

Page 1538: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MultiviewsMatchAny|NegotiatedOnly|Filters|Handlers[Handlers|Filters]

NegotiatedOnly

MultiViewsNameVirtualHostaddr[:port]IP()

NoProxyhost[host]...//

NWSSLTrustedCertsfilename[filename]...

NWSSLUpgradeable[IP-address:]portnumberSSL

Options[+|-]option[[+|-]option]... All

Orderordering Deny,AllowAllowDeny

PassEnvenv-variable[env-variable]...shell

PidFilefilename logs/httpd.pid()PID

ProtocolEchoOn|OffTurntheechoserveronoroff

<Proxywildcard-url>...</Proxy>

ProxyBadHeaderIsError|Ignore|StartBody IsError

ProxyBlock*|word|host|domain[word|host|domain]...

ProxyDomainDomain

Page 1539: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyErrorOverrideOn|Off Off

ProxyIOBufferSizebytes 8192

<ProxyMatchregex>...</ProxyMatch>

ProxyMaxForwardsnumber 10

ProxyPass[path]!|url[key=valuekey=value...]]URL

ProxyPassReverse[path]urlHTTPURL

ProxyPassReverseCookieDomaininternal-domainpublic-domainAdjuststheDomainstringinSet-Cookieheadersfromareverse-proxiedserver

ProxyPassReverseCookiePathinternal-pathpublic-pathAdjuststhePathstringinSet-Cookieheadersfromareverse-proxiedserver

ProxyPreserveHostOn|Off OffHTTP

ProxyReceiveBufferSizebytes 0HTTPFTP()

ProxyRemotematchremote-server

ProxyRemoteMatchregexremote-server

ProxyRequestsOn|Off Off()

ProxyTimeoutseconds 300

Page 1540: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ProxyViaOn|Off|Full|Block OffVia

ReadmeNamefilenameNameofthefilethatwillbeinsertedattheendoftheindexlisting

ReceiveBufferSizebytes 0TCP()

Redirect[status]URL-pathURLURL

RedirectMatch[status]regexURLURL

RedirectPermanentURL-pathURLURL

RedirectTempURL-pathURLURL

RemoveCharsetextension[extension]...

RemoveEncodingextension[extension]...

RemoveHandlerextension[extension]...

RemoveInputFilterextension[extension]...

RemoveLanguageextension[extension]...

RemoveOutputFilterextension[extension]...

RemoveTypeextension[extension]...

RequestHeaderset|append|add|unsetheader[value][early|env=[!]variable]

Page 1541: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

HTTPRequireentity-name[entity-name]...

RewriteBaseURL-pathSetsthebaseURLforper-directoryrewrites

RewriteCondTestStringCondPatternDefinesaconditionunderwhichrewritingwilltakeplace

RewriteEngineon|off offEnablesordisablesruntimerewritingengine

RewriteLockfile-pathSetsthenameofthelockfileusedforRewriteMapsynchronization

RewriteLogfile-pathSetsthenameofthefileusedforloggingrewriteengineprocessing

RewriteLogLevelLevel 0Setstheverbosityofthelogfileusedbytherewriteengine

RewriteMapMapNameMapType:MapSourceDefinesamappingfunctionforkey-lookup

RewriteOptionsOptionsSetssomespecialoptionsfortherewriteengine

RewriteRulePatternSubstitutionDefinesrulesfortherewritingengine

RLimitCPUseconds|max[seconds|max]ApacheCPU

RLimitMEMbytes|max[bytes|max]Apache

RLimitNPROCnumber|max[number|max]Apache

SatisfyAny|All All

ScoreBoardFilefile-path logs/apache_status(coordinationdata)

Page 1542: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Scriptmethodcgi-scriptCGI

ScriptAliasURL-pathfile-path|directory-pathURLCGI

ScriptAliasMatchregexfile-path|directory-pathURLCGI

ScriptInterpreterSourceRegistry|Registry-Strict|Script

Script

CGIScriptLogfile-pathCGI

ScriptLogBufferbytes 1024PUTPOST

ScriptLogLengthbytes 10385760()

ScriptSockfile-path logs/cgisockCGI

SecureListen[IP-address:]portnumberCertificate-Name[MUTUAL]SSL

SendBufferSizebytes 0TCP()

ServerAdminemail-address|URL

ServerAliashostname[hostname]...

ServerLimitnumber

ServerNamefully-qualified-domain-name[:port]

Page 1543: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ServerPathURL-pathURL

ServerRootdirectory-path /usr/local/apache

ServerSignatureOn|Off|EMail Off

ServerTokensMajor|Minor|Min[imal]|Prod[uctOnly]|OS|Full

Full

"Server:"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 "-->"Stringthatendsanincludeelement

SSIErrorMsgmessage "[anerroroccurred+ErrormessagedisplayedwhenthereisanSSIerror

SSIStartTagtag "<!--#"Stringthatstartsanincludeelement

SSITimeFormatformatstring "%A,%d-%b-%Y%H:%M+

Page 1544: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ConfigurestheformatinwhichdatestringsaredisplayedSSIUndefinedEchostring "(none)"Stringdisplayedwhenanunsetvariableisechoed

SSLCACertificateFilefile-pathFileofconcatenatedPEM-encodedCACertificatesforClientAuth

SSLCACertificatePathdirectory-pathDirectoryofPEM-encodedCACertificatesforClientAuth

SSLCADNRequestFilefile-pathFileofconcatenatedPEM-encodedCACertificatesfordefiningacceptableCAnames

SSLCADNRequestPathdirectory-pathDirectoryofPEM-encodedCACertificatesfordefiningacceptableCAnames

SSLCARevocationFilefile-pathFileofconcatenatedPEM-encodedCACRLsforClientAuth

SSLCARevocationPathdirectory-pathDirectoryofPEM-encodedCACRLsforClientAuth

SSLCertificateChainFilefile-pathFileofPEM-encodedServerCACertificates

SSLCertificateFilefile-pathServerPEM-encodedX.509Certificatefile

SSLCertificateKeyFilefile-pathServerPEM-encodedPrivateKeyfile

SSLCipherSuitecipher-spec ALL:!ADH:RC4+RSA:+H+

CipherSuiteavailablefornegotiationinSSLhandshakeSSLCryptoDeviceengine builtinEnableuseofacryptographichardwareaccelerator

SSLEngineon|off|optional offSSLEngineOperationSwitch

SSLHonorCiperOrderflagOptiontoprefertheserver'scipherpreferenceorder

Page 1545: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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+

CipherSuiteavailablefornegotiationinSSLproxyhandshakeSSLProxyEngineon|off offSSLProxyEngineOperationSwitch

SSLProxyMachineCertificateFilefilenameFileofconcatenatedPEM-encodedclientcertificatesandkeystobeusedbytheproxy

SSLProxyMachineCertificatePathdirectoryDirectoryofPEM-encodedclientcertificatesandkeystobeusedbytheproxy

SSLProxyProtocol[+|-]protocol... allConfigureusableSSLprotocolflavorsforproxyusage

SSLProxyVerifylevel noneTypeofremoteserverCertificateverification

SSLProxyVerifyDepthnumber 1

Page 1546: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MaximumdepthofCACertificatesinRemoteServerCertificateverificationSSLRandomSeedcontextsource[bytes]PseudoRandomNumberGenerator(PRNG)seedingsource

SSLRequireexpressionAllowaccessonlywhenanarbitrarilycomplexbooleanexpressionistrue

SSLRequireSSLDenyaccesswhenSSLisnotusedfortheHTTPrequest

SSLSessionCachetype noneTypeoftheglobal/inter-processSSLSessionCache

SSLSessionCacheTimeoutseconds 300NumberofsecondsbeforeanSSLsessionexpiresintheSessionCache

SSLUserNamevarnameVariablenametodetermineusername

SSLVerifyClientlevel noneTypeofClientCertificateverification

SSLVerifyDepthnumber 1MaximumdepthofCACertificatesinClientCertificateverification

StartServersnumber

StartThreadsnumber

SuexecUserGroupUserGroupCGI

ThreadLimitnumber

ThreadsPerChildnumber

ThreadStackSizesize()

TimeOutseconds 300

Page 1547: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TraceEnable[on|off|extended] onTRACE

TransferLogfile|pipe

TypesConfigfile-path conf/mime.typesmime.types

UnsetEnvenv-variable[env-variable]...

UseCanonicalNameOn|Off|DNS Off

UseCanonicalPhysicalPortOn|Off Off

Userunix-userid #-1

UserDirdirectory-filename

VirtualDocumentRootinterpolated-directory|none

none

VirtualDocumentRootIPinterpolated-directory|none

none

IP<VirtualHostaddr[:port][addr[:port]]...>...</VirtualHost>IP

VirtualScriptAliasinterpolated-directory|none noneCGI

VirtualScriptAliasIPinterpolated-directory|none

none

IPCGIWin32DisableAcceptEx

Page 1548: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

accept()AcceptEx()XBitHackon|off|full offParseSSIdirectivesinfileswiththeexecutebitset

Page 1549: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

Page 1550: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 1551: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

“Apache2.0”Apache2.2[]kajaabiAjifeisuncjsDanielflytoseaforehead

LinuxFans.Orgsejishikong[]

LinuxSir.Orgbingzhou[]

chmpdf

Page 1556: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006121|

Page 1557: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

Page 1558: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

coreApacheHTTP

mpm_common(MPM)

beosBeOS(MPM)

eventworkerMPM

mpm_netwareNovellNetWare(MPM)

mpmt_os2OS/2(MPM)

preforkMPM

mpm_winntWindowsNT/2000/XP/2003MPM

workerMPMMPM

Page 1559: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

A|C|D|E|F|H|I|L|M|N|P|R|S|U|V

mod_actionsCGI

mod_aliasURL

mod_asisHTTP

mod_auth_basic

mod_auth_digestMD5()

mod_authn_alias

mod_authn_anon

mod_authn_dbdSQL

mod_authn_dbmDBM

mod_authn_default

mod_authn_file

mod_authnz_ldapLDAP

mod_authz_dbmDBM

Page 1560: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_authz_default

mod_authz_groupfile

mod_authz_hostIP

mod_authz_owner

mod_authz_user

mod_autoindex"ls""dir"

mod_cacheURI()

mod_cern_metaApacheCERNhttpd

mod_cgiMPM(prefork)CGI

mod_cgidMPM(worker)CGICGI

mod_charset_lite

mod_davApacheDAV

mod_dav_fsmod_dav

mod_dav_lockmod_dav

mod_dbd

Page 1561: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

SQL

mod_deflate

mod_dir""

mod_disk_cache

mod_dumpioI/O

mod_echo

mod_envApacheCGISSI

mod_exampleApacheAPI

mod_expiresHTTP" Expires:"" Cache-Control:"

mod_ext_filter

mod_file_cacheApache

mod_filter

mod_headersHTTP

mod_identRFC1413ident

mod_imagemap

Page 1562: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_include(SSI)

mod_infoApacheWeb

mod_isapiWindowsISAPI

mod_ldapLDAPLDAP

mod_log_config

mod_log_forensic""

mod_logio/HTTP

mod_mem_cache

mod_mime(/)(MIME///)

mod_mime_magicMIME

mod_negotiation

mod_nw_sslNetWareSSL

mod_proxyHTTP/1.1/

mod_proxy_ajpmod_proxyApacheJServProtocol

mod_proxy_balancer

Page 1563: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_proxy

mod_proxy_connectmod_proxyHTTP CONNECT

mod_proxy_ftpmod_proxyFTP

mod_proxy_httpmod_proxyHTTP

mod_rewriteURL

mod_setenvif

mod_soDSO

mod_spelingURL

mod_ssl(SSL)(TLS)

mod_statusWeb

mod_suexecwebCGISSI

mod_unique_id

mod_userdir("/~username")

mod_usertrackSession(Cookie)

mod_version

Page 1564: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

mod_vhost_alias

Page 1565: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |200617|

Page 1566: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FAQApache< http://httpd.apache.org/docs/2.2/faq/>

Apache1.3FAQ

Page 1567: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTPServer

Page 1568: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheApacheHTTPServerApacheApachelogo

ApacheApache(ASF)Apache ApacheSoftwareFoundationFAQ

ApacheHTTPServer(Apachehttpd)ApacheHTTP(Web)AboutApache

ApacheHTTPServerHTTP/1.1webHTTP/1.1(RFC2616)

ApacheAPI

Windows2003/XP/2000/NT/9xNetware5.xOS/2Unix

bug

ApacheApacheApacheHTTPServer70%WWW24bug

ApachelogoApache

Apacheweb'PoweredbyApache'Apache 'PoweredbyApache' ApachelogoApache

Page 1569: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

"......"

"......"Apache

Apache()/usr/local/apache2/logs/error_logErrorLog

FAQ!ApacheApache

ApachebugApachebugbug ( ) ""

Apache

FreenodeIRC#apache

bughttpd bug

dump backtrace()

60Apache

Apache

Page 1570: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 1571: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Invalidargument:core_output_filter:writingdatatothenetworkAcceptExfailedPrematureendofscriptheadersPermissiondenied

Invalidargument:core_output_filter:writingdatatothenetworkApachesendfileApache sendfile

sendfile

EnableSendfilesendfile EnableMMAP

AcceptExFailedwin32AcceptEx Win32DisableAcceptEx

PrematureendofscriptheadersCGI" InternalServerError" CGI

Permissiondeniederror_log" Permissiondenied"" Forbidden"ApacheHTTP UserGroup()( chmod+x

FedoraCoreLinuxSELinux" Permissiondenied"FedoraSELinuxFAQApacheSELinuxPolicyDocument

Page 1572: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2

|| |200616|

Page 1573: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTPServerVersion2.2

Page 1574: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

1.32.02.02.2Apache2.1/2.2Apache2.0ApacheLicense

Page 1575: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTP

ApacheApache

DirectoryLocationFiles

URL

(DSO)

Apache(MPM)ApacheApache

suEXEC

URL

Page 1576: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

IP

DNSApache

Page 1577: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

(//)

Page 1578: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheSSL/TLS

SSL/TLSSSL/TLSSSL/TLS...SSL/TLS

Page 1579: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

CGI(SSI).htaccess

Page 1580: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MicrosoftWindowsApacheMicrosoftWindowsApacheNovellNetWareApacheHPUXApacheEBCDIC

Page 1581: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTP

httpdabapachectlapxsconfiguredbmmanagehtcachecleanhtdbmhtdigesthtpasswdlogresolverotatelogssuexec

Page 1582: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 1583: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

ApacheApache

(Core)(MPM)beos(MPM)event(MPM)netware(MPM)os2(MPM)prefork(MPM)winnt(MPM)worker(MPM)

mod_actionsmod_aliasmod_asismod_auth_basicmod_auth_digestmod_authn_aliasmod_authn_anonmod_authn_dbdmod_authn_dbmmod_authn_defaultmod_authn_filemod_authnz_ldapmod_authz_dbmmod_authz_defaultmod_authz_groupfilemod_authz_hostmod_authz_ownermod_authz_usermod_autoindexmod_cache

Page 1584: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_cern_metamod_cgimod_cgidmod_charset_litemod_davmod_dav_fsmod_dav_lockmod_dbdmod_deflatemod_dirmod_disk_cachemod_dumpiomod_echomod_envmod_examplemod_expiresmod_ext_filtermod_file_cachemod_filtermod_headersmod_identmod_imagemapmod_includemod_infomod_isapimod_ldapmod_log_configmod_log_forensicmod_logiomod_mem_cachemod_mimemod_mime_magicmod_negotiationmod_nw_ssl

Page 1585: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mod_proxymod_proxy_ajpmod_proxy_balancermod_proxy_connectmod_proxy_ftpmod_proxy_httpmod_rewritemod_setenvifmod_somod_spelingmod_sslmod_statusmod_suexecmod_unique_idmod_userdirmod_usertrackmod_versionmod_vhost_alias

Page 1586: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheAPIAPRApache2.0Apache2.0HookApache1.3Apache2.0Apache2.0Apache2.0

Page 1587: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Page 1588: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006114|

Page 1589: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheHTTP

Page 1590: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httpd

Apache

apachectl

ApacheHTTP

ab

ApacheHTTP

apxs

APache

configure

dbmmanage

DBM

htcacheclean

htdigest

htdbm

DBM

htpasswd

httxt2dbm

RewriteMapdbm

logresolve

ApacheIP

rotatelogs

Apache

suexec

Exec

Page 1591: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Page 1592: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS

|| |2006116|

Page 1593: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ApacheSSL/TLS

ApacheHTTPmod_ssl(SecureSocketsLayer)(TransportLayerSecurity) OpenSSLRalfS.Engelschall mod_ssl

Page 1594: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

...

Page 1595: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

mod_ssl

mod_ssl

Page 1596: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006118|

Page 1597: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache

" "( www.company1.comwww.company2.com)IP"IP"IP" "

ApacheIP1.1IP" "" IP"

Apache1.3

Page 1598: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

(IP)IP(IP)

()

Page 1599: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

<VirtualHost>

NameVirtualHost

ServerName

ServerAlias

ServerPath

Apache -S

/usr/local/apache2/bin/httpd-S

ApacheIP( httpd)

Page 1600: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1601: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

DeveloperDocumentationforApache2.0

ManyofthedocumentsontheseDeveloperpagesareliftedfromApache1.3'sdocumentation.WhiletheyareallbeingupdatedtoApache2.0,theyareindifferentstagesofprogress.Pleasebepatient,andpointoutanydiscrepanciesorerrorsonthedeveloper/[email protected].

Page 1602: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Topics

Apache1.3APINotesApache2.0HookFunctionsRequestProcessinginApache2.0HowfiltersworkinApache2.0ConvertingModulesfromApache1.3toApache2.0DebuggingMemoryAllocationinAPRDocumentingApache2.0Apache2.0ThreadSafetyIssues

Page 1603: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ExternalResources

ToolsprovidedbyIanHolsman:Apache2crossreferenceAutogeneratedApache2codedocumentation

ModuleDevelopmentTutorialsbyKevinO'DonnellIntegratingamoduleintotheApachebuildsystemHandlingconfigurationdirectives

SomenotesonApachemoduledevelopmentbyRyanBloomDeveloperarticlesatapachetutorinclude:

RequestProcessinginApacheConfigurationforModulesResourceManagementinApacheConnectionPoolinginApacheIntroductiontoBucketsandBrigades

Page 1604: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |200619|

Page 1605: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Apacheweb

ApacheHTTP2.2

Apache

Apache

Apacheweb

URL

mod_rewrite mod_rewriteURL

Apache

Page 1606: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006114|

Page 1607: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httxt2dbm-RewriteMapdbm

httxt2dbmRewriteMapdbm( dbm)

Page 1608: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

httxt2dbm[-v][-fDBM_TYPE]-iSOURCE_TXT-o

OUTPUT_DBM

Page 1609: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

-v

-f

DBM APRGDBMGDBMSDBMSDBMDBberkeleyDBNDBMNDBMdefault

-i

dbmkeyvalue

RewriteMap

-o

dbm

Page 1610: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

httxt2dbm-irewritemap.txt-orewritemap.dbm

httxt2dbm-fSDBM-irewritemap.txt-o

rewritemap.dbm

Page 1611: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006112|

Page 1612: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 1613: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MicrosoftWindows

ApacheWindowsApache2.0

MicrosoftWindowsApache

ApacheWindowsApache

MicrosoftWindowsApache

Page 1614: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

NovellNetWareNovellNetWare5.1Apache2.0

NovellNetWareApache

HP-UXHP-UXApache

HP-UXApache

EBCDICApacheHTTP1.3EBCDICASCII

ApacheHTTP2.0

TheApacheEBCDICPort

Page 1615: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

|| |2006114|

Page 1616: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

suexec-

suexecApacheHTTPCGI rootApache root

suexecrootsetuid root

suexec suexec)

Page 1617: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

suexec-V

Page 1618: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

-V

rootsuexec

Page 1619: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../

|| |200619|

Page 1620: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.../

Page 1621: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

.../

(Authentication)(Authorization)

CGICGI()webCGICGIApachewebCGICGI

CGI

.htaccess

.htaccess("")

See:.htaccess

SSIHTMLHTMLCGI

See:(SSI)

UserDirURL http://example.com/~username/" username" UserDir

See:(public_html)

Page 1622: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL

||< >|???|

Page 1623: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_rewrite

"Thegreatthingaboutmod_rewriteisitgivesyoualltheconfigurabilityandflexibilityofSendmail.Thedownsidetomod_rewriteisthatitgivesyoualltheconfigurabilityandflexibilityofSendmail."

--BrianBehlendorfApacheGroup

"Despitethetonsofexamplesanddocs,mod_rewriteisvoodoo.Damnedcoolvoodoo,butstillvoodoo."

[email protected]

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.

Page 1624: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Sodon'texpecttounderstandthisentiremoduleinjustoneday.

Page 1625: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

Documentation

mod_rewritereferencedocumentation

TechnicaldetailsPracticalsolutionstocommonproblemsPracticalsolutionstoadvancedproblemsGlossary

Page 1626: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL

||< >|???|

Page 1627: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URLRewritingGuide

Thisdocumentsupplementsthemod_rewritereferencedocumentation.ItdescribeshowonecanuseApache'smod_rewritetosolvetypicalURL-basedproblemswithwhichwebmastersarecommononyconfronted.WegivedetaileddescriptionsonhowtosolveeachproblembyconfiguringURLrewritingrulesets.

ATTENTION:Dependingonyourserverconfigurationitmaybenecessarytoslightlychangetheexamplesforyoursituation,e.g.addingthe[PT]flagwhenadditionallyusingmod_aliasmod_userdir,etc.Orrewritingarulesettofitin.htaccesscontextinsteadofper-servercontext.Alwaystrytounderstandwhataparticularrulesetreallydoesbeforeyouuseit.Thisavoidsmanyproblems.

Page 1628: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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]

Page 1629: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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]

Page 1630: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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/

Page 1631: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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]

Page 1632: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or
Page 1633: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

MoveHomedirstoDifferentWebserver

Description:Manywebmastershaveaskedforasolutiontothefollowingsituation:Theywantedtoredirectjustallhomedirsonawebservertoanotherwebserver.Theyusuallyneedsuchthingswhenestablishinganewerwebserverwhichwillreplacetheoldoneovertime.

Solution:Thesolutionistrivialwithmod_rewrite.Ontheoldwebserverwejustredirectall/~user/anypathURLstohttp://newserver/~user/anypath.

RewriteEngineon

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

Page 1634: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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]

Page 1635: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 1636: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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\.[^.]+

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

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

Page 1637: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RedirectHomedirsForForeigners

Description:WewanttoredirecthomedirURLstoanotherwebserverwww.somewhere.comwhentherequestinguserdoesnotstayinthelocaldomainourdomain.com.Thisissometimesusedinvirtualhostcontexts.

Solution:Justarewritecondition:

RewriteEngineon

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

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

Page 1638: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RedirectingAnchors

Description:Bydefault,redirectingtoanHTMLanchordoesn'twork,becausemod_rewriteescapesthe#character,turningitinto%23.This,inturn,breakstheredirection.

Solution:Usethe[NE]flagontheRewriteRule.NEstandsforNoEscape.

Page 1639: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Time-DependentRewriting

Description:Whentricksliketime-dependentcontentshouldhappenalotofwebmastersstilluseCGIscriptswhichdoforinstanceredirectstospecializedpages.Howcanitbedoneviamod_rewrite?

Solution:TherearealotofvariablesnamedTIME_xxxforrewriteconditions.Inconjunctionwiththespeciallexicographiccomparisonpatterns<STRING,>STRING=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...

Page 1640: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 1641: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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]

Page 1642: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 1643: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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,wecanatleastrestrictthecaseswherethebrowsersendsaHTTPRefererheader.

Page 1644: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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]

Page 1645: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.Butnoticethatwhilesuchmapscanbeusedalsobyanaverageuser,onlythesystemadministrator

Page 1646: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

candefineit.

Page 1647: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL

||< >|???|

Page 1648: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

URLRewritingGuide-Advancedtopics

Thisdocumentsupplementsthemod_rewritereferencedocumentation.ItdescribeshowonecanuseApache'smod_rewritetosolvetypicalURL-basedproblemswithwhichwebmastersarecommononyconfronted.WegivedetaileddescriptionsonhowtosolveeachproblembyconfiguringURLrewritingrulesets.

ATTENTION:Dependingonyourserverconfigurationitmaybenecessarytoslightlychangetheexamplesforyoursituation,e.g.addingthe[PT]flagwhenadditionallyusingmod_aliasmod_userdir,etc.Orrewritingarulesettofitin.htaccesscontextinsteadofper-servercontext.Alwaystrytounderstandwhataparticularrulesetreallydoesbeforeyouuseit.Thisavoidsmanyproblems.

Page 1649: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

WebclusterthroughHomogeneousURLLayout

Description: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.Thefollowing

Page 1650: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

rulesetdoesthisforusbythehelpofthemapfiles(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\

Page 1651: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

StructuredHomedirs

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

Page 1652: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

FilesystemReorganization

Description:Thisreallyisahardcoreexample:akillerapplicationwhichheavilyusesper-directoryRewriteRulestogetasmoothlookandfeelontheWebwhileitsdatastructureisnevertouchedoradjusted.Background:net.swismyarchiveoffreelyavailableUnixsoftwarepackages,whichIstartedtocollectin1992.Itisbothmyhobbyandjobtotothis,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"meansthatIwantedtoofferaninterfacewhereyoucanbrowsedirectlythroughthearchivehierarchy.And"nice"meansthatIdidn'twantedtochangeanythinginsidethishierarchy-notevenbyputtingsomeCGI

Page 1653: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

scriptsatthetopofit.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

DATA/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

Page 1654: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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:

Page 1655: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

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

3. Noticethecatch-allpatterninthelastrule

Page 1656: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RedirectFailingURLsToOtherWebserver

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

Solution:Thefirstsolutionhasthebestperformancebutlessflexibility,andislesserrorsafe:

RewriteEngineon

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

RewriteRule^(.+)http://

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.

Page 1657: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ArchiveAccessMultiplexer

Description:DoyouknowthegreatCPAN(ComprehensivePerlArchiveNetwork)underhttp://www.perl.com/CPAN?ThisdoesaredirecttooneofseveralFTPserversaroundtheworldwhichcarryaCPANmirrorandisapproximatelynearthelocationoftherequestingclient.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:

##

##map.cxan--MultiplexingMapforCxAN

##

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

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

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

:

##EOF##

Page 1658: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

ContentHandling

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[

RewriteCond%{HTTP_USER_AGENT}^Lynx/.*[OR]

RewriteCond%{HTTP_USER_AGENT}^Mozilla/[12].*

RewriteRule^foo\.html$foo.20.html[

RewriteRule^foo\.html$foo.32.html[

DynamicMirrorDescription:

Assumetherearenicewebpagesonremotehostswewanttobringintoournamespace.ForFTPserverswewouldusethe

Page 1659: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

mirrorprogramwhichactuallymaintainsanexplicitup-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

Page 1660: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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).Howcanthisbedone?

Page 1661: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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/rotatedordereverytime.Thiswaytheclientsarespreadoverthevariousservers.Butnoticethatthisnotaperfectloadbalancingscheme,becauseDNSresolveinformationgetscachedbytheother

Page 1662: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

nameserversonthenet,soonceaclienthasresolvedwww.foo.comtoaparticularwwwN.foo.com,allsubsequentrequestsalsogotothisparticularnamewwwN.foo.com.Butthefinalresultisok,becausethetotalsumoftherequestsarereallyspreadoverthevariouswebservers.

2. DNSLoad-BalancingAsophisticatedDNS-basedmethodforload-balancingistousetheprogramlbnamedwhichcanbefoundathttp://www.stanford.edu/~schemers/docs/lbnamed/lbnamed.html.ItisaPerl5programinconjunctionwithauxilliarytoolswhichprovidesarealload-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:

Page 1663: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

#!/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-RobinThereisahardwaresolutionavailable,too.CiscohasabeastcalledLocalDirectorwhichdoesaloadbalancingattheTCP/IPlevel.Actuallythisissomesortofacircuitlevelgatewayinfrontofawebcluster.Ifyouhaveenoughmoneyandreallyneedasolutionwithhighperformance,usethisone.

Page 1664: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

NewMIME-type,NewServiceDescription:

OnthenettherearealotofniftyCGIprograms.Buttheirusageisusuallyboring,soalotofwebmasterdon'tusethem.EvenApache'sActionhandlerfeatureforMIME-typesisonlyappropriatewhentheCGIprogramsdon'tneedspecialURLs(actuallyPATH_INFOQUERY_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,

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-codeboththelocationoftheareathelocationoftheCGIinsidethehyperlink.Whenwehavetoreorganizethearea,wespendalotoftimechangingthevarioushyperlinks.

Page 1665: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.pagesshouldbedeliveredaspurestaticpages(readfromthefilesystemandjustpassedthrough),buttheyhavetobegenerateddynamicallybythewebserverifmissing.ThiswayyoucanhaveCGI-generatedpageswhicharestaticallyservedunlessone(oracronjob)removesthestaticcontents.Thenthecontentsgetsrefreshed.

Solution:Thisisdoneviathefollowingruleset:

RewriteCond%{REQUEST_FILENAME}!-s

Page 1666: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Herearequesttopage.htmlleadstoainternalrunofacorrespondingpage.cgiifpage.htmlisstillmissingorhasfilesizenull.Thetrickhereisthatpage.cgiisausualCGIscriptwhich(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

Page 1667: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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{

Page 1668: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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

Page 1669: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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:

<VirtualHost>featureofApacheisniceandworksgreat

Page 1670: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

whenyoujusthaveafewdozensvirtualhosts.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

Page 1671: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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}}]

:

Page 1672: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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-

Page 1673: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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_basic).

Solution:Weusealistofrewriteconditionstoexcludeallexceptourfriends:

Page 1674: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}!^[email protected]\.com$

RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}!^friend2

RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}!^friend3

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/

Page 1675: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

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

Page 1676: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>

||< >|???|

Page 1677: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apache2.0ThreadSafetyIssues

WhenusinganyofthethreadedmpmsinApache2.0itisimportantthateveryfunctioncalledfromApachebethreadsafe.Whenlinkingin3rdpartyextensionsitcanbedifficulttodeterminewhethertheresultingserverwillbethreadsafe.Casualtestinggenerallywon'ttellyouthiseitherasthreadsafetyproblemscanleadtosubtleraceconditonsthatmayonlyshowupincertainconditionsunderheavyload.

Page 1678: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.

Page 1679: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.

Page 1680: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Commonstandardtroublesomefunctions

Notonlydothingshavetobethreadsafe,buttheyalsohavetobereentrant.strtok()isanobviousone.Youcallitthefirsttimewithyourdelimiterwhichitthenremembersandoneachsubsequentcallitreturnsthenexttoken.Obviouslyifmultiplethreadsarecallingityouwillhaveaproblem.Mostsystemshaveareentrantversionofofthefunctioncalledstrtok_r()whereyoupassinanextraargumentwhichcontainsanallocatedchar*whichthefunctionwilluseinsteadofitsownstaticstorageformaintainingthetokenizingstate.IfyouareusingAPRyoucanuseapr_strtok().

crypt()isanotherfunctionthattendstonotbereentrant,soifyourunacrosscallstothatfunctioninalibrary,watchout.Onsomesystemsitisreentrantthough,soitisnotalwaysaproblem.Ifyoursystemhascrypt_r()chancesareyoushouldbeusingthat,orifpossiblesimplyavoidthewholemessbyusingmd5instead.

Page 1681: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Common3rdPartyLibraries

Thefollowingisalistofcommonlibrariesthatareusedby3rdpartyApachemodules.Youcanchecktoseeifyourmoduleisusingapotentiallyunsafelibrarybyusingtoolssuchasldd(1)nm(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)tolook

Page 1682: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

forindividualsymbolsinthemodule.

Page 1683: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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()gethostbyname()

arenotthread-safeonmostClibraryimplementations.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_errorImageMagick 5.2.2 Yes ImageMagickdocsclaimitisthreadsafesince

version5.2.2(seeChangelog).Imlib2 ?libjpeg v6b ?

Page 1684: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

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_rlibraryvarianttoensurethread-safety.OpenSSL 0.9.6g Yes RequiresproperusageofCRYPTO_num_locks

CRYPTO_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.

Page 1685: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL

||< >|???|

Page 1686: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_rewriteIntroduction

Thisdocumentsupplementsthemod_rewritereferencedocumentation.Itdescribesthebasicconceptsnecessaryforuseofmod_rewrite.Otherdocumentsgointogreaterdetail,butthisdocshouldhelpthebeginnergettheirfeetwet.

Page 1687: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

TheApachemodulemod_rewriteisaverypowerfulandsophisticatedmodulewhichprovidesawaytodoURLmanipulations.Withit,youcandonearlyalltypesofURLrewritingthatyoumayneed.Itis,however,somewhatcomplex,andmaybeintimidatingtothebeginner.Thereisalsoatendencytotreatrewriterulesasmagicincantation,usingthemwithoutactuallyunderstandingwhattheydo.

Thisdocumentattemptstogivesufficientbackgroundsothatwhatfollowsisunderstood,ratherthanjustcopiedblindly.

Page 1688: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RegularExpressions

mod_rewriteusesthePerlCompatibleRegularExpressionvocabulary.Inthisdocument,wedonotattempttoprovideadetailedreferencetoregularexpressions.Forthat,werecommendthePCREmanpages,thePerlregularexpressionmanpage,andMasteringRegularExpressions,byJeffreyFriedl.

Inthisdocument,weattempttoprovideenoughofaregexvocabularytogetyoustarted,withoutbeingoverwhelming,inthehopethatRewriteRuleswillbescientificformulae,ratherthanmagicalincantations.

RegexvocabularyThefollowingaretheminimalbuildingblocksyouwillneed,inordertowriteregularexpressionsandRewriteRules.

Character Meaning. Matchesanycharacter

RegexBack-ReferenceAvailabilityOneimportantthingherehastoberemembered:WheneveryouuseparenthesesinPatternorinoneoftheCondPattern,back-referencesareinternallycreatedwhichcanbeusedwiththestrings$N%N(seebelow).TheseareavailableforcreatingthestringsSubstitutionTestString.Figure2showstowhichlocationstheback-referencesaretransferredforexpansion.

Page 1689: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Figure2:Theback-referenceflowthrougharule.

Page 1690: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteRulebasics

BasicanatomyofaRewriteRule,withexhaustivelyannotatedsimpleexamples.

Page 1691: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RewriteFlags

DiscussionoftheflagstoRewriteRule,andwhenandwhyonemightusethem.

Page 1692: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Rewriteconditions

DiscussionofRewriteCond,looping,andotherrelatedconcepts.

Page 1693: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Rewritemaps

DiscussionofRewriteMap,includingsimple,butheavilyannotated,examples.

Page 1694: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

.htaccessfiles

Discussionofthedifferencesbetweenrewriterulesinhttpd.confandin.htaccessfiles.

Page 1695: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

EnvironmentVariables

Thismodulekeepstrackoftwoadditional(non-standard)CGI/SSIenvironmentvariablesnamedSCRIPT_URLSCRIPT_URI.ThesecontainthelogicalWeb-viewtothecurrentresource,whilethestandardCGI/SSIvariablesSCRIPT_NAMESCRIPT_FILENAMEcontainthephysicalSystem-view.

ThesevariablesholdtheURI/URL astheywereinitiallyrequested,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/

Page 1696: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL

||< >|???|

Page 1697: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

Apachemod_rewriteTechnicalDetails

Thisdocumentdiscussessomeofthetechnicaldetailsofmod_rewriteandURLmatching.

Page 1698: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

InternalProcessing

Theinternalprocessingofthismoduleisverycomplexbutneedstobeexplainedonceeventotheaverageusertoavoidcommonmistakesandtoletyouexploititsfullfunctionality.

Page 1699: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

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.htaccessfileslivein

Page 1700: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

thefilesystem,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!

Page 1701: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

RulesetProcessing

Nowwhenmod_rewriteistriggeredinthesetwoAPIphases,itreadstheconfiguredrulesetsfromitsconfigurationstructure(whichitselfwaseithercreatedonstartupforper-servercontextorduringthedirectorywalkoftheApachekernelforper-directorycontext).ThentheURLrewritingengineisstartedwiththecontainedruleset(oneormorerulestogetherwiththeirconditions).TheoperationoftheURLrewritingengineitselfisexactlythesameforbothconfigurationcontexts.Onlythefinalresultprocessingisdifferent.

Theorderofrulesintherulesetisimportantbecausetherewritingengineprocessestheminaspecial(andnotveryobvious)order.Theruleisthis:Therewritingengineloopsthroughtherulesetrulebyrule(RewriteRuledirectives)andwhenaparticularrulematchesitoptionallyloopsthroughexistingcorrespondingconditions(RewriteConddirectives).Forhistoricalreasonstheconditionsaregivenfirst,andsothecontrolflowisalittlebitlong-winded.SeeFigure1formoredetails.

Figure1:The

Page 1702: Apache HTTP Server Version 2 · whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or

||||

controlflowthroughtherewritingruleset

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.