apache http server version 2 · whether in tort (including negligence), contract, or otherwise,...
TRANSCRIPT
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200614|
ApacheHTTPServerVersion2.2[2006321]
Apache2.1/2.2Apache2.02.02.2Apache
(MPM)
(DSO)
URL
SSL/TLSCGISuexecURL
.../
CGI.htaccess(SSI)(public_html)
MicrosoftWindowsNovellNetWareEBCDICPort
||||
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200617|
1.32.0
Apache src/CHANGES
ApacheautoconflibtoolApache1.3APACIApache2.0(MPM)
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
Apache1.3mod_auth_digestApache1.3mod_mmap_staticmod_file_cachesrc
||||
Apache2.0APIApache1.3 Apache2.0
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200617|
2.02.2
Apache src/CHANGES
2.02.21.3 1.32.0
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
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"
mod_cache2.0mod_disk_cache2.0mod_mem_cache2.0mod_charset_lite2.0mod_dumpio2.0
||||
2.02.2
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200615|
Apache2.2
ApacheHTTPServer2.02.21.3 Apache2.0
/(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
/(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
httpd
-M -l mod_soDSO()
httxt2dbm
dbm RewriteMapdbm(map)
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
||||
API API
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |2006321|
Apache2.0
Apache1.32.0
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
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
||||
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
||< >|???|
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
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
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
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
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
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
||||
Unlessrequiredbyapplicablelaworagreedtoinwriting,software
distributedundertheLicenseisdistributedonan"ASIS"BASIS,
WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
SeetheLicenseforthespecificlanguagegoverningpermissionsand
limitationsundertheLicense.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200614|
ApacheUnixUnixWindows MicrosoftWindowsApache
Apache libtoolautoconf
(2.2.54→2.2.55)
$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
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/
ApacheApacheHTTPUNIXApache()INSTALL.bindist
tar PGP( PGP)
Apachehttpdtar
$gzip-dhttpd-NN.tar.gz
$tarxvfhttpd-NN.tar
cd
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
Apache
$make
PREFIX( --prefix)
$makeinstall
PREFIX/conf/ApacheHTTP
$viPREFIX/conf/httpd.conf
docs/manual/Apache http://httpd.apache.org/docs/2.2/
ApacheHTTP
$PREFIX/bin/apachectl-kstart
http://localhost/ DocumentRoot PREFIX/htdocs/
$PREFIX/bin/apachectl-kstop
||||
(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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200614|
Apache
WindowsNT/2000/XP/2003ApacheWindows95/98/MEApacheApache
Unix httpd httpd
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
Apache ErrorLog" UnabletobindtoPort..."
rootApacheweb
apachectl( rc.localrc.N)rootApache
apachectlSysV startrestartstop httpd apachectl
||||
httpdapachectlApache
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200616|
UnixApacheWindowsNT/2000/XP/2003 ApacheWindows9x/ME Apache
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
TERMapachectl-kstop
TERMstop
USR1apachectl-kgraceful
USR1graceful()
MPM StartServers StartServers
StartServers
mod_statusUSR1 () scoreboard
mod_status" G"
USR1 USR11015
Apache("") -t(httpd)root httpdroot( httpd)
HUPapachectl-krestart
HUPrestartTERM
mod_statusHUP
WINCHapachectl-kgraceful-stop
WINCHgraceful-stop() PidFile
GracefulShutdownTimeout TERM
"" TERM PidFile apachectlhttpd
graceful-stophttpdApache
LockfileScriptSockPIDCGI httpd
rotatelogs rotatelogs
||||
Apache1.2b9 ""
ScoreBoardFileScoreBoard"bind:Addressalreadyinuse"(HUP)"longlostchildcamehome!"( USR1)ScoreBoardScoreBoard
HTTP(KeepAlive)1.220
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200611|
Apache
mod_mime <IfDefine>
Include
TypesConfig
Apache httpd.conf -f IncludeApache
MIME TypesConfig mime.types
Apache"\"()
(argument)"#"
apachectlconfigtest -tApache
mod_so <IfModule>
LoadModule
Apache base DSO LoadModuleApache<IfModule>
-l
<Directory>
<DirectoryMatch>
<Files>
<FilesMatch>
<Location>
<LocationMatch>
<VirtualHost>
<Directory><DirectoryMatch><Files><FilesMatch><Location>
URL
Apache <VirtualHost>()
||||
.htaccess
AccessFileName
AllowOverride
Apache .htaccessAccessFileName .htaccess
.htaccess .htaccess
.htaccess AllowOverride.htaccess
.htaccess .htaccess
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200615|
()
URL() .htaccess
()
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
<IfVersion>=2.1>
#2.1.0
</IfVersion>
<IfDefine><IfModule><IfVersion>"!"
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>
<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
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
<VirtualHost>
<Proxy><ProxyMatch>mod_proxyURL cnn.com
<Proxyhttp://cnn.com/*>
Orderallow,deny
Denyfromall
</Proxy>
<Directory>
<DirectoryMatch><Files><FilesMatch><Location><LocationMatch>
AllowOverride<Directory>
OptionsFollowSymLinksSymLinksIfOwnerMatch
<Directory>.htaccessOptions<Files><FilesMatch>
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>
||||
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>
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200611|
m
od_cachemod_disk_cachemod_mem_cachemod_file_cache
htcachecleanApacheweb(proxy)
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
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)
(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"
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
(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
(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
(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
MMapStatic/usr/local/apache2/htdocs/index.html
CacheFileApache
MMapStaticApache
mod_mem_cachemod_mem_cacheHTTP MMap mod_mem_cache
#
CacheEnablemem/
#1MB
MCacheSize1024
(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"
||||
mod_disk_cache
Apache htcacheclean htcacheclean
htcachecleancron htcacheclean(G)cron
1:
mod_disk_cache htcacheclean""
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200616|
(core)
ServerName
ServerAdmin
ServerSignature
ServerTokens
UseCanonicalName
UseCanonicalPhysicalPort
ServerAdminServerTokens() ServerTokensHTTP
ServerNameUseCanonicalNameUseCanonicalPhysicalPort
URL"/"Apache"/"
CoreDumpDirectory
DocumentRoot
ErrorLog
LockFile
PidFile
ScoreBoardFile
ServerRoot
Apache(/) ServerRootroot
||||
LimitRequestBody
LimitRequestFields
LimitRequestFieldsize
LimitRequestLine
RLimitCPU
RLimitMEM
RLimitNPROC
ThreadStackSize
LimitRequest*Apache(DOS)
RLimit*ApacheCGISSIexec
ThreadStackSize
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200614|
WebApacheHTTP
ApacheApache(root)
(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
(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
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
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
SetEnvIfRequest_URI"^/robots\.txt$"dontlog
#
CustomLoglogs/access_logcommonenv=!dontlog
SetEnvIfAccept-Language"en"english
CustomLoglogs/english_logcommonenv=english
CustomLoglogs/non_english_logcommonenv=!english
100001MBApache
(graceful)
mvaccess_logaccess_log.old
mverror_logerror_log.old
apachectlgraceful
sleep600
gzipaccess_log.olderror_log.old
Apachehttpd" |"Apache("")
Apachehttpdroot
rotatelogs24
CustomLog"|/usr/local/apache/bin/rotatelogs
/var/log/access_log86400"common
cronolog
<VirtualHost>
CustomLogErrorLog<VirtualHost> <VirtualHost>
LogFormat"%v%l%u%t\"%r\"%>s%b"comonvhost
CustomLoglogs/access_logcomonvhost
%v split-logfile
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200617|
URL
ApacheURL
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
DocumentRoot
ApacheURL(URL) DocumentRoot
Apache DocumentRoot mod_vhost_aliasIP
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
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
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
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
URL
mod_rewriteURLIP(aliases) URL
||||
FileNotFound
URL URL
HTMLURLApache mod_speling"FileNotFound"
mod_spelingURLunixURL""URL
Apache"404"() ErrorDocument
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006110|
Apache
ApacheHTTPApacheApacheHTTP ApacheHTTPApache
WebApacheCGI
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)
(SSI)
ApacheSSISSI
SSICGI"execcmd"SSICGIhttpd.confApache
SSISSI
CGIsuexecSSI
.html.htmSSISSI.shtml
SSI Options IncludesNOEXECIncludes<--#includevirtual="..."--> ScriptAliasCGI
CGI
CGI
CGI
CGICGICGI/
CGI
Apachemod_php,mod_perl,mod_tcl,mod_pythonApache(User)Apache
.htaccess
<Directory/>
AllowOverrideNone
</Directory>
.htaccess
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
||||
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>
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200612|
(DSO)
ApacheHTTP httpd httpd(DSO)DSOApache(apxs)
DSO
mod_so LoadModule
ApacheDSOApachemod_so coreDSOApache --enable-module=sharedDSO mod_foo.soDSO httpd.conf
mod_soLoadModule
apxs(APacheeXtenSion)ApacheDSOApacheDSOApacheconfigure makeinstallApacheC apxsApache
DSO
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
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
||||
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()
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200612|
ApacheHTTP/1.1
mod_negotiation
(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)
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
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
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.
9. ASCII
3. ""HTTP Vary()
4. ()406HTMLHTTP Vary
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"
"fr"HTTP/1.1
(cookiesURL)2.0.47 mod_negotiationprefer-language
mod_negotiation
SetEnvIfCookie"language=(.+)"prefer-language=$1
Apache{encoding..}(RFC2295)RVSA/1.0(RFC2296)Accept-EncodingRVSA/1.0
( 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)
URL(representation)URLApacheHTTP/1.1ApacheHTTP/1.1
HTTP/1.0() CacheNegotiatedDocsHTTP/1.1
HTTP/1.1Apache Vary force-no-vary
||||
AlanJ.Flavell LanguageNegotiationNotesApache2.0
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200612|
Apache
"500ServerError"URL()
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:)
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
||||
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:"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200611|
(Binding)
Apache
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
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
||||
Listen(mainserver) <VirtualHost>
<VirtualHost> <VirtualHost>
<VirtualHost>
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200615|
Apache
ApacheHTTPApache
Apache2.0web(MPM)
Apache mpm_winntApache1.3POSIXWindowsApacheMPM
workereventMPM prefork
MPMApacheMPMMPM
MPM
MPMMPMUnixMPMApacheApache
configure --with-mpm=NAMEMPM NAMEMPM
./httpd-lMPMMPM
||||
MPM
MPMMPM
BeOS beos
Netware mpm_netware
OS/2 mpmt_os2
Unix prefork
Windows mpm_winnt
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200613|
Apache
ApacheHTTP (environmentvariable)CGI
ApacheCGI(SSI)shell
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
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
mod_ext_filterExtFilterDefine disableenv=enableenv=
URLRewriteCond %{ENV:...}TestStringmod_rewritemod_rewrite ENV:mod_rewrite
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
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
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200614|
Apache
Apache
(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)
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>
||||
ApacheAPI ApacheAPI
char*handler
invoke_handler r->handler"-""/"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200613|
(Filter)
Apache
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)
Apache
mod_include
mod_sslSSL(https)mod_deflate/mod_charset_lite
mod_ext_filter
Apache(byte-rangehandling)
modules.apache.org
HTMLXMLXSLTXIncludesXMLHTML
PHP
Apache2.1mod_filterHTMLJPEG(filterharness)(provider)(provider)
HTMLtext/htmlapplication/xhtml+xml
||||
()
AddInputFilter,AddOutputFilter,RemoveInputFilter,RemoveOutputFilter
mod_filter FilterChain,FilterDeclare,FilterProvider
AddOutputFilterByType
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200616|
suEXEC
suEXECApachewebCGISSICGISSIweb
CGISSI setuidrootsuEXEC
Apache
UNIX setuidsetgidsuEXEC
setuid/setgid
suEXECsuEXEC Apache
Apache suEXECsuEXECsuEXECsuEXECApachesuEXEC
suEXEC
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
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.
19.
suEXEC()()
20.
suEXEC
suEXECCGI/SSI
suEXEC
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"
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
suEXEC
Apache --sbindir("/usr/local/apache/sbin/suexec")suexecApachesuEXEC
[notice]suEXECmechanismenabled(wrapper:
/path/to/suexec)
setuidroot
ApachesuEXECApacheHUPUSR1
suEXEC suexecApache
suEXEC
CGIsuEXEC SuexecUserGroup mod_userdir
suEXECVirtualHostSuexecUserGroupUIDCGI<VirtualHost>UserGroup <VirtualHost>UID
mod_userdirsuEXECUIDCGICGI --with-
suexec-userdir
suEXEC
suEXEC --with-suexec-logfile
||||
Jabberwock
Apache
suEXEC"bugs"
suEXEC
suEXEC4ApachesuEXEC()
suEXECPATH
suEXEC
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006321|
Apache2.0webApache2.0
Apache1.32.0Apache2.0httpd
webweb"""""" MaxClients
topApache
CPU""
TCP
sendfile()(LinuxLinux2.4Solaris8)sendfileApache2CPU
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
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"
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
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
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
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)
{
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)){
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
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){
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
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()
/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
||||
/65:close(9)=0
/65:close(10)=0
/65:lwp_park(0x00000000,0)(sleeping...)
/67:accept(3,0x001FEB74,0x001FEB94,1)(sleeping...)
(MPM) accept()()
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006321|
mod_rewrite
Apachemod_rewriteURLURL mod_rewriteApachemod_rewrite mod_rewrite
URL
mod_aliasmod_userdir[PT].htaccess
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/
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]
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}
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/
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"
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()
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]
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
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\
[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:"""
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
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
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
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
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
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
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
:
...
:
##
##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
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]
#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/
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
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
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"<b>ERROR</b>:Nofilegiven\n";
exit(0);
}
if(!-f$QS_f){
print"HTTP/1.0200OK\n";
print"Content-type:text/html\n\n";
print"<b>ERROR</b>:File$QS_fnotfound\n";
exit(0);
}
subprint_http_headers_multipart_begin{
print"HTTP/1.0200OK\n";
$bound="ThisRandomString12345";
print"Content-type:multipart/x-mixed-replace;boundary=$bound\n";
&print_http_headers_multipart_next;
}
subprint_http_headers_multipart_next{
print"\n--$bound\n";
}
subprint_http_headers_multipart_end{
print"\n--$bound--\n";
}
subdisplayhtml{
local($buffer)=@_;
$len=length($buffer);
print"Content-type:text/html\n";
print"Content-length:$len\n\n";
print$buffer;
}
subreadfile{
local($file)=@_;
local(*FP,$size,$buffer,$bytes);
($x,$x,$x,$x,$x,$x,$x,$size)=stat($file);
$size=sprintf("%d",$size);
open(FP,"<$file");
$bytes=sysread(FP,$buffer,$size);
close(FP);
return$buffer;
}
$buffer=&readfile($QS_f);
&print_http_headers_multipart_begin;
&displayhtml($buffer);
submystat{
local($file)=$_[0];
local($time);
($x,$x,$x,$x,$x,$x,$x,$x,$x,$mtime)=stat($file);
return$mtime;
}
$mtimeL=&mystat($QS_f);
$mtime=$mtime;
for($n=0;$n<$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##
: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
#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}}]
:
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]
:
:
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
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
||||
: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/...
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006118|
IP
IPIPIPHTTPIP
DNSIPApacheHTTPIPIPIP
"Host"HTTP/1.1HTTP/1.0SSLSSLIP
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
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>
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006118|
IP
" IP" IPIP("IP""ifconfig")
Apache
apache httpd
web User,Group,Listen,ServerRootIP Listen""( httpdN-1)
httpd
httpd ListenIP()
Listenwww.smallco.com:80
IP( DNSApache)
||||
httpd VirtualHostServerAdmin,ServerName,DocumentRoot,ErrorLog,TransferLog,CustomLog
<VirtualHostwww.smallco.com>
DocumentRoot/groups/smallco/www
ServerNamewww.smallco.com
ErrorLog/groups/smallco/logs/error_log
TransferLog/groups/smallco/logs/access_log
</VirtualHost>
<VirtualHostwww.baygroup.org>
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>
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006118|
Apache
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
()
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
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
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
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>
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
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"
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)
RewriteCond%{REQUEST_URI}^/cgi-bin/
RewriteRule^/(.*)$/www/hosts/${lowercase:%
{SERVER_NAME}}/cgi-bin/$1[T=application/x-httpd-
cgi]
#ok
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/
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006117|
IPweb
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
NameVirtualHost172.20.30.40
<VirtualHost172.20.30.40>
#...
IP" *"ISPIP" *"IPIP
IP
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
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
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>
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)
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>
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>
<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>
" _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_"
80" _default_"
<VirtualHost_default_:80>
DocumentRoot/www/default
...
</VirtualHost>
80
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)()
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
||||
" Host:"
" Host:" http://www.sub2.domain.tld/sub1/sub1-vhost
RewriteRule" Host:"URLURL
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006117|
Apache1.3Apache NameVirtualHost1.3
<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>
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)
ServerName VirtualHost
" _default_" ServerName
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
IPIPIP NameVirtualHost
IPServerAliasServerPathIP" _default_" NameVirtualHost
" Host:"ApacheServerPathServerPath(" Host:")IPIP" _default_" " _default_"( Listen)(" _default_:*")" NameVirtualHost*"IP(" _default_")IP(" _default_")() NameVirtualHost" Host:" " _default_"VirtualHostDNSDNSServerNameDNS
||||
DNS
VirtualHost()NameVirtualHostVirtualHost
ServerPathsServerPaths""("ServerPath/abc/def""ServerPath/abc")
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006117|
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
||||
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 "
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200612|
DNSApache
ApacheDNSApacheDNS()()()
<VirtualHostwww.abc.dom>
DocumentRoot/www/abc
</VirtualHost>
Apache ServerNameIPIPApacheDNS www.abc.dom
DNS (Apache1.2)
www.abc.domIP10.0.0.1
<VirtualHost10.0.0.1>
DocumentRoot/www/abc
</VirtualHost>
ApacheDNSServerName(Apache1.2)IPApacheURLURL
<VirtualHost10.0.0.1>
ServerNamewww.abc.dom
DocumentRoot/www/abc
</VirtualHost>
()Apache1.2DNSDNS abc.dom
DNS www.abc.dom1.2Apache
<VirtualHostwww.abc.dom>
DocumentRoot/www/abc
</VirtualHost>
<VirtualHostwww.def.dom>
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
""
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
VirtualHostIPListenIPServerName
<VirtualHost_default_:*>
||||
DNSApache1.2DNSInternetIP
DNSDNS(FTPTCP""DNS)
IPDNS
HTTP/1.1HostIPwebDNS19973web
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS
|| |2006116|
SSL/TLS
--A.Tanenbaum,"IntroductiontoComputerNetworks"
WebHTTPApacheSSL mod_ssl
IntroducingSSLandCertificatesusingSSLeayFrederickJ.HirschOpenGroupResearchInstitute1997 WebSecurity:AMatterofTrust,WorldWideWebJournal,Volume2,Issue3,Summer1997 FrederickHirsch() RalfS.Engelschall(mod_ssl)
SSL()([ AC96)
Alice
Alice
()()
Alice()
AliceAlice
Alice
AliceAlice
()
()Alice
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
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
Alice""
CA""--
ThawteVeriSign
InternetIntranet
([CertificateRevocationListsCRL])AliceAlice()
(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
SSLSSL()
Figure1:SimplifiedSSLHandshakeSequence
1.
2.
3.
4.
SSL3.031
(MessageAuthenticationCode[MAC])
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)
SSLHandshakeProtocolSSLChangeCipherSpecProtocolSSLAlertProtocolSSL
SSLRecordProtocol Figure2
Figure2:SSLProtocolStack
SSLNull
SSL Figure3SSL(SSL)
Figure3:SSLRecordProtocol
HTTPSSLHTTPHTTPHTTPSSL(HTTPS)URL httpshttp(443) mod_sslApache...
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",
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS
|| |2006116|
SSL/TLS
PC--
SSLmod_sslApacheSSLBenLauriemod_ssl)RedHat SecureWebServer(mod_ssl)CovalentRavenSSLModule(mod_ssl)C2Net Stronghold(Stringhold2.xSiouxStronghold3.xmod_ssl)
mod_sslmod_ssl
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
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 -
SSLProxyMachineCertFilefile -SSLProxyCACertificatePath
dir-
SSLProxyCACertificateFile
file-
SSLProxyVerifyDepthnumber -SSLProxyCipherListspec -
" 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
SSL_SERVER_IOU SSL_SERVER_I_DN_OU
SSL_SERVER_IC SSL_SERVER_I_DN_C
SSL_SERVER_ISP SSL_SERVER_I_DN_SP
SSL_SERVER_IL SSL_SERVER_I_DN_L
SSL_CLIENT_CERTIFICATE SSL_CLIENT_CERT
SSL_CLIENT_CERT_START SSL_CLIENT_V_START
SSL_CLIENT_CERT_END SSL_CLIENT_V_END
SSL_CLIENT_CERT_SERIAL SSL_CLIENT_M_SERIAL
SSL_CLIENT_SIGNATURE_ALGORITHM SSL_CLIENT_A_SIG
SSL_CLIENT_DN SSL_CLIENT_S_DN
SSL_CLIENT_CN SSL_CLIENT_S_DN_CN
SSL_CLIENT_EMAIL SSL_CLIENT_S_DN_Email
SSL_CLIENT_O SSL_CLIENT_S_DN_O
SSL_CLIENT_OU SSL_CLIENT_S_DN_OU
SSL_CLIENT_C SSL_CLIENT_S_DN_C
SSL_CLIENT_SP SSL_CLIENT_S_DN_SP
SSL_CLIENT_L SSL_CLIENT_S_DN_L
SSL_CLIENT_IDN SSL_CLIENT_I_DN
SSL_CLIENT_ICN SSL_CLIENT_I_DN_CN
SSL_CLIENT_IEMAIL SSL_CLIENT_I_DN_Email
SSL_CLIENT_IO SSL_CLIENT_I_DN_O
SSL_CLIENT_IOU SSL_CLIENT_I_DN_OU
SSL_CLIENT_IC SSL_CLIENT_I_DN_C
SSL_CLIENT_ISP SSL_CLIENT_I_DN_SP
SSL_CLIENT_IL SSL_CLIENT_I_DN_L
SSL_EXPORT SSL_CIPHER_EXPORT
SSL_KEYSIZE SSL_CIPHER_ALGKEYSIZE
SSL_SECKEYSIZE SSL_CIPHER_USEKEYSIZE
SSL_SSLEAY_VERSION SSL_VERSION_LIBRARY
SSL_STRONG_CRYPTO - 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
||||
mod_sslApache(DSO)" %{name}c" 3
3:FunctionCall%...{version}c SSL%...{cipher}c SSL%...{subjectdn}c SubjectDistinguishedName%...{issuerdn}c IssuerDistinguishedName%...{errcode}c ()%...{errstr}c ()
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS
|| |2006116|
SSL/TLS...?
--
SSLHTTPApacheSSLweb
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>
#
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>
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
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
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]+$
||||
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>
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS
||< >|???|
SSL/TLSStrongEncryption:FAQ
Thewisemandoesn'tgivetherightanswers,heposestherightquestions.
--ClaudeLevi-Strauss
Thischapterisacollectionoffrequentlyaskedquestions(FAQ)andcorrespondinganswersfollowingthepopularUSENETtradition.MostofthesequestionsoccurredontheNewsgroupcomp.infosystems.www.servers.unixorthemod_sslSupportMailingListmodssl-users@modssl.org.Theyarecollectedatthisplacetoavoidansweringthesamequestionsoverandover.
Pleasereadthischapteratleastoncewheninstallingmod_ssloratleastsearchforyourproblemherebeforesubmittingaproblemreporttotheauthor.
AboutTheModule
Whatisthehistoryofmod_ssl?mod_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
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.
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.
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
$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).
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.
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.
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
3. Itisimportantthatyouareawarethatthisserver.keydoesnothaveanypassphrase.Toaddapassphrasetothekey,youshouldrunthefollowingcommand,andenter&verifythepassphraseasrequested.$opensslrsa-des3-inserver.key-out
server.key.new
$mvserver.key.newserver.key
Pleasebackuptheserver.keyfile,andthepassphraseyouentered,inasecurelocation.
HowdoIcreatearealSSLCertificate?Hereisastep-by-stepdescription:
1. MakesureOpenSSLisinstalledandinyourPATH.
2. CreateaRSAprivatekeyforyourApacheserver(willbeTriple-DESencryptedandPEMformatted):
$opensslgenrsa-des3-outserver.key1024
Pleasebackupthisserver.keyfileandthepass-phraseyouenteredinasecurelocation.YoucanseethedetailsofthisRSAprivatekeybyusingthecommand:
$opensslrsa-noout-text-inserver.key
Ifnecessary,youcanalsocreateadecryptedPEMversion(notrecommended)ofthisRSAprivatekeywith:
$opensslrsa-inserver.key-out
server.key.unsecure
3. CreateaCertificateSigningRequest(CSR)withtheserverRSAprivatekey(outputwillbePEMformatted):
$opensslreq-new-keyserver.key-out
server.csr
MakesureyouentertheFQDN("FullyQualifiedDomainName")oftheserverwhenOpenSSLpromptsyouforthe"CommonName",i.e.whenyougenerateaCSRforawebsitewhichwillbelateraccessedviahttps://www.foo.dom/,enter"www.foo.dom"here.YoucanseethedetailsofthisCSRbyusing
$opensslreq-noout-text-inserver.csr
4. YounowhavetosendthisCertificateSigningRequest(CSR)toaCertifyingAuthority(CA)tobesigned.OncetheCSRhasbeensigned,youwillhavearealCertificate,whichcanbeusedbyApache.YoucanhaveaCSRsignedbyacommercialCA,oryoucancreateyourownCAtosignit.CommercialCAsusuallyaskyoutoposttheCSRintoawebform,payforthesigning,andthensendasignedCertificate,whichyoucanstoreinaserver.crtfile.FormoreinformationaboutcommercialCAsseethefollowinglocations:
1. Verisignhttp://digitalid.verisign.com/server/apacheNotice.htm
2. Thawtehttp://www.thawte.com/
3. CertiSignCertificadoraDigitalLtda.http://www.certisign.com.br
4. IKSGmbH
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
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-
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.
HowdoIverifythataprivatekeymatchesitsCertificate?Aprivatekeycontainsaseriesofnumbers.Twoofthesenumbersformthe"publickey",theothersarepartofthe"privatekey".The"publickey"bitsareincludedwhenyougenerateaCSR,andsubsequentlyformpartoftheassociatedCertificate.
TocheckthatthepublickeyinyourCertificatematchesthepublicportionofyourprivatekey,yousimplyneedtocomparethesenumbers.ToviewtheCertificateandthekeyrunthecommands:
$opensslx509-noout-text-inserver.crt
$opensslrsa-noout-text-inserver.key
The'modulus'andthe'publicexponent'portionsinthekeyandtheCertificatemustmatch.Asthepublicexponentisusually65537andit'sdifficulttovisuallycheckthatthelongmodulusnumbersarethesame,youcanusethefollowingapproach:
$opensslx509-noout-modulus-inserver.crt|
opensslmd5
$opensslrsa-noout-modulus-inserver.key|
opensslmd5
Thisleavesyouwithtworathershorternumberstocompare.Itis,intheory,possiblethatthesenumbersmaybethesame,withoutthemodulusnumbersbeingthesame,butthechancesofthisareoverwhelminglyremote.
ShouldyouwishtochecktowhichkeyorcertificateaparticularCSRbelongsyoucanperformthesamecalculationontheCSRasfollows:
$opensslreq-noout-modulus-inserver.csr|
opensslmd5
Whydoconnectionsfailwithan"alertbadcertificate"
error?ErrorssuchasOpenSSL:error:14094412:SSLroutines:SSL3_READ_BYTES:sslv3alertbad
certificateintheSSLlogfile,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:$
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.
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
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
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
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.
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
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
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?
Thisusuallyoccurswhenyouhavecreatedanewservercertificateforagivendomain,buthadpreviouslytoldyourbrowsertoalwaysaccepttheoldservercertificate.Onceyoucleartheentryfortheoldcertificatefromyourbrowser,everythingshouldbefine.Netscape'sSSLimplementationiscorrect,sowhenyouencounterI/OerrorswithNetscapeNavigatoritisusuallycausedbytheconfiguredcertificates.
mod_sslSupport
Whatinformationresourcesareavailableincaseofmod_sslproblems?Whatsupportcontactsareavailableincaseofmod_sslproblems?WhatinformationshouldIprovidewhenwritingabugreport?Ihadacoredump,canyouhelpme?HowdoIgetabacktrace,tohelpfindthereasonformycoredump?
Whatinformationresourcesareavailableincaseofmod_sslproblems?Thefollowinginformationresourcesareavailable.Incaseofproblemsyoushouldsearchherefirst.
AnswersintheUserManual'sF.A.Q.List(this)http://httpd.apache.org/docs/2.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
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
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.
||||
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../
|| |200618|
(Authentication)(Authorization)
( 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
""
( <Directory>)( .htaccess)
.htaccess AllowOverride
AllowOverride
AllowOverrideAuthConfig
/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)
"RestrictedFiles" "RestrictedFiles"
AuthUserFile htpasswdApachemod_authn_dbmAuthDBMUserFile dbmmanage Apache
Require Require
( 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
Basic
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
||||
mod_auth_basicmod_authz_host mod_authn_alias
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../
|| |200618|
CGI
mod_alias
mod_cgi
AddHandler
Options
ScriptAlias
CGI()webCGICGIApachewebCGICGI
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
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>
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.
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
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
?
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
CGI/
CGI
PerlCGI CPANCGI.pmCGI::Lite
CCGI CGIC http://www.boutell.com/cgic/
||||
CGIUsenet comp.infosystems.www.authoring.cgiCGIHTMLWritersGuild http://www.hwg.org/lists/hwg-servers/
CGICGI NCSACommonGatewayInterfaceRFCproject
CGICGI
CGIApachebugApache
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../
|| |200619|
HTML
mod_include
mod_cgi
mod_expires
Options
XBitHack
AddType
SetOutputFilter
BrowserMatchNoCase
(SSI)SSIHTMLSSI
SSISSI
SSI?
SSIHTMLHTMLCGI
SSISSI
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
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"-->
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
config
SSI
[anerroroccurredwhileprocessingthis
directive]
configerrmsg
<!--#configerrmsg="[Itappearsthatyoudon't
knowhowtouseSSI]"-->
configsizefmt bytesKbMb (abbrev)
CGISSI execSSIshell( /bin/shWin32DOSshell)
<pre>
<!--#execcmd="ls"-->
</pre>
Windows
<pre>
<!--#execcmd="dir"-->
</pre>
Windows dir"< dir>"
exec"" OptionsIncludesNOEXEC exec
SSI
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-->
<!--#endif-->
test_condition""() mod_include
BrowserMatchNoCasemacintoshMac
BrowserMatchNoCaseMSIEInternetExplorer
MacintoshInternetExplorer"Mac""InternetExplorer"
SSI
<!--#ifexpr="${Mac}&&${InternetExplorer}"-->
Apologetictextgoeshere
<!--#else-->
CoolJavaScriptcodegoeshere
<!--#endif-->
MacIEMacIEJavaScript
()Apache SetEnvIfCGI
||||
SSICGI
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../
|| |200618|
.htaccess
.htaccess
.htaccess
core
mod_authn_file
mod_authz_groupfile
mod_cgi
mod_include
mod_mime
AccessFileName
AllowOverride
Options
AddHandler
SetHandler
AuthType
AuthName
AuthUserFile
AuthGroupFile
Require
.htaccess("")
.htaccess AccessFileName .config
AccessFileName.config
.htaccess AllowOverride.htaccess .htaccess
AllowOverride
AddDefaultCharset.htaccess("") FileInfo.htaccess AllowOverrideFileInfo
serverconfig,virtualhost,directory,.htaccessFileInfo
.htaccess""".htaccess"
().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>
AddTypetext/example.exm
</Directory>
Apache
AllowOverridenone.htaccess
AllowOverrideNone
.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>
.htaccess <Directory> .htaccess
.htaccess
.htaccess
.htaccess
AuthTypeBasic
AuthName"PasswordRequired"
AuthUserFile/www/passwords/password.file
AuthGroupFile/www/passwords/group.file
RequireGroupadmins
AllowOverrideAuthConfig
(SSI)
.htaccess(SSI) .htaccess
Options+Includes
AddTypetext/htmlshtml
AddHandlerserver-parsedshtml
AllowOverrideOptions AllowOverrideFileInfo
SSI
CGI
.htaccessCGI
Options+ExecCGI
AddHandlercgi-scriptcgipl
CGI
Options+ExecCGI
SetHandlercgi-script
AllowOverrideOptions AllowOverrideFileInfo
CGI CGI
||||
.htaccess
AllowOverride AllowOverrideNone .htaccess
AllowOverrideNone
Apache .htaccess
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../
|| |200619|
UserDirURL http://example.com/~username/" username" UserDir
mod_userdir UserDir
DirectoryMatch
AllowOverride
UserDir
UserDir
UserDirpublic_html
URLhttp://example.com/~rbowen/file.html/home/rbowen/public_html/file.html
UserDir/var/html
URLhttp://example.com/~rbowen/file.html/var/html/rbowen/file.html
(*)
UserDir/var/www/*/docs
URLhttp://example.com/~rbowen/file.html/var/www/rbowen/docs/file.html
UserDir
UserDirenabled
UserDirdisabledrootjrofish
disabled
UserDirdisabled
UserDirenabledrbowenkrietz
UserDir
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
||||
.htaccess AllowOverride .htaccess
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006112|
MicrosoftWindowsApache
MicrosoftWindowsApache2.0bug bug
ApacheWindowsApache(bugs) WindowsApache
Windows
WindowsNT:NTMicrosoftWindowsWindowsNT,Windows2000,WindowsXP,Windows.NETServer2003Windows9x:MicrosoftWindowsWindows95,Windows98,WindowsME
Apache2.0WindowsNTx86IntelAMDApacheWindows9x
TCP/IPWindows95"Winsock2""Winsock2"forWindows95
NT4.0ServicePack6ServicePack4TCP/IPWinsockServicePack
ApacheforWindows
Apachehttp://httpd.apache.org/download.cgialphabetawebftp
.msiApacheforWindowsMicrosoftInstallerApache
.zipMicrosoftVisualC++(VisualStudio)
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
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
Windows9x
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
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)
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
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
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
"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
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006112|
MicrosoftWindowsApache
Apache MicrosoftWindowsApache
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
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
Apache cd
ApachemakeMakefile.winWindowsNTApache release
debug
nmake/fMakefile.win_apacher
nmake/fMakefile.win_apached
Apachebugs
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
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
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
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
UsingApacheWithNovellNetWare
Thisdocumentexplainshowtoinstall,configureandrunApache2.0underNovellNetWare6.0andabove.Ifyoufindanybugs,orwishtocontributeinotherways,pleaseuseourbugreportingpage.
Thebugreportingpageanddev-httpdmailinglistarenotprovidedtoanswerquestionsaboutconfigurationorrunningApache.Beforeyousubmitabugreportorrequest,firstconsultthisdocument,theFrequentlyAskedQuestionspageandtheotherrelevantdocumentationtopics.Ifyoustillhaveaquestionorproblem,postittothenovell.devsup.webservernewsgroup,wheremanyApacheusersaremorethanwillingtoanswernewandobscurequestionsaboutusingApacheonNetWare.
MostofthisdocumentassumesthatyouareinstallingApachefromabinarydistribution.IfyouwanttocompileApacheyourself(possiblytohelpwithdevelopment,ortotrackdownbugs),seethesectiononCompilingApacheforNetWarebelow.
Requirements
Apache2.0isdesignedtorunonNetWare6.0servicepack3andabove.IfyouarerunningaservicepacklessthanSP3,youmustinstallthelatestNetWareLibrariesforC(LibC).
NetWareservicepacksareavailablehere.
Apache2.0forNetWarecanalsoberuninaNetWare5.1environmentaslongasthelatestservicepackorthelatestversionoftheNetWareLibrariesforC(LibC)hasbeeninstalled.WARNING:Apache2.0forNetWarehasnotbeentargetedforortestedinthisenvironment.
DownloadingApacheforNetWare
InformationonthelatestversionofApachecanbefoundontheApachewebserverathttp://www.apache.org/.Thiswilllistthecurrentrelease,anymorerecentalphaorbeta-testreleases,togetherwithdetailsofmirrorwebandanonymousftpsites.BinarybuildsofthelatestreleasesofApache2.0forNetWarecanbedownloadedfromhere.
InstallingApacheforNetWare
ThereisnoApacheinstallprogramforNetWarecurrently.IfyouarebuildingApache2.0forNetWarefromsource,youwillneedtocopythefilesovertotheservermanually.
FollowthesestepstoinstallApacheonNetWarefromthebinarydownload(assumingyouwillinstalltosys:/apache2):
UnzipthebinarydownloadfiletotherootoftheSYS:volume(maybeinstalledtoanyvolume)Editthehttpd.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
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).
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:
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
keywordAPACHE2.
RESTARTInstructsApachetoterminateallrunningworkerthreadsastheybecomeidle,rereadtheconfigurationfileandrestarteachworkerthreadbasedonthenewconfiguration.
VERSIONDisplaysversioninformationaboutthecurrentlyrunninginstanceofApache.
MODULESDisplaysalistofloadedmodulesbothbuilt-inandexternal.
DIRECTIVESDisplaysalistofallavailabledirectives.
SETTINGSEnablesordisablesthethreadstatusdisplayontheconsole.Whenenabled,thestateofeachrunningthreadsisdisplayedontheApacheconsolescreen.
SHUTDOWNTerminatestherunninginstanceoftheApachewebserver.
HELPDescribeseachoftheruntimedirectives.
BydefaultthesedirectivesareissuedagainsttheinstanceofApacherunningintheOSaddressspace.Toissueadirectiveagainstaspecificinstancerunninginaprotectedaddressspace,includethe-pparameteralongwiththenameoftheaddressspace.Formoreinformationtype"apache2Help"onthecommandline.
ConfiguringApacheforNetWare
Apacheisconfiguredbyreadingconfigurationfilesusuallystoredintheconfdirectory.ThesearethesameasfilesusedtoconfiguretheUnixversion,butthereareafewdifferentdirectivesforApacheonNetWare.SeetheApachedocumentationforalltheavailabledirectives.
ThemaindifferencesinApacheforNetWareare:
BecauseApacheforNetWareismultithreaded,itdoesnotuseaseparateprocessforeachrequest,asApachedoesonsomeUniximplementations.Insteadthereareonlythreadsrunning:aparentthread,andmultiplechildorworkerthreadswhichhandletherequests.
Thereforethe"process"-managementdirectivesaredifferent:
MaxRequestsPerChild-LiketheUnixdirective,thiscontrolshowmanyrequestsaworkerthreadwillservebeforeexiting.Therecommendeddefault,MaxRequestsPerChild0,causesthethreadtocontinueservicingrequestindefinitely.ItisrecommendedonNetWare,unlessthereissomespecificreason,thatthisdirectivealwaysremainsetto0.
StartThreads-Thisdirectivetellstheserverhowmanythreadsitshouldstartinitially.TherecommendeddefaultisStartThreads50.
MinSpareThreads-Thisdirectiveinstructstheservertospawnadditionalworkerthreadsifthenumberofidlethreadseverfallsbelowthisvalue.TherecommendeddefaultisMinSpareThreads10.
MaxSpareThreads-Thisdirectiveinstructstheservertobeginterminatingworkerthreadsifthenumberofidlethreadsever
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.
NWSSLTrustedCerts-Addstrustedcertificatesthatareusedtocreatesecureconnectionstoproxiedservers.
NWSSLUpgradeable-Allowaconnectioncreatedonthespecifiedaddress/porttobeupgradedtoanSSLconnection.
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:
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
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
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:
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
||||
Netware/buildnetware-libc
BeforebuildingApache,settheenvironmentvariableOSSLSDKtothefullpathtotherootoftheopensslsourcecodedirectory.
SetOSSLSDK=d:\openssl-0.9.7x
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
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
||||
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
TheApacheEBCDICPort
Warning:Thisdocumenthasnotbeenupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.
OverviewoftheApacheEBCDICPort
Version1.3oftheApacheHTTPServeristhefirstversionwhichincludesaporttoa(non-ASCII)mainframemachinewhichusestheEBCDICcharactersetasitsnativecodeset.
(ItistheSIEMENSfamilyofmainframesrunningtheBS2000/OSDoperatingsystem.ThismainframeOSnowadaysfeaturesaSVR4-derivedPOSIXsubsystem).
Theportwasstartedinitiallyto
provethefeasibilityofportingtheApacheHTTPservertothisplatformfinda"worthyandcapable"successorforthevenerableCERN-3.0daemon(whichwasportedacoupleofyearsago),andtoprovethatApache'spreforkingprocessmodelcanonthisplatformeasilyoutperformtheaccept-fork-servemodelusedbyCERNbyafactorof5ormore.
Thisdocumentservesasarationaletodescribesomeofthedesigndecisionsoftheporttothismachine.
DesignGoals
OneobjectiveoftheEBCDICportwastomaintainenoughbackwardscompatibilitywiththe(EBCDIC)CERNservertomakethetransitiontothenewserverattractiveandeasy.ThisrequiredtheadditionofaconfigurablemethodtodefinewhetheraHTMLdocumentwasstoredinASCII(theonlyformatacceptedbytheoldserver)orinEBCDIC(thenativedocumentformatinthePOSIXsubsystem,andthereforetheonlyrealisticformatinwhichtheotherPOSIXtoolslikegrepsedcouldoperateonthedocuments).Thecurrentsolutiontothisisa"pseudo-MIME-format"whichisinterceptedandinterpretedbytheApacheserver(seebelow).Futureversionsmightsolvetheproblembydefiningan"ebcdic-handler"foralldocumentswhichmustbeconverted.
TechnicalSolution
SinceallApacheinputandoutputisbasedupontheBUFFdatatypeanditsmethods,theeasiestsolutionwastoaddtheconversiontotheBUFFhandlingroutines.Theconversionmustbesettableatanytime,soaBUFFflagwasaddedwhichdefineswhetheraBUFFobjecthascurrentlyenabledconversionornot.ThisflagismodifiedatseveralpointsintheHTTPprotocol:
setbeforearequestisreceived(becausetherequestandtherequestheaderlinesarealwaysinASCIIformat)set/unsetwhentherequestbodyisreceived-dependingonthecontenttypeoftherequestbody(becausetherequestbodymaycontainASCIItextorabinaryfile)setbeforeareplyheaderissent(becausetheresponseheaderlinesarealwaysinASCIIformat)set/unsetwhentheresponsebodyissent-dependingonthecontenttypeoftheresponsebody(becausetheresponsebodymaycontaintextorabinaryfile)
PortingNotes
1. Therelevantchangesinthesourceare#ifdef'edintotwocategories:
#ifdefCHARSET_EBCDIC
CodewhichisneededforanyEBCDICbasedmachine.Thisincludescharactertranslations,differencesincontiguityofthetwocharactersets,flagswhichindicatewhichpartoftheHTTPprotocolhastobeconvertedandwhichpartdoesn'tetc.
#ifdef_OSD_POSIX
CodewhichisneededfortheSIEMENSBS2000/OSDmainframeplatformonly.ThisdealswithincludefiledifferencesandsocketimplementationtopicswhichareonlyrequiredontheBS2000/OSDplatform.
2. ThepossibilitytotranslatebetweenASCIIandEBCDICatthesocketlevel(onBS2000POSIX,thereisasocketoptionwhichsupportsthis)wasintentionallynotchosen,becausethebytestreamattheHTTPprotocollevelconsistsofamixtureofprotocolrelatedstringsandnon-protocolrelatedrawfiledata.HTTPprotocolstringsarealwaysencodedinASCII(theGETrequest,anyHeader:lines,thechunkinginformationetc.)whereasthefiletransferparts(i.e.,GIFimages,CGIoutputetc.)shouldusuallybejust"passedthrough"bytheserver.Thisseparationbetween"protocolstring"and"rawdata"isreflectedintheservercodebyfunctionslikebgets()rvputs()forstrings,andfunctionslikebwrite()forbinarydata.Aglobaltranslationofeverythingwouldthereforebeinadequate.
(Inthecaseoftextfilesofcourse,provisionsmustbemadesothatEBCDICdocumentsarealwaysservedinASCII)
3. Thisportthereforefeaturesabuilt-inprotocollevelconversionfor
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:
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.
DocumentStorageNotes
BinaryFilesAllfileswithaContent-Type:whichdoesnotstartwithtext/areregardedasbinaryfilesbytheserverandarenotsubjecttoanyconversion.ExamplesforbinaryfilesareGIFimages,gzip-compressedfilesandthelike.
WhenexchangingbinaryfilesbetweenthemainframehostandaUnixmachineorWindowsPC,besuretousetheftp"binary"(TYPEI)command,orusethercp-bcommandfromthemainframehost(the-bswitchisnotsupportedinunixrcp's).
TextDocumentsThedefaultassumptionoftheserveristhatTextFiles(i.e.,allfileswhoseContent-Type:startswithtext/)arestoredinthenativecharactersetofthehost,EBCDIC.
ServerSideIncludedDocumentsSSIdocumentsmustcurrentlybestoredinEBCDIConly.NoprovisionismadetoconvertitfromASCIIbeforeprocessing.
ApacheModules'Status
Module Status Notescore +mod_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 +
mod_proxy +mod_rewrite + untestedmod_setenvif +mod_speling +mod_status +mod_unique_id +mod_userdir +mod_usertrack ? untested
||||
ThirdPartyModules'Status
Module Status Notesmod_jserv - JAVAstillbeingported.mod_php3 + mod_php3runsfine,withLDAPandGDand
FreeTypelibraries.mod_put ? untestedmod_session - untested
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006114|
httpd-Apache
httpdApache(HTTP)
httpdUnix apachectl WindowsNT/2000/XP/2003Windows95/98/ME .
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]
-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
()
||||
-t
"0"(OK)0(Error)"-D DUMP_VHOSTS"
-v
httpd
-V
httpd
-X
httpd
Windows
-kinstall|config|uninstall
ApacheWindowsNTApacheApache
-nname
Apachename
-w
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006113|
ab-ApacheHTTP
abApache(HTTP)ApacheApache
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
-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
-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>
||||
Bugs
HTTP/1.x"" strstr() ab
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006113|
apachectl-ApacheHTTP
apachectlApacheHTTPApache
apachectl httpd httpdSysVstart,restart,stophttpd
Apache apachectlhttpd httpd
apachectl0>0
apachectlhttpd
apachectl[httpd-argument]
SysV apachectl
apachectlcommand
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006113|
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
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...
-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
-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
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
||||
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
$_
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006115|
configure-
configureApacheApache
Unix
configure
./configure[OPTION]...[VAR=VALUE]...
( CC,CFLAGS...) VAR=VALUE
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
--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
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]
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
(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
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)
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)
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
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
--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
--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]
--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[]
||||
configure configure/
CC
C
CFLAGS
Cflags
CPP
C
CPPFLAGS
C/C++flags" -Iincludedir" includedir
LDFLAGS
flags"-L -Llibdir" libdir
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006113|
dbmmanage-DBM
dbmmanageDBM mod_authn_dbmHTTPApacheHTTPdbmmanageDBM htpasswd
dbmmanage[encoding]filename
add|adduser|check|delete|updateusername[
encpasswd[group[,group...][comment]]]
dbmmanagefilenameview[username]
dbmmanagefilenameimport
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
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
||||
Bugs
DBMSDBM,NDBM,GDBM,BerkeleyDB2filenamedbmmanage dbmmanageDBMnothingDBMDBM
dbmmanageDBM @AnyDBM::ISABerkeleyDB2dbmmanageBerkeleyDB2,NDBM,GDBM,SDBM
dbmmanageDBMperl @AnyDBM::ISADBMC
Unix fileDBM
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006113|
htcacheclean-
htcachecleanmod_disk_cacheTERMINT
htcacheclean[-D][-v][-t][-r][-n]-
ppath-llimit
htcacheclean-b[-n][-t][-i]-dinterval-
ppath-llimit
-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
||||
htcacheclean" 0"" 1"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006321|
htdbm-DBM
htdbmmod_authn_dbmHTTPDBM dbmmanageDBM
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]
-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
-TDBTYPE
DBM(SDBM,GDBM,DB,"default")
Bugs
DBMSDBM,NDBM,GNUGDBM,Berkeley/SleepycatDB2/3/4filenamehtdbm htdbm
DBM
Unix fileDBM
htdbm" 0"" 1"" 2"" 3"" 4"(username,filename,password,)" 5"( )" 6"" 7"
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
Web( htdbm)
-b
||||
WindowsMPE htdbm255
htdbmMD5ApacheApacheWeb
255( :)
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006114|
htdigest-
htdigest// htdigest
mod_auth_digest
htdigest[-c]passwdfilerealmusername
||||
-c
passwdfilepasswdfile
passwdfile
// -c
realm
username
passwdfile username
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006114|
htpasswd-
htpasswd/ htpasswd
htpasswdDBM dbmmanage
htpasswdApacheMD5crypt() htpasswdMD5crypt()
mod_auth_basic
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
-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
htpasswdpasswdfile" 0"" 1"" 2"" 3"" 4"(username,filename,password,)" 5"( )" 6"" 7"
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
Web( htpasswd)
-b
||||
WindowsMPE htdbm255
htdbmMD5ApacheApacheWeb
255( :)
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006114|
logresolve-ApacheIP
logresolveApacheIPIP
ApacheIP
logresolve[-sfilename][-c]<access_log>
access_log.new
||||
-sfilename
-c
logresolveDNSIPIP
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006114|
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
rotatelogs[-l]logfile[rotationtime[offset
]]|[filesizeM]
-l
GMTGMT() -l
logfile
logfile"%" strftime()" .nnnnnnnnnn"
rotationtime
offset
UTC"0"UTCUTC"-5"" -300"
filesizeM
filesizeM
||||
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
%% "%"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006114|
Apache" support"
log_server_status
perlcron
||||
split-logfile
perlweb(" %v")+" .log"
webstdin
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |200619|
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
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.
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.
ApacheIETF
RFC2617(Draftstandard)"HTTP/1.0",includesthespecificationforaBasicAccessAuthenticationscheme.
||||
/
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006121|
(Status)
(Status)Apache
MPMMPM
Base
ExtensionApache
ExperimentalApache
ExternalApache("")
<IfModule>
LoadModule
||||
Apache2.0
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006121|
Apache
()"|" "..."
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
(Apache)" None"httpd.conf
serverconfig(httpd.conf) <VirtualHost><Directory>.htaccess
virtualhost<VirtualHost>
directory<Directory>,<Location>,<Files>,<Proxy>
.htaccess.htaccess overrides
" serverconfig,.htaccess" httpd.conf
.htaccess<Directory><VirtualHost>
.htaccess .htaccess
AllowOverride() AllowOverride
Apache
CoreApache
MPMMPM
BaseApache
ExtensionApache
Experimental
||||
Apache2
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006120|
Apache(Core)
ApacheHTTP(C)
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
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>
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
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
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
AddOutputFilter
SetOutputFilter
AllowEncodedSlashes
URLAllowEncodedSlashesOn|Off
AllowEncodedSlashesOff
serverconfig,virtualhost(C)coreApache2.0.46
AllowEncodedSlashesURL("%2F"→"/"" %5C"→"\")URL"404"()
AllowEncodedSlashesOnPATH_INFO
() %2F%5C()URL
AcceptPathInfo
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,
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
AuthName
HTTPAuthNameauth-domain
directory,.htaccessAuthConfig(C)core
AuthName AuthTypeRequireAuthUserFile
AuthGroupFile
AuthName"TopSecret"
AuthName
AuthType
AuthTypeBasic|Digest
directory,.htaccessAuthConfig(C)core
Basic(mod_auth_basic)Digest(mod_auth_digest)
AuthNameRequire( mod_authn_file)(mod_authz_user)
CGIMapExtension
CGICGIMapExtensioncgi-path.extension
directory,.htaccessFileInfo(C)coreNetWareonly
ApacheCGI" CGIMapExtensionsys:\foo.nlm.foo".fooCGIFOO
ContentDigest
Content-MD5
ContentDigestOn|Off
ContentDigestOff
serverconfig,virtualhost,directory,.htaccessOptions(C)core
RFC1854RFC2068Content-MD5
MD5""("")
Content-MD5
Content-MD5:AuLb7Dp1rqtRtxz2m9kRpA==
()
Content-MD5ApacheSSICGI
DefaultType
MIMEDefaultTypeMIME-type
DefaultTypetext/plain
serverconfig,virtualhost,directory,.htaccessFileInfo(C)core
MIME
DefaultType
DefaultTypeimage/gif
gif.gif
ForceTypemimemime
<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>
/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>
<DirectoryMatch>
<DirectoryMatchregex>...</DirectoryMatch>
serverconfig,virtualhost(C)core
<DirectoryMatch></DirectoryMatch> <Directory>
<DirectoryMatch"^/www/(.+/)*[0-9]{3}">
/www/3
<Directory><Directory>
<Directory><Location><Files>
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
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>
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>
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>
ErrorDocument404default
</Directory>
ErrorDocumentURL(" http")ApacheURLweb"" ErrorDocument401"
MicrosoftInternetExplorer(MSIE)""""512byteMSIE Q294807
ErrorDocument""
2.0
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(/)(\)
LogLevel
Apache
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"
<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>
<FilesMatch>
<FilesMatchregex>...</FilesMatch>
serverconfig,virtualhost,directory,.htaccessAll(C)core
<FilesMatch><Files>
<FilesMatch"\.(gif|jpe?g|png)$">
internet
<Directory><Location><Files>
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>
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
<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>
<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>
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
apachectl
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
KeepAliveTimeout
KeepAliveTimeoutseconds
KeepAliveTimeout5
serverconfig,virtualhost(C)core
Apache Timeout
KeepAliveTimeout
<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
<LimitExcept>
HTTP<LimitExceptmethod[method]...>...
</LimitExcept>
serverconfig,virtualhost,directory,.htaccessAll(C)core
<LimitExcept></LimitExcept> HTTP <Limit>
<LimitExceptPOSTGET>
Requirevalid-user
</LimitExcept>
LimitInternalRecursion
LimitInternalRecursionnumber[number]
LimitInternalRecursion10
serverconfig,virtualhost(C)coreApache2.0.47
ActionCGIApacheURI mod_dirDirectoryIndex
LimitInternalRecursion
number() number number
LimitInternalRecursion5
LimitRequestBody
HTTPLimitRequestBodybytes
LimitRequestBody0
serverconfig,virtualhost,directory,.htaccessAll(C)core
bytes0()2147483647(2GB)
LimitRequestBody()HTTPCGI PUT
100K
LimitRequestBody102400
LimitRequestFields
HTTPLimitRequestFieldsnumber
LimitRequestFields100
serverconfig(C)core
Number0()32767 DEFAULT_LIMIT_REQUEST_FIELDS(100)
LimitRequestFieldsHTTP20HTTP
LimitRequestFields50
LimitRequestFieldSize
LimitRequestFieldsizebytes
LimitRequestFieldsize8190
serverconfig(C)core
bytesHTTP
LimitRequestFieldSizeHTTPSPNEGO12392
LimitRequestFieldSize4094
LimitRequestLine
HTTPLimitRequestLinebytes
LimitRequestLine8190
serverconfig(C)core
bytesHTTP
LimitRequestLineHTTPHTTPURILimitRequestLineURI GET
LimitRequestLine4094
LimitXMLRequestBody
XMLLimitXMLRequestBodybytes
LimitXMLRequestBody1000000
serverconfig,virtualhost,directory,.htaccessAll(C)core
XML" 0"
LimitXMLRequestBody0
<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
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>
<LocationMatch>
URL<LocationMatchregex>...</LocationMatch>
serverconfig,virtualhost(C)core
<LocationMatch><Location>URL
<LocationMatch"/(extra|special)/data">
" /extra/data"" /special/data"URL
<Directory><Location><Files>
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
notice syslog
MaxKeepAliveRequests
MaxKeepAliveRequestsnumber
MaxKeepAliveRequests100
serverconfig,virtualhost(C)core
MaxKeepAliveRequestsKeepAlive" 0"
MaxKeepAliveRequests500
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*
<VirtualHost>
<VirtualHost>NameVirtualHost
NameVirtualHost1.2.3.4
<VirtualHost1.2.3.4>
#...
</VirtualHost>
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
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
-IncludesNOEXEC -Includes
All
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
Satisfy mod_authz_host
<Directory/path/to/protected/>
Requireuserdavid
</Directory>
<Directory/path/to/protected/unprotected>
#
SatisfyAny
Allowfromall
</Directory>
Satisfy
mod_authz_host
RLimitCPU
ApacheCPURLimitCPUseconds|max[seconds|max]
serverconfig,virtualhost,directory,.htaccessAll(C)core
" max" root
ApacheApacheCGISSIApache
CPU
RLimitMEM
RLimitNPROC
RLimitMEM
ApacheRLimitMEMbytes|max[bytes|max]
serverconfig,virtualhost,directory,.htaccessAll(C)core
" max" root
ApacheApacheCGISSIApache
RLimitCPU
RLimitNPROC
RLimitNPROC
ApacheRLimitNPROCnumber|max[number|max]
serverconfig,virtualhost,directory,.htaccessAll(C)core
" max" root
ApacheApacheCGISSIApache
CGIwebuid error_log" cannotfork"
RLimitMEM
RLimitCPU
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
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
ServerAdmin
ServerAdminemail-address|URL
serverconfig,virtualhost(C)core
ServerAdmin httpdURLemail-addressmailto:EmailCGIURL
ServerAlias
ServerAliashostname[hostname]...
virtualhost(C)core
ServerAlias
<VirtualHost*>
ServerNameserver.domain.com
ServerAliasserverserver2.domain.comserver2
#...
</VirtualHost>
Apache
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
ServerPath
URLServerPathURL-path
virtualhost(C)core
ServerPath(legacy)URL
Apache
ServerRoot
ServerRootdirectory-path
ServerRoot/usr/local/apache
serverconfig(C)core
ServerRoot conf/logs/( IncludeLoadModule)
ServerRoot/home/httpd
httpd -dServerRoot
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
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
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
SetInputFilter
POSTSetInputFilterfilter[;filter...]
serverconfig,virtualhost,directory,.htaccessFileInfo(C)core
SetInputFilterPOST( AddInputFilter)
(;)
SetOutputFilter
SetOutputFilterfilter[;filter...]
serverconfig,virtualhost,directory,.htaccessFileInfo(C)core
SetOutputFilter( AddOutputFilter)
/www/data/SSI
<Directory/www/data/>
SetOutputFilterINCLUDES
</Directory>
(;)
TimeOut
TimeOutseconds
TimeOut300
serverconfig(C)core
TimeOutApache
1. GET
2. POSTPUTTCP
3. TCPACK
1.21200300
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
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
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
UseCanonicalName
ServerName
Listen
<VirtualHost>
IP<VirtualHostaddr[:port][addr[:port]]...>...
</VirtualHost>
serverconfig(C)core
<VirtualHost></VirtualHost> <VirtualHost>
Addr
IPIP" *"" NameVirtualHost*"IP" _default_"IPIP
<VirtualHost10.1.2.3>
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]>
DocumentRoot/www/docs/host.example.com
ServerNamehost.example.com
ErrorLoglogs/host.example.com-error_log
TransferLoglogs/host.example.com-access_log
</VirtualHost>
||||
IPIPIP( ifconfigalias)
<VirtualHost>Apache ListenApache
IP" _default_"IP" _default_"IP""()NameVirtualHostIP""" _default_"
" :port" Listen" :*"(" _default_")
ApacheDNSApacheApache<Directory><Location><Files>
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006122|
ApacheMPM
(MPM)MPM
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
CoreDumpDirectory
ApacheCoreDumpDirectorydirectory
serverconfigMPMbeos,mpm_winnt,prefork,worker
Apache ServerRoot
Linux
ApacherootLinux ApacheApache2.0.46CoreDumpDirectoryLinux2.4
EnableExceptionHook
EnableExceptionHookOn|Off
EnableExceptionHookOff
serverconfigMPMprefork,workerApache2.0.49
--enable-exception-hook(hook)
(mod_whatkilledusmod_backtrace)JeffTrawickEnableExceptionHooksite
GracefulShutdownTimeout
GracefulShutDownTimeoutseconds
GracefulShutDownTimeout0
serverconfigMPMprefork,worker,eventApache2.2
GracefulShutdownTimeout""
"0"
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
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
Listen192.170.2.1:8443https
Listen" Addressalreadyinuse"
DNS
ListenBackLog
(pendingconnection)ListenBacklogbacklog
ListenBacklog511
serverconfigMPMbeos,mpm_netware,mpm_winnt,mpmt_os2,prefork,worker
(pendingconnection)TCPSYN listen(2)
()
LockFile
LockFilefilename
LockFilelogs/accept.lock
serverconfigMPMprefork,worker
LockFileAcceptMutexfcntlflockApache logsNFSPID
( /var/tmp)
AcceptMutex
MaxClients
MaxClientsnumber
serverconfigMPMbeos,prefork,worker
MaxClients MaxClients ListenBacklog
MPM( prefork) MaxClients 256 ServerLimit
MPM( beosworker) MaxClients beos50MPM16(ServerLimit)25(ThreadsPerChild) MaxClients16ServerLimit
MaxMemFree
free()(KB)MaxMemFreeKBytes
MaxMemFree0
serverconfigMPMbeos,mpm_netware,prefork,worker,mpm_winnt
MaxMemFreefree()(KB)"0"
MaxRequestsPerChild
MaxRequestsPerChildnumber
MaxRequestsPerChild10000
serverconfigMPMmpm_netware,mpm_winnt,mpmt_os2,prefork,worker
MaxRequestsPerChild MaxRequestsPerChild
MaxRequestsPerChild" 0"
mpm_netwarempm_winnt" 0"
MaxRequestsPerChild
()
KeepAlive
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
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
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
ReceiveBufferSize
TCP()ReceiveBufferSizebytes
ReceiveBufferSize0
serverconfigMPMbeos,mpm_netware,mpm_winnt,mpmt_os2,prefork,worker
TCP()(100ms)
" 0"
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
SendBufferSize
TCP()SendBufferSizebytes
SendBufferSize0
serverconfigMPMbeos,mpm_netware,mpm_winnt,mpmt_os2,prefork,worker
TCP()(100ms)
" 0"
ServerLimit
ServerLimitnumber
serverconfigMPMprefork,worker
preforkMPM MaxClients workerMPM ThreadLimit
MaxClients MaxClients
ServerLimit ServerLimitMaxClientsApache
preforkMPM MaxClients256 MaxClients
workerMPM MaxClientsThreadsPerChild16 MaxClients
ThreadsPerChild
Apache" ServerLimit20000"( preforkMPM" ServerLimit200000")
Apache
StartServers
StartServersnumber
serverconfigMPMmpmt_os2,prefork,worker
StartServers
MPM worker" 3" prefork" 5" mpmt_os2" 2"
StartThreads
StartThreadsnumber
serverconfigMPMbeos,mpm_netware
mpm_netware" 50"
beos" 10"
ThreadLimit
ThreadLimitnumber
serverconfigMPMmpm_winnt,worker2.0.41mpm_winnt
ThreadsPerChild ThreadsPerChild
ThreadLimitThreadsPerChild ThreadLimit
ThreadsPerChildApache ThreadsPerChild
mpm_winntThreadLimit1920MPM64
Apache" ThreadLimit20000"( mpm_winnt" ThreadLimit
15000")
ThreadsPerChild
ThreadsPerChildnumber
serverconfigMPMmpm_winnt,worker
mpm_winntMPM workerMPM
mpm_winntThreadsPerChild64MPM25
ThreadStackSize
()ThreadStackSizesize
NetWare65536
serverconfigMPMmpm_netware,mpm_winnt,workerApache2.1
ThreadStackSize()()
(HP-UX)Apache ThreadStackSize
ThreadStackSize ThreadStackSize
||||
User
Userunix-userid
User#-1
serverconfigMPMprefork,worker2.0
User root root root root Unix-userid
"#"
Apache nobody
User( Group)root
<VirtualHost> suexecSuexecUserGroup
Userbeosmpmt_os2MPM
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
ApacheMPMbeos
ThisMulti-ProcessingModuleisoptimizedforBeOS.MPMmpm_beos_modulebeos.c
ThisMulti-ProcessingModule(MPM)isthedefaultforBeOS.Itusesasinglecontrolprocesswhichcreatesthreadstohandlerequests.
||||
MaxRequestsPerThread
LimitonthenumberofrequeststhatanindividualthreadwillhandleduringitslifeMaxRequestsPerThreadnumber
MaxRequestsPerThread0
serverconfigMPMbeos
MaxRequestsPerThreaddirectivesetsthelimitonthenumberofrequeststhatanindividualserverthreadwillhandle.AfterMaxRequestsPerThreadrequests,thethreadwilldie.IfMaxRequestsPerThreadis0,thenthethreadwillneverexpire.
SettingMaxRequestsPerThreadtoanon-zerolimithastwobeneficialeffects:
itlimitstheamountofmemorythatathreadcanconsumeby(accidental)memoryleakage;bygivingthreadsafinitelifetime,ithelpsreducethenumberofthreadswhentheserverloadreduces.
ForKeepAliverequests,onlythefirstrequestiscountedtowardsthislimit.Ineffect,itchangesthebehaviortolimitthenumberofconnectionsperthread.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
||||
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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
requestsindefinitely.
||||
MaxThreads
SetthemaximumnumberofworkerthreadsMaxThreadsnumber
MaxThreads2048
serverconfigMPMmpm_netware
MaxThreadsdirectivesetsthedesiredmaximumnumberworkerthreadsallowable.Thedefaultvalueisalsothecompiledinhardlimit.Thereforeitcanonlybelowered,forexample:
MaxThreads512
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
||||
ApacheMPMos2
Hybridmulti-process,multi-threadedMPMforOS/2MPMmpm_mpmt_os2_modulempmt_os2.c
TheServerconsistsofamain,parentprocessandasmall,staticnumberofchildprocesses.
Theparentprocess'sjobistomanagethechildprocesses.ThisinvolvesspawningchildrenasrequiredtoensuretherearealwaysStartServersprocessesacceptingconnections.
Eachchildprocessconsistsofaapoolofworkerthreadsandamainthreadthatacceptsconnectionsandpassesthemtotheworkersviaaworkqueue.Theworkerthreadpoolisdynamic,managedbyamaintenancethreadsothatthenumberofidlethreadsiskeptbetweenMinSpareThreadsMaxSpareThreads.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006121|
ApacheMPMprefork
MPMMPMmpm_prefork_moduleprefork.c
(MPM)webApache1.3MPM
MPM MaxClients
()Apache (spare)
StartServers,MinSpareServers,MaxSpareServers,MaxClientsApache256 MaxClients MaxClients
Unix root80Apache UserGroup
MaxRequestsPerChild
MaxSpareServers
MaxSpareServersnumber
MaxSpareServers10
serverconfigMPMprefork
MaxSpareServers MaxSpareServers
MinSpareServersApache" MinSpareServers+1"
MinSpareServers
StartServers
||||
MinSpareServers
MinSpareServersnumber
MinSpareServers5
serverconfigMPMprefork
MinSpareServers MinSpareServersApache
MaxSpareServers
StartServers
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006121|
ApacheMPMwinnt
WindowsNTMPMMPMmpm_winnt_modulempm_winnt.c
(MPM)WindowsNT
||||
Win32DisableAcceptEx
accept()AcceptEx()Win32DisableAcceptEx
AcceptEx()
serverconfigMPMmpm_winntApache2.0.49
AcceptEx()WinSock2APIBSDaccept()APIWindowsAcceptEx()
[error](730038)Anoperationwasattemptedon
somethingthatisnotasocket.:winnt_accept:
AcceptExfailed.Attemptingtorecover.
AcceptEx()
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006121|
ApacheMPMworker
MPMmpm_worker_moduleworker.c
(MPM)MPMMPM
MPM ThreadsPerChild MaxClients
||||
() 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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006122|
Apachemod_actions
CGI(B)actions_modulemod_actions.c
ActionMIMECGI ScriptCGICGI
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>
AddHandler
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006123|
Apachemod_alias
URL(B)alias_modulemod_alias.c
URL AliasScriptAliasURL DocumentRoot
ScriptAliasCGI
RedirectURL
mod_aliasURLURL mod_rewrite
(context) (context)( <VirtualHost>)
RedirectRedirectMatch
Alias/foo/bar/baz
Alias/foo/gaq
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>
AliasMatch
URLAliasMatchregexfile-path|directory-path
serverconfig,virtualhost(B)mod_alias
Alias URL-path" /icons"
AliasMatch^/icons(.*)/usr/local/apache/icons$1
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
""(303)
gone""(410) URL
status300-399 URLApache(http_protocol.csend_error_response)
Redirectpermanent/onehttp://example.com/two
Redirect303/threehttp://example.com/other
RedirectMatch
URLRedirectMatch[status]regexURL
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_alias
Redirect regexURL-pathGIFJPEG
RedirectMatch(.*)\.gif$
http://www.anotherserver.com$1.jpg
RedirectPermanent
URLRedirectPermanentURL-pathURL
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_alias
(status301)" Redirectpermanent"
RedirectTemp
URLRedirectTempURL-pathURL
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_alias
(status302)" Redirecttemp"
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
||||
ScriptAliasMatch
URLCGIScriptAliasMatchregexfile-path|directory-path
serverconfig,virtualhost(B)mod_alias
ScriptAlias regexURL-path /cgi-bin
ScriptAliasMatch^/cgi-bin(.*)
/usr/local/apache/cgi-bin$1
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006123|
Apachemod_asis
HTTP(B)asis_modulemod_asis.c
send-as-isApacheHTTP(headers)
HTTPcgi-scriptnphscript
MIME httpd/send-as-is
||||
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:"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006123|
Apachemod_auth_basic
(B)auth_basic_modulemod_auth_basic.cApache2.1
HTTP mod_auth_digestHTTP(mod_authn_file)( mod_authz_user)
AuthBasicAuthoritative
()AuthBasicAuthoritativeOn|Off
AuthBasicAuthoritativeOn
directory,.htaccessAuthConfig(B)mod_auth_basic
AuthBasicProvider AuthBasicAuthoritative
OffuserID userIDrule() (non-provider-based)()mod_auth_basicAuthBasicProvider
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006123|
Apachemod_auth_digest
MD5()(X)auth_digest_modulemod_auth_digest.c
HTTP
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
MSInternetExplorer6
InternetExplorer6 GETRFC
POSTGET
2.0.51Apache AuthDigestEnableQueryStringHack
(workaround) AuthDigestEnableQueryStringHackApacheInternetExplorer6bugURI
MSIE6BrowserMatch"MSIE"
AuthDigestEnableQueryStringHack=On
BrowserMatch
AuthDigestAlgorithm
AuthDigestAlgorithmMD5|MD5-sess
AuthDigestAlgorithmMD5
directory,.htaccessAuthConfig(X)mod_auth_digest
AuthDigestAlgorithm
MD5-sess
AuthDigestDomain
URIAuthDigestDomainURI[URI]...
directory,.htaccessAuthConfig(X)mod_auth_digest
AuthDigestDomainURI(/)URIURI""URI/URIURI()URI
URI AuthDigestNcCheck"On"
URI
AuthDigestNcCheck
Enablesordisablescheckingofthenonce-countsentbytheserverAuthDigestNcCheckOn|Off
AuthDigestNcCheckOff
serverconfig(X)mod_auth_digest
AuthDigestNonceFormat
DetermineshowthenonceisgeneratedAuthDigestNonceFormatformat
directory,.htaccessAuthConfig(X)mod_auth_digest
AuthDigestNonceLifetime
nonce()AuthDigestNonceLifetimeseconds
AuthDigestNonceLifetime300
directory,.htaccessAuthConfig(X)mod_auth_digest
AuthDigestNonceLifetimenonce()nonce()" stale=true"401() seconds"0"nonce()()30120(10)
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
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
||||
AuthDigestShmemSize
AuthDigestShmemSizesize
AuthDigestShmemSize1000
serverconfig(X)mod_auth_digest
AuthDigestShmemSize AuthDigestShmemSize
" 0"Apache
size" K"" M"KBMB
AuthDigestShmemSize1048576
AuthDigestShmemSize1024K
AuthDigestShmemSize1M
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006123|
Apachemod_authn_alias
(E)authn_alias_modulemod_authn_alias.cApache2.1
AuthBasicProviderAuthDigestProvider
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>
||||
<AuthnProviderAlias>
<AuthnProviderAliasbaseProviderAlias>...
</AuthnProviderAlias>
serverconfig,virtualhost(E)mod_authn_alias
<AuthnProviderAlias></AuthnProviderAlias>
AuthBasicProviderAuthDigestProvider
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
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>
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.
Anonymous_LogEmail
SetswhetherthepasswordenteredwillbeloggedintheerrorlogAnonymous_LogEmailOn|Off
Anonymous_LogEmailOn
directory,.htaccessAuthConfig(E)mod_authn_anon
WhensetOn,thedefault,the'password'entered(whichhopefullycontainsasensibleemailaddress)isloggedintheerrorlog.
Anonymous_MustGiveEmail
SpecifieswhetherblankpasswordsareallowedAnonymous_MustGiveEmailOn|Off
Anonymous_MustGiveEmailOn
directory,.htaccessAuthConfig(E)mod_authn_anon
Specifieswhethertheusermustspecifyanemailaddressasthepassword.Thisprohibitsblankpasswords.
Anonymous_NoUserID
SetswhethertheuserIDfieldmaybeemptyAnonymous_NoUserIDOn|Off
Anonymous_NoUserIDOff
directory,.htaccessAuthConfig(E)mod_authn_anon
WhensetOn,userscanleavetheuserID(andperhapsthepasswordfield)empty.ThiscanbeveryconvenientforMS-ExploreruserswhocanjusthitreturnorclickdirectlyontheOKbutton;whichseemsanaturalreaction.
||||
Anonymous_VerifyEmail
SetswhethertocheckthepasswordfieldforacorrectlyformattedemailaddressAnonymous_VerifyEmailOn|Off
Anonymous_VerifyEmailOff
directory,.htaccessAuthConfig(E)mod_authn_anon
WhensetOnthe'password'enteredischeckedforatleastone'@'anda'.'toencourageuserstoentervalidemailaddresses(seetheaboveAnonymous_LogEmail).
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
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>
AuthDBDUserPWQuery
SQLquerytolookupapasswordforauserAuthDBDUserPWQueryquery
directoryAuthConfig(E)mod_authn_dbd
AuthDBDUserPWQueryspecifiesanSQLquerytolookupapasswordforaspecifieduser.Thequerymusttakeasinglestring(typicallySQLvarchar)argument(username),andreturnasinglevalue(encryptedpassword).
AuthDBDUserPWQuery"SELECTpasswordFROMauthn
WHEREusername=%s"
||||
AuthDBDUserRealmQuery
SQLquerytolookupapasswordhashforauserandrealm.AuthDBDUserRealmQueryquery
directoryAuthConfig(E)mod_authn_dbd
AuthDBDUserRealmPWQueryspecifiesanSQLquerytolookupapasswordforaspecifieduserandrealm.Thequerymusttaketwostring(typicallySQLvarchar)arguments(usernameandrealm),andreturnasinglevalue(encryptedpassword).
AuthDBDUserRealmPWQuery"SELECTpasswordFROM
authnWHEREusername=%sANDrealm=%s"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
AuthDBMType
SetsthetypeofdatabasefilethatisusedtostorepasswordsAuthDBMTypedefault|SDBM|GDBM|NDBM|DB
AuthDBMTypedefault
directory,.htaccessAuthConfig(E)mod_authn_dbm
Setsthetypeofdatabasefilethatisusedtostorethepasswords.Thedefaultdatabasetypeisdeterminedatcompiletime.Theavailabilityofothertypesofdatabasefilesalsodependsoncompile-timesettings.
Itiscrucialthatwhateverprogramyouusetocreateyourpasswordfilesisconfiguredtousethesametypeofdatabase.
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
||||
withthismodule.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006124|
Apachemod_authn_default
(B)authn_default_modulemod_authn_default.cApache2.1
(fallback)( mod_auth_basic)
||||
AuthDefaultAuthoritative
AuthDefaultAuthoritativeOn|Off
AuthDefaultAuthoritativeOn
directory,.htaccessAuthConfig(B)mod_authn_default
AuthDefaultAuthoritative Off( modules.c)
mod_authn_default AuthDefaultAuthoritative
(On)
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006124|
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
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
Contents
OperationTheAuthenticationPhaseTheAuthorizationPhase
TherequireDirectivesrequirevalid-userrequireldap-userrequireldap-grouprequireldap-dnrequireldap-attributerequireldap-filter
ExamplesUsingTLSUsingSSLUsingMicrosoftFrontPagewithmod_authnz_ldap
HowItWorksCaveats
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
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
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.
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,
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
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"
requireldap-attributecity="SanJose"
status=active
requireldap-filterrequireldap-filterdirectiveallowstheadministratortograntaccessbasedonacomplexLDAPsearchfilter.Ifthednreturnedbythefiltersearchmatchestheauthenticateduserdn,accessisgranted.
Thefollowingdirectivewouldgrantaccesstoanyonehavingacellphoneandisinthemarketingdepartment
requireldap-filter&(cell=*)
(department=marketing)
Thedifferencebetweentherequireldap-filterdirectiveandtherequireldap-attributedirectiveisthatldap-filterperformsasearchoperationontheLDAPdirectoryusingthespecifiedsearchfilterratherthanasimpleattributecomparison.Ifasimpleattributecomparisonisallthatisrequired,thecomparisonoperationperformedbyldap-attributewillbefasterthanthesearchoperationusedbyldap-filterespeciallywithinalargedirectory.
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
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
(&(|(qpagePagerID=*)(uid=jmanager))
(uid=jmanager))
Theabovesearchwillsucceedwhetherjmanagerhasapagerornot.
UsingTLS
TouseTLS,seethemod_ldapdirectivesLDAPTrustedClientCert,LDAPTrustedGlobalCertLDAPTrustedMode.
AnoptionalsecondparametercanbeaddedtotheAuthLDAPURLtooverridethedefaultconnectiontypesetbyLDAPTrustedMode.Thiswillallowtheconnectionestablishedbyanldap://Urltobeupgradedtoasecureconnectiononthesameport.
UsingSSL
TouseSSL,seethemod_ldapdirectivesLDAPTrustedClientCert,LDAPTrustedGlobalCertLDAPTrustedMode.
TospecifyasecureLDAPserver,useldaps://intheAuthLDAPURLdirective,insteadofldap://.
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
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.
AuthLDAPBindDN
OptionalDNtouseinbindingtotheLDAPserverAuthLDAPBindDNdistinguished-name
directory,.htaccessAuthConfig(E)mod_authnz_ldap
AnoptionalDNusedtobindtotheserverwhensearchingforentries.Ifnotprovided,mod_authnz_ldapwilluseananonymousbind.
AuthLDAPBindPassword
PasswordusedinconjuctionwiththebindDNAuthLDAPBindPasswordpassword
directory,.htaccessAuthConfig(E)mod_authnz_ldap
AbindpasswordtouseinconjunctionwiththebindDN.Notethatthebindpasswordisprobablysensitivedata,andshouldbeproperlyprotected.YoushouldonlyusetheAuthLDAPBindDNAuthLDAPBindPasswordifyouabsolutelyneedthemtosearchthedirectory.
AuthLDAPCharsetConfig
LanguagetocharsetconversionconfigurationfileAuthLDAPCharsetConfigfile-path
serverconfig(E)mod_authnz_ldap
AuthLDAPCharsetConfigdirectivesetsthelocationofthelanguagetocharsetconversionconfigurationfile.File-pathisrelativetotheServerRoot.Thisfilespecifiesthelistoflanguageextensionstocharactersets.Mostadministratorsusetheprovidedcharset.convfile,whichassociatescommonlanguageextensionstocharactersets.
Thefilecontainslinesinthefollowingformat:
Language-Extensioncharset[Language-String]...
Thecaseoftheextensiondoesnotmatter.Blanklines,andlinesbeginningwithahashcharacter(#)areignored.
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.
AuthLDAPDereferenceAliases
Whenwillthemodulede-referencealiasesAuthLDAPDereferenceAliases
never|searching|finding|always
AuthLDAPDereferenceAliasesAlways
directory,.htaccessAuthConfig(E)mod_authnz_ldap
Thisdirectivespecifieswhenmod_authnz_ldapwillde-referencealiasesduringLDAPoperations.Thedefaultisalways.
AuthLDAPGroupAttribute
LDAPattributesusedtocheckforgroupmembershipAuthLDAPGroupAttributeattribute
directory,.htaccessAuthConfig(E)mod_authnz_ldap
ThisdirectivespecifieswhichLDAPattributesareusedtocheckforgroupmembership.Multipleattributescanbeusedbyspecifyingthisdirectivemultipletimes.Ifnotspecified,thenmod_authnz_ldapusesthememberuniquememberattributes.
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.
AuthLDAPRemoteUserIsDN
UsetheDNoftheclientusernametosettheREMOTE_USERenvironmentvariableAuthLDAPRemoteUserIsDNon|off
AuthLDAPRemoteUserIsDNoff
directory,.htaccessAuthConfig(E)mod_authnz_ldap
Ifthisdirectiveissettoon,thevalueoftheREMOTE_USERenvironmentvariablewillbesettothefulldistinguishednameoftheauthenticateduser,ratherthanjusttheusernamethatwaspassedbytheclient.Itisturnedoffbydefault.
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.
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
theconnectiontype.Thisparametercanbeoneofthefollowing:
NONEEstablishanunsecureconnectiononthedefaultLDAPport.Thisisthesameasldap://onport389.
SSLEstablishasecureconnectiononthedefaultsecureLDAPport.Thisisthesameasldaps://
TLS|STARTTLSEstablishanupgradedsecureconnectiononthedefaultLDAPport.Thisconnectionwillbeinitiatedonport389bydefaultandthenupgradedtoasecureconnectiononthesameport.
SeeaboveforexamplesofAuthLDAPURLURLs.
||||
AuthzLDAPAuthoritative
PreventotherauthenticationmodulesfromauthenticatingtheuserifthisonefailsAuthzLDAPAuthoritativeon|off
AuthzLDAPAuthoritativeon
directory,.htaccessAuthConfig(E)mod_authnz_ldap
Settooffifthismoduleshouldletotherauthenticationmodulesattempttoauthenticatetheuser,shouldauthenticationwiththismodulefail.ControlisonlypassedontolowermodulesifthereisnoDNorrulethatmatchesthesuppliedusername(aspassedbytheclient).
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_authz_dbm
DBM(E)authz_dbm_modulemod_authz_dbm.cApache2.1
Thismoduleprovidesauthorizationcapabilitiessothatauthenticateduserscanbeallowedordeniedaccesstoportionsofthewebsitebygroupmembership.Similarfunctionalityisprovidedbymod_authz_groupfile.
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
ThekeyforthesingleDBMistheusername.Thevalueconsistsof
EncryptedPassword:ListofGroups[:(ignored)
]
Thepasswordsectioncontainstheencryptedpasswordasbefore.Thisisfollowedbyacolonandthecommaseparatedlistofgroups.OtherdatamayoptionallybeleftintheDBMfileafteranothercolon;itisignoredbytheauthorizationmodule.Thisiswhatwww.telescope.orgusesforitscombinedpasswordandgroupdatabase.
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;
Generallyitiseasiertojustsecureasingle.htpasswdfile,thanitistosecureadatabasewhichmighthavemoreaccessinterfaces.
||||
AuthzDBMType
SetsthetypeofdatabasefilethatisusedtostorelistofusergroupsAuthzDBMTypedefault|SDBM|GDBM|NDBM|DB
AuthzDBMTypedefault
directory,.htaccessAuthConfig(E)mod_authz_dbm
Setsthetypeofdatabasefilethatisusedtostorethelistofusergroups.Thedefaultdatabasetypeisdeterminedatcompiletime.Theavailabilityofothertypesofdatabasefilesalsodependsoncompile-timesettings.
Itiscrucialthatwhateverprogramyouusetocreateyourgroupfilesisconfiguredtousethesametypeofdatabase.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006124|
Apachemod_authz_default
(B)authz_default_modulemod_authz_default.cApache2.1
(fallback)( mod_authz_usermod_authz_groupfile)
||||
AuthzDefaultAuthoritative
AuthzDefaultAuthoritativeOn|Off
AuthzDefaultAuthoritativeOn
directory,.htaccessAuthConfig(B)mod_authz_default
AuthzDefaultAuthoritative Off( modules.c)
mod_authz_default AuthzDefaultAuthoritative
(On)
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006124|
Apachemod_authz_groupfile
(B)authz_groupfile_modulemod_authz_groupfile.cApache2.1
mod_authz_dbm
AuthGroupFile
AuthGroupFilefile-path
directory,.htaccessAuthConfig(B)mod_authz_groupfile
AuthGroupFile File-path ServerRoot
mygroup:bobjoeanne
AuthDBMGroupFile
AuthGroupFileWEB
||||
AuthzGroupFileAuthoritative
AuthzGroupFileAuthoritativeOn|Off
AuthzGroupFileAuthoritativeOn
directory,.htaccessAuthConfig(B)mod_authz_groupfile
AuthzGroupFileAuthoritative OffuserID()( modules.c)
NCSA
.htaccess .htpasswd
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006124|
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>
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
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
Allowfromenv=let_me_in
</Directory>
KnockKnock/2.0
Deny
Denyfromall|host|env=env-variable[host|env=env-
variable]...
directory,.htaccessLimit(B)mod_authz_host
IP DenyAllow
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
||||
apache.org"" Denyfromfoo.apache.org" apache.org
AllowDeny Order
<Directory/www>
OrderAllow,Deny
</Directory>
/www
Order <Location>AllowDeny<Directory>.htaccess
AllowDeny Order
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
Ifmod_authz_ownerisusedinordertoauthorizearesourcethatisnotactuallypresentinthefilesystem(i.e.avirtualresource),itwilldenytheaccess.
Particularlyitwillneverauthorizecontentnegotiated"MultiViews"resources.
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.
<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>
||||
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006124|
Apachemod_authz_user
(B)authz_user_modulemod_authz_user.cApache2.1
mod_authz_user() Requireuser require
valid-user
||||
AuthzUserAuthoritative
AuthzUserAuthoritativeOn|Off
AuthzUserAuthoritativeOn
directory,.htaccessAuthConfig(B)mod_authz_user
AuthzUserAuthoritative OffuserID() ( modules.c
)
NCSA
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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
directive'sSuppressColumnSortingoption.
Notethatwhenthedisplayissortedby"Size",it'stheactualsizeofthefilesthat'sused,notthedisplayedvalue-soa1010-bytefilewillalwaysbedisplayedbeforea1011-bytefile(ifinascendingorder)eventhoughtheybothareshownas"1K".
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
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>
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
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
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
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
affecttherestofthedirectorylisting.
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.
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
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/*
DefaultIcon
IcontodisplayforfileswhennospecificiconisconfiguredDefaultIconurl-path
serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex
DefaultIcondirectivesetstheicontodisplayforfileswhennospecificiconisknown,forFancyIndexing.Url-pathisa(%-escaped)relativeURLtotheicon.
DefaultIcon/icon/unknown.xbm
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
ContentnegotiationwillbeperformedifOptionsMultiViewsisineffect.Iffilenameresolvestoastatictext/htmldocument(notaCGIscript)andeitheroneoftheoptionsIncludesIncludesNOEXECisenabled,thefilewillbeprocessedforserver-sideincludes(seethemod_includedocumentation).
IfthefilespecifiedbyHeaderNamecontainsthebeginningsofanHTMLdocument(<html>,<head>,etc.)thenyouwillprobablywanttosetIndexOptions+SuppressHTMLPreamble,sothatthesetagsarenotrepeated.
IndexIgnore
AddstothelistoffilestohidewhenlistingadirectoryIndexIgnorefile[file]...
serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex
IndexIgnoredirectiveaddstothelistoffilestohidewhenlistingadirectory.Fileisashell-stylewildcardexpressionorfullfilename.MultipleIndexIgnoredirectivesaddtothelist,ratherthanthereplacingthelistofignoredfiles.Bydefault,thelistcontains.(thecurrentdirectory).
IndexIgnoreREADME.htaccess*.bak*~
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
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
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.
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
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
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.
TounconditionallysettheIndexOptionsforaparticulardirectory,clearingtheinheritedsettings,specifykeywordswithoutany+-prefixes.
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.
IndexStyleSheet
AddsaCSSstylesheettothedirectoryindexIndexStyleSheeturl-path
serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex
IndexStyleSheetdirectivesetsthenameofthefilethatwillbeusedastheCSSfortheindexlisting.
IndexStyleSheet"/css/style.css"
||||
ReadmeName
NameofthefilethatwillbeinsertedattheendoftheindexlistingReadmeNamefilename
serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_autoindex
ReadmeNamedirectivesetsthenameofthefilethatwillbeappendedtotheendoftheindexlisting.Filenameisthenameofthefiletoinclude,andistakentoberelativetothelocationbeingindexed.IfFilenamebeginswithaslash,itwillbetakentoberelativetotheDocumentRoot.
ReadmeNameFOOTER.html
Example2ReadmeName/include/FOOTER.html
SeealsoHeaderName,wherethisbehaviorisdescribedingreaterdetail.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
RelatedModulesandDirectives
mod_disk_cache
mod_mem_cache
CacheRoot
CacheSize
CacheDirLevels
CacheDirLength
CacheMinFileSize
CacheMaxFileSize
MCacheSize
MCacheMaxObjectCount
MCacheMinObjectSize
MCacheMaxObjectSize
MCacheRemovalAlgorithm
MCacheMaxStreamingBuffer
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>
CacheDefaultExpire
Thedefaultdurationtocacheadocumentwhennoexpirydateisspecified.CacheDefaultExpireseconds
CacheDefaultExpire3600(onehour)
serverconfig,virtualhost(E)mod_cache
CacheDefaultExpiredirectivespecifiesadefaulttime,inseconds,tocacheadocumentifneitheranexpirydatenorlast-modifieddateareprovidedwiththedocument.ThevaluespecifiedwiththeCacheMaxExpiredirectivedoesnotoverridethissetting.
CacheDefaultExpire86400
CacheDisable
DisablecachingofspecifiedURLsCacheDisableurl-string
serverconfig,virtualhost(E)mod_cache
CacheDisabledirectiveinstructsmod_cachetonotcacheurlsatorbelowurl-string.
CacheDisable/local_files
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
CacheEnabledisk/
#CacheFTP-proxiedurl's
CacheEnablediskftp://
#Cachecontentfromwww.apache.org
CacheEnablediskhttp://www.apache.org/
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
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
CacheIgnoreHeadersSet-Cookie
Example2CacheIgnoreHeadersNone
Warning:IfheaderslikeExpireswhichareneededforpropercachemanagementarenotstoredduetoaCacheIgnoreHeaderssetting,thebehaviourofmod_cacheisundefined.
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
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
CacheMaxExpire
ThemaximumtimeinsecondstocacheadocumentCacheMaxExpireseconds
CacheMaxExpire86400(oneday)
serverconfig,virtualhost(E)mod_cache
CacheMaxExpiredirectivespecifiesthemaximumnumberofsecondsforwhichcachableHTTPdocumentswillberetainedwithoutcheckingtheoriginserver.Thus,documentswillbeoutofdateatmostthisnumberofseconds.Thismaximumvalueisenforcedevenifanexpirydatewassuppliedwiththedocument.
CacheMaxExpire604800
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
||||
CacheStorePrivate
AttempttocacheresponsesthattheserverhasmarkedasprivateCacheStorePrivateOn|Off
CacheStorePrivateOff
serverconfig,virtualhost(E)mod_cache
Ordinarily,responseswithCache-Control:privateheadervalueswillnotbestoredinthecache.TheCacheStorePrivatedirectiveallowsthisbehaviortobeoverridden.CacheStorePrivateOntellstheservertoattempttocachetheresourceevenifitcontainsprivateheadervalues.Resourcesrequiringauthorizationwillneverbecached.
CacheStorePrivateOn
Warning:Thisdirectivewillallowcachingeveniftheupstreamserverhasrequestedthattheresourcenotbecached.Thisdirectiveisonlyidealfora'private'cache.
CacheIgnoreCacheControl
CacheStoreNoStore
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_cern_meta
ApacheCERNhttpd(E)cern_meta_modulemod_cern_meta.c
EmulatetheCERNHTTPDMetafilesemantics.MetafilesareHTTPheadersthatcanbeoutputinadditiontothenormalrangeofheadersforeachfileaccessed.TheyappearratherliketheApache.asisfiles,andareabletoprovideacrudewayofinfluencingtheExpires:header,aswellasprovidingothercuriosities.Therearemanywaystomanagemetainformation,thisonewaschosenbecausethereisalreadyalargenumberofCERNuserswhocanexploitthismodule.
MoreinformationontheCERNmetafilesemanticsisavailable.
MetaDir
NameofthedirectorytofindCERN-stylemetainformationfilesMetaDirdirectory
MetaDir.web
serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_cern_meta
SpecifiesthenameofthedirectoryinwhichApachecanfindmetainformationfiles.Thedirectoryisusuallya'hidden'subdirectoryofthedirectorythatcontainsthefilebeingaccessed.Setto"."tolookinthesamedirectoryasthefile:
MetaDir.
Or,tosetittoasubdirectoryofthedirectorycontainingthefiles:
MetaDir.meta
MetaFiles
ActivatesCERNmeta-fileprocessingMetaFileson|off
MetaFilesoff
serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_cern_meta
Turnson/offMetafileprocessingonaper-directorybasis.
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006124|
Apachemod_cgi
MPM(prefork)CGI(B)cgi_modulemod_cgi.c
MIMEapplication/x-httpd-cgicgi-scriptCGICGIAddType ScriptAlias
CGIDOCUMENT_ROOT DocumentRoot
ApacheCGI CGI
UNIXMPM mod_cgid
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
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
ScriptLog
CGIScriptLogfile-path
serverconfig,virtualhost(B)mod_cgi,mod_cgid
ScriptLogCGI ScriptLogCGI ServerRoot
ScriptLoglogs/cgi_log
User
CGI
ScriptLogBuffer
PUTPOSTScriptLogBufferbytes
ScriptLogBuffer1024
serverconfig,virtualhost(B)mod_cgi,mod_cgid
PUTPOST1024
||||
ScriptLogLength
()ScriptLogLengthbytes
ScriptLogLength10385760
serverconfig,virtualhost(B)mod_cgi,mod_cgid
ScriptLogLengthCGICGI()CGI
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006124|
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
||||
ScriptSock
CGIScriptSockfile-path
ScriptSocklogs/cgisock
serverconfig,virtualhost(B)mod_cgid
CGI(PID)Apache(root)CGI
ScriptSock/var/run/cgid.sock
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
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.
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>
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.
||||
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_dav
ApacheDAV(E)dav_modulemod_dav.c
Thismoduleprovidesclass1andclass2WebDAV('Web-basedDistributedAuthoringandVersioning')functionalityforApache.ThisextensiontotheHTTPprotocolallowscreating,moving,copying,anddeletingresourcesandcollectionsonaremotewebserver.
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
AuthUserFileuser.passwd
<LimitExceptGETOPTIONS>
requireuseradmin
</LimitExcept>
</Location>
mod_davisadescendentofGregStein'smod_davforApache1.3.Moreinformationaboutthemoduleisavailablefromthatsite.
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.
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.
Dav
EnableWebDAVHTTPmethodsDavOn|Off|provider-name
DavOff
directory(E)mod_dav
UsetheDavdirectivetoenabletheWebDAVHTTPmethodsforthegivencontainer:
<Location/foo>
DavOn
</Location>
ThevalueOnisactuallyanaliasforthedefaultproviderfilesystemwhichisservedbythemod_dav_fsmodule.Note,thatonceyouhaveDAVenabledforsomelocation,itcannotbedisabledforsublocations.Foracompleteconfigurationexamplehavealookatthesectionabove.
DonotenableWebDAVuntilyouhavesecuredyourserver.Otherwiseeveryonewillbeabletodistributefilesonyoursystem.
DavDepthInfinity
AllowPROPFIND,Depth:InfinityrequestsDavDepthInfinityon|off
DavDepthInfinityoff
serverconfig,virtualhost,directory(E)mod_dav
UsetheDavDepthInfinitydirectivetoallowtheprocessingofPROPFINDrequestscontainingtheheader'Depth:Infinity'.Becausethistypeofrequestcouldconstituteadenial-of-serviceattack,bydefaultitisnotallowed.
||||
DavMinTimeout
MinimumamountoftimetheserverholdsalockonaDAVresourceDavMinTimeoutseconds
DavMinTimeout0
serverconfig,virtualhost,directory(E)mod_dav
WhenaclientrequestsaDAVresourcelock,itcanalsospecifyatimewhenthelockwillbeautomaticallyremovedbytheserver.Thisvalueisonlyarequest,andtheservercanignoreitorinformtheclientofanarbitraryvalue.
UsetheDavMinTimeoutdirectivetospecify,inseconds,theminimumlocktimeouttoreturntoaclient.MicrosoftWebFoldersdefaultstoatimeoutof120seconds;theDavMinTimeoutcanoverridethistoahighervalue(like600seconds)toreducethechanceoftheclientlosingthelockduetonetworklatency.
<Location/MSWord>
DavMinTimeout600
</Location>
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_dav_fs
mod_dav
(E)dav_fs_modulemod_dav_fs.c
Thismodulerequirestheserviceofmod_dav.Itactsasasupportmoduleformod_davandprovidesaccesstoresourceslocatedintheserver'sfilesystem.Theformalnameofthisproviderisfilesystem.mod_davbackendproviderswillbeinvokedbyusingtheDavdirective:
Davfilesystem
Sincefilesystemisthedefaultproviderformod_dav,youmaysimplyusethevalueOninstead.
||||
DavLockDB
LocationoftheDAVlockdatabaseDavLockDBfile-path
serverconfig,virtualhost(E)mod_dav_fs
UsetheDavLockDBdirectivetospecifythefullpathtothelockdatabase,excludinganextension.Ifthepathisnotabsolute,itwillbetakenrelativetoServerRoot.Theimplementationofmod_dav_fsusesaSDBMdatabasetotrackuserlocks.
DavLockDBvar/DavLock
ThedirectorycontainingthelockdatabasefilemustbewritablebytheUserGroupunderwhichApacheisrunning.Forsecurityreasons,youshouldcreateadirectoryforthispurposeratherthanchangingthepermissionsonanexistingdirectory.Intheaboveexample,Apachewillcreatefilesinthevar/directoryundertheServerRootwiththebasefilenameDavLockandextensionnamechosenbytheserver.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
||||
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_dbd
SQL(E)dbd_modulemod_dbd.cVersion2.1
mod_dbdmanagesSQLdatabaseconnectionsusingapr_dbd.ItprovidesdatabaseconnectionsonrequesttomodulesrequiringSQLdatabasefunctions,andtakescareofmanagingdatabaseswithoptimalefficiencyandscalabilityforboththreadedandnon-threadedMPMs.
ConnectionPooling
Thismodulemanagesdatabaseconnections,inamanneroptimisedfortheplatform.Onnon-threadedplatforms,itprovidesapersistentconnectioninthemannerofclassicLAMP(Linux,Apache,Mysql,Perl/PHP/Python).Onthreadedplatform,itprovidesanaltogethermorescalableandefficientconnectionpool,asdescribedinthisarticleatApacheTutor.mod_dbdsupersedesthemodulespresentedinthatarticle.
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*));
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*));
SQLPreparedStatements
mod_dbdsupportsSQLpreparedstatementsonbehalfofmodulesthatmaywishtousethem.Eachpreparedstatementmustbeassignedaname(label),andtheyarestoredinahash:thepreparedfieldofanap_dbd_t.Hashentriesareoftypeapr_dbd_prepared_tandcanbeusedinanyoftheapr_dbdpreparedstatementSQLqueryorselectcommands.
Itisuptodbdusermodulestousethepreparedstatementsanddocumentwhatstatementscanbespecifiedinhttpd.conf,ortoprovidetheirowndirectivesanduseap_dbd_prepare.
DBDExptime
KeepalivetimeforidleconnectionsDBDExptimetime-in-seconds
serverconfig,virtualhost(E)mod_dbd
SetthetimetokeepidleconnectionsalivewherethenumberofconnectionsspecifiedinDBDKeephasbeenexceeded(threadedplatformsonly).
DBDKeep
MaximumsustainednumberofconnectionsDBDKeepnumber
serverconfig,virtualhost(E)mod_dbd
Setthemaximumnumberofconnectionsperprocesstobesustained,otherthanforhandlingpeakdemand(threadedplatformsonly).
DBDMax
MaximumnumberofconnectionsDBDMaxnumber
serverconfig,virtualhost(E)mod_dbd
Setthehardmaximumnumberofconnectionsperprocess(threadedplatformsonly).
DBDMin
MinimumnumberofconnectionsDBDMinnumber
serverconfig,virtualhost(E)mod_dbd
Settheminimumnumberofconnectionsperprocess(threadedplatformsonly).
DBDParams
ParametersfordatabaseconnectionDBDParamsparam1=value1[,param2=value2]
serverconfig,virtualhost(E)mod_dbd
Asrequiredbytheunderlyingdriver.Typicallythiswillbeusedtopasswhatevercannotbedefaultedamongstusername,password,databasename,hostnameandportnumberforconnection.
DBDPersist
WhethertousepersistentconnectionsDBDPersist0|1
serverconfig,virtualhost(E)mod_dbd
Ifsetto0,persistentandpooledconnectionsaredisabled.Anewdatabaseconnectionisopenedwhenrequestedbyaclient,andclosedimmediatelyonrelease.Thisoptionisfordebuggingandlow-usageservers.
Thedefaultistoenableapoolofpersistentconnections(orasingleLAMP-stylepersistentconnectioninthecaseofanon-threadedserver),andshouldalmostalwaysbeusedinoperation.
DBDPrepareSQL
DefineanSQLpreparedstatementDBDPrepareSQL"SQLstatement"label
serverconfig,virtualhost(E)mod_dbd
FormodulessuchasauthenticationthatuserepeatedlyuseasingleSQLstatement,optimumperformanceisachievedbypreparingthestatementatstartupratherthaneverytimeitisused.ThisdirectivepreparesanSQLstatementandassignsitalabel.
||||
DBDriver
SpecifyanSQLdriverDBDrivername
serverconfig,virtualhost(E)mod_dbd
Selectsanapr_dbddriverbyname.Thedrivermustbeinstalledonyoursystem(onmostsystems,itwillbeasharedobjectordll).Forexample,DBDrivermysqlwillselecttheMySQLdriverinapr_dbd_mysql.so.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006125|
Apachemod_deflate
(E)deflate_modulemod_deflate.c
mod_deflateDEFLATE
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>
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"
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
mod_deflate" Vary:Accept-Encoding"HTTP" Accept-
Encoding"
( User-Agent) Vary DEFLATEUser-Agent
HeaderappendVaryUser-Agent
(HTTP) Vary" *"
HeadersetVary*
DeflateBufferSize
zlib()DeflateBufferSizevalue
DeflateBufferSize8096
serverconfig,virtualhost(E)mod_deflate
DeflateBufferSizezlib
DeflateCompressionLevel
DeflateCompressionLevelvalue
Zlib
serverconfig,virtualhost(E)mod_deflateApache2.0.45
DeflateCompressionLevelCPU
1()9()
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
LogFormat'"%r"%{outstream}n/%{instream}n(%
{ratio}n%%)'deflate
CustomLoglogs/deflate_logdeflate
mod_log_config
DeflateMemLevel
zlibDeflateMemLevelvalue
DeflateMemLevel9
serverconfig,virtualhost(E)mod_deflate
DeflateMemLevelzlib(19)
||||
DeflateWindowSize
Zlib(compressionwindow)DeflateWindowSizevalue
DeflateWindowSize15
serverconfig,virtualhost(E)mod_deflate
DeflateWindowSizezlib(compressionwindow)(115)
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006125|
Apachemod_dir
""(B)dir_modulemod_dir.c
index.htmlmod_dirDirectoryIndexmod_autoindex
"/" http://servername/foo/dirname dirname
mod_dir http://servername/foo/dirname/
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
||||
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 "/"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_disk_cache
(E)disk_cache_modulemod_disk_cache.c
mod_disk_cacheimplementsadiskbasedstoragemanager.Itisprimarilyofuseinconjunctionmod_cache.
ContentisstoredinandretrievedfromthecacheusingURIbasedkeys.Contentwithaccessprotectionisnotcached.
htcachecleancanbeusedtomaintainthecachesizeatamaximumlevel.
mod_disk_cacherequirestheservicesofmod_cache.
CacheDirLength
ThenumberofcharactersinsubdirectorynamesCacheDirLengthlength
CacheDirLength2
serverconfig,virtualhost(E)mod_disk_cache
CacheDirLengthdirectivesetsthenumberofcharactersforeachsubdirectorynameinthecachehierarchy.
TheresultofCacheDirLevels*CacheDirLengthmustnotbehigherthan20.
CacheDirLength4
CacheDirLevels
Thenumberoflevelsofsubdirectoriesinthecache.CacheDirLevelslevels
CacheDirLevels3
serverconfig,virtualhost(E)mod_disk_cache
CacheDirLevelsdirectivesetsthenumberofsubdirectorylevelsinthecache.CacheddatawillbesavedthismanydirectorylevelsbelowtheCacheRootdirectory.
TheresultofCacheDirLevels*CacheDirLengthmustnotbehigherthan20.
CacheDirLevels5
CacheMaxFileSize
Themaximumsize(inbytes)ofadocumenttobeplacedinthecacheCacheMaxFileSizebytes
CacheMaxFileSize1000000
serverconfig,virtualhost(E)mod_disk_cache
CacheMaxFileSizedirectivesetsthemaximumsize,inbytes,foradocumenttobeconsideredforstorageinthecache.
CacheMaxFileSize64000
CacheMinFileSize
Theminimumsize(inbytes)ofadocumenttobeplacedinthecacheCacheMinFileSizebytes
CacheMinFileSize1
serverconfig,virtualhost(E)mod_disk_cache
CacheMinFileSizedirectivesetstheminimumsize,inbytes,foradocumenttobeconsideredforstorageinthecache.
CacheMinFileSize64
||||
CacheRoot
ThedirectoryrootunderwhichcachefilesarestoredCacheRootdirectory
serverconfig,virtualhost(E)mod_disk_cache
CacheRootdirectivedefinesthenameofthedirectoryonthedisktocontaincachefiles.Ifthemod_disk_cachemodulehasbeenloadedorcompiledintotheApacheserver,thisdirectivemustbedefined.FailingtoprovideavalueforCacheRootwillresultinaconfigurationfileprocessingerror.TheCacheDirLevelsCacheDirLengthdirectivesdefinethestructureofthedirectoriesunderthespecifiedrootdirectory.
CacheRootc:/cacheroot
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006125|
Apachemod_dumpio
I/O(E)dumpio_modulemod_dumpio.c
mod_dumpioApache(error.log)
SSL()SSL()
dumpio
DumpIOInput
DumpIOInputOn|Off
DumpIOInputOff
serverconfig(E)mod_dumpioApache2.1.3
DumpIOInputOn
||||
DumpIOOutput
DumpIOOutputOn|Off
DumpIOOutputOff
serverconfig(E)mod_dumpioApache2.1.3
DumpIOOutputOn
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_echo
(X)echo_modulemod_echo.cApache2.0
Thismoduleprovidesanexampleprotocolmoduletoillustratetheconcept.Itprovidesasimpleechoserver.Telnettoitandtypestuff,anditwillechoit.
||||
ProtocolEcho
TurntheechoserveronoroffProtocolEchoOn|Off
serverconfig,virtualhost(X)mod_echoProtocolEchoisonlyavailablein2.0
ProtocolEchodirectiveenablesordisablestheechoserver.
ProtocolEchoOn
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006125|
Apachemod_env
ApacheCGISSI(B)env_modulemod_env.c
CGISSI httpdshell(set)(unset)
PassEnv
shellPassEnvenv-variable[env-variable]...
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_env
httpdshellCGISSI
PassEnvLD_LIBRARY_PATH
SetEnv
SetEnvenv-variablevalue
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_env
CGISSI
SetEnvSPECIAL_PATH/foo/bin
||||
UnsetEnv
UnsetEnvenv-variable[env-variable]...
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_env
CGISSI
UnsetEnvLD_LIBRARY_PATH
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
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
Usingthemod_exampleModule
Toactivatetheexamplemodule,includeablocksimilartothefollowinginyourhttpd.conffile:
<Location/example-info>
SetHandlerexample-handler
</Location>
Asanalternative,youcanputthefollowingintoa.htaccessfileandthenrequestthefile"test.example"fromthatlocation:
AddHandlerexample-handler.example
Afterreloading/restartingyourserver,youshouldbeabletobrowsetothislocationandseethebriefdisplaymentionedearlier.
||||
Example
DemonstrationdirectivetoillustratetheApachemoduleAPIExample
serverconfig,virtualhost,directory,.htaccess(X)mod_example
Exampledirectivejustsetsademonstrationflagwhichtheexamplemodule'scontenthandlerdisplays.Ittakesnoarguments.IfyoubrowsetoanURLtowhichtheexamplecontent-handlerapplies,youwillgetadisplayoftheroutineswithinthemoduleandhowandinwhatordertheywerecalledtoservicethedocumentrequest.Theeffectofthisdirectiveonecanobserveunderthepoint"Exampledirectivedeclaredhere:YES/NO".
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006125|
Apachemod_expires
HTTP" Expires"" Cache-Control"(E)expires_modulemod_expires.c
ExpiresCache-Controlmax-age(expirationdate)
HTTP()
Cache-Controlmax-age( RFC2616section14.9) Header
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"
"Expires:" ""
ExpiresActive
" Expires:"" Cache-Control:"ExpiresActiveOn|Off
serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_expires
ExpiresCache-Control OffExpiresCache-Control(.htaccess) OnExpiresByTypeExpiresDefault
ExpiresCache-Control
ExpiresCache-Control
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
||||
ExpiresDefault
ExpiresDefault<code>seconds
serverconfig,virtualhost,directory,.htaccessIndexes(E)mod_expires
ExpiresByTypeMIME ExpiresByTypealternatesyntax
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
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
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
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.
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);
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
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.
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
||||
mod_ext_filter.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
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
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
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
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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).
SmartFiltering
Inthetraditionalfilteringmodel,filtersareinsertedunconditionallyusingAddOutputFilterandfamily.Eachfilterthenneedstodeterminewhethertorun,andthereislittleflexibilityavailableforserveradminstoallowthechaintobeconfigureddynamically.
mod_filterbycontrastgivesserveradministratorsagreatdealofflexibilityinconfiguringthefilterchain.Infact,filterscanbeinsertedbasedonanyRequestHeader,ResponseHeaderorEnvironmentVariable.ThisgeneralisesthelimitedflexibilityofferedbyAddOutputFilterByType,andfixesittoworkcorrectlywithdynamiccontent,regardlessofthecontentgenerator.TheabilitytodispatchbasedonEnvironmentVariablesoffersthefullflexibilityofconfigurationwithmod_rewritetoanyonewhoneedsit.
FilterDeclarations,ProvidersandChains
Figure1:Thetraditionalfiltermodel
Inthetraditionalmodel,outputfiltersareasimplechainfromthecontentgenerator(handler)totheclient.Thisworkswellprovidedthefilterchaincanbecorrectlyconfigured,butpresentsproblemswhenthefiltersneedtobeconfigureddynamicallybasedontheoutcomeofthehandler.
Figure2:Themod_filtermodel
mod_filterworksbyintroducingindirectionintothefilterchain.Insteadofinsertingfiltersinthechain,weinsertafilterharnesswhichinturndispatchesconditionallytoafilterprovider.Anycontentfiltermaybeusedasaprovidertomod_filter;nochangetoexistingfiltermodulesisrequired(althoughitmaybepossibletosimplifythem).Therecanbemultipleprovidersforonefilter,butnomorethanoneproviderwillrunforanysinglerequest.
Afilterchaincomprisesanynumberofinstancesofthefilterharness,eachofwhichmayhaveanynumberofproviders.Aspecialcaseisthatofasingleproviderwithunconditionaldispatch:thisisequivalenttoinsertingtheproviderfilterdirectlyintothechain.
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.
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
$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>
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.
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
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.
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.
cache=no
Thefilterrenderstheoutputuncacheable(egbyintroducingrandomisedcontentchanges)
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:
Character Description(none) exactmatch$ substringmatch/ regexmatch(delimitedbyasecond/)= integerequality< integerless-than<= integerless-thanorequal> integergreater-than>= integergreater-thanorequal* Unconditionalmatch
||||
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006125|
Apachemod_headers
HTTP(E)headers_modulemod_headers.cRequestHeaderApache2.0
HTTP
mod_headers
RequestHeaderappendMirrorID"mirror12"
RequestHeaderunsetMirrorID
MirrorID MirrorID"mirror12"
mod_headers""[whenRequestHeadersaresetimmediatelybeforerunningthecontentgeneratorandResponseHeadersjustastheresponseissentdownthewire.]""
""/ early""
""URL"" <Directory><Location>
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"
MyHeader:D=3775428t=991424704447256mytext
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
%% (%)
%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
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006126|
Apachemod_ident
RFC1413ident(E)ident_modulemod_ident.cApache2.1
RFC1413
IdentityCheck
RFC1413IdentityCheckOn|Off
IdentityCheckOff
serverconfig,virtualhost,directory(E)mod_identApache2.1
identd RFC1413(" %l")
IdentityCheckTimeout
||||
IdentityCheckTimeout
identIdentityCheckTimeoutseconds
IdentityCheckTimeout30
serverconfig,virtualhost,directory(E)mod_ident
ident"30"() RFC1413
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
NewFeatures
Theimagemapmoduleaddssomenewfeaturesthatwerenotpossiblewithpreviouslydistributedimagemapprograms.
URLreferencesrelativetotheReferer:information.Default<base>assignmentthroughanewmapdirectivebase.Noneedforimagemap.conffile.Pointreferences.Configurablegenerationofimagemapmenus.
ImagemapFile
Thelinesintheimagemapfilescanhaveoneofseveralformats:
directivevalue[x,y...]
directivevalue"Menutext"[x,y...]
directivevaluex,y..."Menutext"
Thedirectiveisoneofbase,default,poly,circle,rect,orpoint.ThevalueisanabsoluteorrelativeURL,oroneofthespecialvalueslistedbelow.Thecoordinatesarex,ypairsseparatedbywhitespace.Thequotedtextisusedasthetextofthelinkifaimagemapmenuisgenerated.Linesbeginningwith'#'arecomments.
ImagemapFileDirectivesTherearesixdirectivesallowedintheimagemapfile.Thedirectivescancomeinanyorder,butareprocessedintheordertheyarefoundintheimagemapfile.
baseDirectiveHastheeffectof<basehref="value">.Thenon-absoluteURLsofthemap-filearetakenrelativetothisvalue.ThebasedirectiveoverridesImapBaseassetina.htaccessfileorintheserverconfigurationfiles.IntheabsenceofanImapBaseconfigurationdirective,basedefaultstohttp://server_name/.
base_uriissynonymouswithbase.NotethatatrailingslashontheURLissignificant.
defaultDirectiveTheactiontakenifthecoordinatesgivendonotfitanyofthepoly,circlerectdirectives,andtherearenopointdirectives.DefaultstonocontentintheabsenceofanImapDefaultconfigurationsetting,causingastatuscodeof
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.
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>
Ifyouwanttousedoublequoteswithinthistext,youhavetowritethemas".
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?"
Referencingyourmapfile
HTMLexample<ahref="/maps/imagemap1.map">
<imgismapsrc="/images/imagemap1.gif">
</a>
XHTMLexample<ahref="/maps/imagemap1.map">
<imgismap="ismap"src="/images/imagemap1.gif"
/>
</a>
ImapBase
DefaultbaseforimagemapfilesImapBasemap|referer|URL
ImapBasehttp://servername/
serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_imagemap
ImapBasedirectivesetsthedefaultbaseusedintheimagemapfiles.Itsvalueisoverriddenbyabasedirectivewithintheimagemapfile.Ifnotpresent,thebasedefaultstohttp://servername/.
UseCanonicalName
ImapDefault
DefaultactionwhenanimagemapiscalledwithcoordinatesthatarenotexplicitlymappedImapDefaulterror|nocontent|map|referer|URL
ImapDefaultnocontent
serverconfig,virtualhost,directory,.htaccessIndexes(B)mod_imagemap
ImapDefaultdirectivesetsthedefaultdefaultusedintheimagemapfiles.Itsvalueisoverriddenbyadefaultdirectivewithintheimagemapfile.Ifnotpresent,thedefaultactionisnocontent,whichmeansthata204NoContentissenttotheclient.Inthiscase,theclientshouldcontinuetodisplaytheoriginalpage.
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.
||||
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_include
(SSI)(B)include_modulemod_include.cImplementedasanoutputfiltersinceApache2.0
Thismoduleprovidesafilterwhichwillprocessfilesbeforetheyaresenttotheclient.TheprocessingiscontrolledbyspeciallyformattedSGMLcomments,referredtoaselements.Theseelementsallowconditionaltext,theinclusionofotherfilesorprograms,aswellasthesettingandprintingofenvironmentvariables.
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.
PATH_INFOwithServerSideIncludes
Filesprocessedforserver-sideincludesnolongeracceptrequestswithPATH_INFO(trailingpathnameinformation)bydefault.YoucanusetheAcceptPathInfodirectivetoconfiguretheservertoacceptrequestswithPATH_INFO.
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
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,
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).
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.
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
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
Thisprintsoutalistingofallexistingvariablesandtheirvalues.Specialcharactersareentityencoded(seetheechoelementfordetails)beforebeingoutput.Therearenoattributes.
<!--#printenv-->
ThesetElementThissetsthevalueofavariable.Attributes:
var
Thenameofthevariabletoset.
value
Thevaluetogiveavariable.
<!--#setvar="category"value="help"-->
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).
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-->
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.
<!--#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
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.
SSIEndTag
StringthatendsanincludeelementSSIEndTagtag
SSIEndTag"-->"
serverconfig,virtualhost(B)mod_includeApache2.0.30
Thisdirectivechangesthestringthatmod_includelooksfortomarktheendofanincludeelement.
SSIEndTag"%>"
SSIStartTag
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-->"
SSIStartTag
StringthatstartsanincludeelementSSIStartTagtag
SSIStartTag"<!--#"
serverconfig,virtualhost(B)mod_includeApache2.0.30
Thisdirectivechangesthestringthatmod_includelooksfortomarkanincludeelementtoprocess.
Youmaywanttousethisoptionifyouhave2serversparsingtheoutputofafileeachprocessingdifferentcommands(possiblyatdifferenttimes).
SSIStartTag"<%"
SSIEndTag"%>"
Theexamplegivenabove,whichalsospecifiesamatchingSSIEndTag,willallowyoutouseSSIdirectivesasshownintheexamplebelow:
SSIdirectiveswithalternatestartandendtags<%printenv%>
SSIEndTag
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".
SSIUndefinedEcho
StringdisplayedwhenanunsetvariableisechoedSSIUndefinedEchostring
SSIUndefinedEcho"(none)"
serverconfig,virtualhost,directory,.htaccessAll(B)mod_includeApache2.0.34
Thisdirectivechangesthestringthatmod_includedisplayswhenavariableisnotsetand"echoed".
SSIUndefinedEcho"<!--undef-->"
||||
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).
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006321|
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
mod_info .htaccess
/
mod_authz_host
<Location/server-info>
SetHandlerserver-info
Orderallow,deny
#
Allowfrom127.0.0.1
#
Allowfrom192.168.1.17
</Location>
server-info http://your.host.example.com/server-
info?config
?<module-name>
?config
?hooks
(Hook)
?list
?server
mod_info
ServerRoot,LoadModule,LoadFileInclude,<IfModule>,<IfDefine> Include
.htaccess
mod_info</Directory>
( mod_ssl)
||||
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>'
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006126|
Apachemod_isapi
WindowsISAPI(B)isapi_modulemod_isapi.cWin32
(InternetServerextensionAPI)WindowsApache(ISAPI)
ISAPI(.dll)ApacheISAPIISAPI Apache
AddHandlerisapi-isaISAPI.dllISAPIhttpd.conf
AddHandlerisapi-isa.dll
Apachehttpd.confApache
ISAPICacheFilec:/WebWork/Scripts/ISAPI/mytest.dll
ISAPIISAPICGIISAPI" OptionsExecCGI"
mod_isapiISAPI
ApacheISAPII/O(Microsoft-specific)ISAPI2.0ApacheI/OISAPIISAPII/O"
IISISAPIApacheISAPI ISAPICacheFile
ApacheISAPIApache
ApacheISAPI ISAPIISAPI
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
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
ISAPIAppendLogToErrors
ISAPIHSE_APPEND_LOG_PARAMETERISAPIAppendLogToErrorson|off
ISAPIAppendLogToErrorsoff
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi
ISAPIHSE_APPEND_LOG_PARAMETER
ISAPIAppendLogToQuery
ISAPIHSE_APPEND_LOG_PARAMETERISAPIAppendLogToQueryon|off
ISAPIAppendLogToQueryon
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi
ISAPIHSE_APPEND_LOG_PARAMETER( CustomLog%q)
ISAPICacheFile
ISAPIISAPICacheFilefile-path[file-path]...
serverconfig,virtualhost(B)mod_isapi
ApacheISAPI ServerRoot
ISAPIFakeAsync
ISAPIISAPIFakeAsyncon|off
ISAPIFakeAsyncoff
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi
onISAPI
ISAPILogNotSupported
ISAPIISAPILogNotSupportedon|off
ISAPILogNotSupportedoff
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi
ISAPIonISAPIOff
||||
ISAPIReadAheadBuffer
ISAPIISAPIReadAheadBuffersize
ISAPIReadAheadBuffer49152
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_isapi
ISAPI ReadClientISAPI ReadClientISAPI
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |???|
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
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>
LDAP
LDAPLDAPunbind->connect->rebindHTTPKeep-Alives
LDAPLDAPApache
ApacheLDAP
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
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
requirevalid-user
</Location>
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>
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
[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
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.
LDAPCacheEntries
LDAPLDAPCacheEntriesnumber
LDAPCacheEntries1024
serverconfig(E)mod_ldap
LDAPsearch/bind0search/bind1024
LDAPCacheTTL
search/bindLDAPCacheTTLseconds
LDAPCacheTTL600
serverconfig(E)mod_ldap
search/bind600(10)
LDAPConnectionTimeout
LDAPConnectionTimeoutseconds
serverconfig(E)mod_ldap
Specifiesthetimeoutvalue(inseconds)inwhichthemodulewillattempttoconnecttotheLDAPserver.Ifaconnectionisnotsuccessfulwiththetimeoutperiod,eitheranerrorwillbereturnedorthemodulewillattempttoconnecttoasecondaryLDAPserverifoneisspecified.Thedefaultis10seconds.
LDAPOpCacheEntries
LDAPcompareLDAPOpCacheEntriesnumber
LDAPOpCacheEntries1024
serverconfig(E)mod_ldap
mod_ldapLDAPcompare10240
LDAPOpCacheTTL
LDAPOpCacheTTLseconds
LDAPOpCacheTTL600
serverconfig(E)mod_ldap
600
LDAPSharedCacheFile
LDAPSharedCacheFiledirectory-path/filename
serverconfig(E)mod_ldap
()
LDAPSharedCacheSize
LDAPSharedCacheSizebytes
LDAPSharedCacheSize102400
serverconfig(E)mod_ldap
Byte100KB
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
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)
KEY_DER-binaryDERencodedprivatekeyKEY_BASE64-PEMencodedprivatekeyKEY_PFX-PKCS#12encodedprivatekey(NovellSDK)
LDAPTrustedMode
SpecifiestheSSL/TLSmodetobeusedwhenconnectingtoanLDAPserver.LDAPTrustedModetype
serverconfig,virtualhost,directory,.htaccess(E)mod_ldap
Thefollowingmodesaresupported:
NONE-noencryptionSSL-ldaps://encryptionondefaultport636TLS-STARTTLSencryptionondefaultport389
NotallLDAPtoolkitssupportalltheabovemodes.Anerrormessagewillbeloggedatruntimeifamodeisnotsupported,andtheconnectiontotheLDAPserverwillfail.
Ifanldaps://URLisspecified,themodebecomesSSLandthesettingofLDAPTrustedModeisignored.
||||
LDAPVerifyServerCert
ForceservercertificateverificationLDAPVerifyServerCertOn|Off
LDAPVerifyServerCertOn
serverconfig(E)mod_ldap
SpecifieswhethertoforcetheverificationofaservercertificatewhenestablishinganSSLconnectiontotheLDAPserver.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006126|
Apachemod_log_config
(B)log_config_modulemod_log_config.c
TransferLog LogFormat CustomLog
TransferLogCustomLog
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)
%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
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"
Apache
BufferedLogs
BufferedLogsOn|Off
BufferedLogsOff
serverconfig(B)mod_log_configApache2.0.41
BufferedLogsmod_log_config
CookieLog
cookiesCookieLogfilename
serverconfig,virtualhost(B)mod_log_config
CookieLogcookies ServerRoot mod_cookies
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
#
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
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
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
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.
SecurityConsiderations
Seethesecuritytipsdocumentfordetailsonwhyyoursecuritycouldbecompromisedifthedirectorywherelogfilesarestorediswritablebyanyoneotherthantheuserthatstartstheserver.
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
||||
betakentomakesurethatonlyforwardslashedareusedeventhoughtheplatformmayallowtheuseofbackslashes.Ingeneralitisagoodideatoalwaysuseforwardslashesthroughouttheconfigurationfiles.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006126|
Apachemod_logio
/HTTP(E)logio_modulemod_logio.c
/SSL/TLSSSL/TLS
mod_log_config
||||
" %"
%I
%O
I/O"%h%l%u%t\"%r\"%>s%b\"%{Referer}i\"\"%
{User-agent}i\"%I%O"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006126|
Apachemod_mem_cache
(E)mem_cache_modulemod_mem_cache.c
mod_cache mod_cache mod_mem_cache
mod_mem_cache mod_proxyProxyPass( )
URI
MCacheMaxObjectCount
MCacheMaxObjectCountvalue
MCacheMaxObjectCount1009
serverconfig(E)mod_mem_cache
MCacheMaxObjectCount
MCacheRemovalAlgorithm
MCacheMaxObjectCount13001
MCacheMaxObjectSize
()MCacheMaxObjectSizebytes
MCacheMaxObjectSize10000
serverconfig(E)mod_mem_cache
MCacheMaxObjectSize(Byte)
MCacheMaxObjectSize6400000
MCacheMaxObjectSizeMCacheMinObjectSize
MCacheMaxStreamingBuffer
MCacheMaxStreamingBuffersize_in_bytes
MCacheMaxStreamingBuffer100000MCacheMaxObjectSize
serverconfig(E)mod_mem_cache
MCacheMaxStreamingBuffer Content-LengthCGIContent-Length MCacheMaxStreamingBuffer
Content-Length
MCacheMaxStreamingBuffer mod_mem_cache
#64KB
MCacheMaxStreamingBuffer65536
MCacheMinObjectSize
()MCacheMinObjectSizebytes
MCacheMinObjectSize0
serverconfig(E)mod_mem_cache
MCacheMinObjectSize
MCacheMinObjectSize10000
MCacheRemovalAlgorithm
MCacheRemovalAlgorithmLRU|GDSF
MCacheRemovalAlgorithmGDSF
serverconfig(E)mod_mem_cache
MCacheRemovalAlgorithm
LRU()LRU
GDSF(GreadyDual-Size)GDSF
MCacheRemovalAlgorithmGDSF
MCacheRemovalAlgorithmLRU
||||
MCacheSize
KBMCacheSizeKBytes
MCacheSize100
serverconfig(E)mod_mem_cache
MCacheSizeKB(1024-byte)MCacheRemovalAlgorithm
MCacheSize700000
MCacheSizeMCacheMaxObjectSize
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006127|
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()""()
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
MIME gzip pgpUUencodingUUencodingASCII()
HTTP/1.1RFC14.11
"Content-Encoding""Content-Type""Content-Encoding"
( )
MicrosoftWord .docMicrosoftWord .zippkzipResume.doc.zippkzipWord
ApacheContent-encoding
Content-encoding:pkzip
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
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
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
AddHandler
AddHandlerhandler-nameextension[extension]...
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mime
extensionhandler-name extension .cgiCGI
AddHandlercgi-script.cgi
http.conf .cgiCGI
extension
SetHandler
AddInputFilter
AddInputFilterfilter[;filter...]extension
[extension]...
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.26
AddInputFilterextension SetInputFilter extension
filterextension extension
RemoveInputFilter
SetInputFilter
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
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
AddType
AddTypeMIME-typeextension[extension]...
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mime
AddType MIME-typeextension extension( TypesConfig)
AddTypeimage/gif.gif
AddType TypesConfig
extension
DefaultType
ForceType
DefaultLanguage
DefaultLanguageMIME-lang
serverconfig,virtualhost,directory,.htaccessFileInfo(B)mod_mime
DefaultLanguageApache( <Directory>)(AddLanguage.fr.de) MIME-lang
DefaultLanguage
DefaultLanguageAddLanguage
DefaultLanguageen
mod_negotiation
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
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
RemoveCharset
RemoveCharsetextension[extension]...
virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.24
RemoveCharset .htaccess
extension
RemoveCharset.html.shtml
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
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
RemoveInputFilter
RemoveInputFilterextension[extension]...
virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.26
RemoveInputFilter .htaccess
extension
AddInputFilter
SetInputFilter
RemoveLanguage
RemoveLanguageextension[extension]...
virtualhost,directory,.htaccessFileInfo(B)mod_mimeApache2.0.24
RemoveLanguage .htaccess
extension
RemoveOutputFilter
RemoveOutputFilterextension[extension]...
virtualhost,directory,.htaccessFileInfo(B)mod_mime2.0.26
RemoveOutputFilter .htaccess
extension
RemoveOutputFiltershtml
AddOutputFilter
RemoveType
RemoveTypeextension[extension]...
virtualhost,directory,.htaccessFileInfo(B)mod_mime
RemoveType .htaccess
/foo/.htaccessRemoveType.cgi
/foo/.cgi DefaultType
RemoveTypeAddType RemoveTypeAddType
extension
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006127|
Apachemod_mime_magic
MIME(E)mime_magic_modulemod_mime_magic.c
Unixfile(1) MIMEmod_mime""
Unixfile(1)"Magic""Magic" MimeMagicFile
"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
>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
web
file(1)webweb""
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
||||
MimeMagicFile
MagicMIMEMimeMagicFilefile-path
serverconfig,virtualhost(E)mod_mime_magic
MimeMagicFileMagic conf/magic ServerRoot
MimeMagicFileconf/magic
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006128|
Apachemod_negotiation
(B)negotiation_modulemod_negotiation.c
""
( type-map)"MultiViews"( OptionsMultiViews)
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>
----xyz----
MultiViews
MultiViewsOptionsMultiViews /some/dir/foo
/some/dir/foo foo.* foo.*
MultiViewsMatchApache
CacheNegotiatedDocs
CacheNegotiatedDocsOn|Off
CacheNegotiatedDocsOff
serverconfig,virtualhost(B)mod_negotiation2.0
"On"
HTTP/1.0HTTP/1.1HTTP/1.1
2.0 CacheNegotiatedDocs
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
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006128|
Apachemod_nw_ssl
NetWareSSL(B)nwssl_modulemod_nw_ssl.cNetWare
(port)SSLNetWareSSL
NWSSLTrustedCerts
NWSSLTrustedCertsfilename[filename]...
serverconfig(B)mod_nw_ssl
(DER)SSL .der
NWSSLUpgradeable
SSLNWSSLUpgradeable[IP-address:]portnumber
serverconfig(B)mod_nw_ssl
/SSL/ Listen
||||
SecureListen
SSLSecureListen[IP-address:]portnumberCertificate-
Name[MUTUAL]
serverconfig(B)mod_nw_ssl
SSLeDirectorymutual
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |???|
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
Apache(forward)(reverse)
(originserver)()
Internet( mod_cache)
ProxyRequests
(name-space)()
InternetURLwebwebURL
ProxyPass( RewriteRule[P]) ProxyRequests
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
<Proxy>
<Proxy*>
OrderDeny,Allow
Denyfromall
Allowfrom192.168.0
</Proxy>
mod_authz_host
( ProxyRequests)(" ProxyRequestsOff"ProxyPass)
ProxyBlockIP
Apache( ProxyRemote) NoProxy
WWW"http://somehost/" http://somehost.example.com/
ProxyDomain
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>
(POST)HTTP(chunkedtransferencoding) Content-Length
mod_proxy_httpContent-Length proxy-
sendclContent-Length proxy-sendchunked
AllowCONNECT
CONNECT
AllowCONNECTport[port]...
AllowCONNECT443563
serverconfig,virtualhost(E)mod_proxy
AllowCONNECTCONNECT https http
https(443)snews(563) AllowCONNECT
mod_proxy_connect CONNECT
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
" 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
<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>
ProxyBadHeader
ProxyBadHeaderIsError|Ignore|StartBody
ProxyBadHeaderIsError
serverconfig,virtualhost(E)mod_proxyApache2.0.44
ProxyBadHeadermod_proxy((:))
IsError
"502"(BadGateway)
Ignore
StartBody
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*
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
ProxyErrorOverride
ProxyErrorOverrideOn|Off
ProxyErrorOverrideOff
serverconfig,virtualhost(E)mod_proxyApache2.0
( mod_includeSSI)("On"SSI)
ProxyIOBufferSize
ProxyIOBufferSizebytes
ProxyIOBufferSize8192
serverconfig,virtualhost(E)mod_proxy
ProxyIOBufferSize() 8192
<ProxyMatch>
<ProxyMatchregex>...</ProxyMatch>
serverconfig,virtualhost(E)mod_proxy
<ProxyMatch><Proxy>
ProxyMaxForwards
ProxyMaxForwardsnumber
ProxyMaxForwards10
serverconfig,virtualhost(E)mod_proxyApache2.0
ProxyMaxForwardsDoS
ProxyMaxForwards15
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
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.
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
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.
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.
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
<Location> <Location>
ProxyPassReverseCookieDomain
AdjuststheDomainstringinSet-Cookieheadersfromareverse-proxiedserverProxyPassReverseCookieDomaininternal-domain
public-domain
serverconfig,virtualhost,directory(E)mod_proxy
UsageisbasicallysimilartoProxyPassReverse,butinsteadofrewritingheadersthatareaURL,thisrewritesthedomainstringinSet-Cookieheaders.
ProxyPassReverseCookiePath
AdjuststhePathstringinSet-Cookieheadersfromareverse-proxiedserverProxyPassReverseCookiePathinternal-pathpublic-
path
serverconfig,virtualhost,directory(E)mod_proxy
UsageisbasicallysimilartoProxyPassReverse,butinsteadofrewritingheadersthatareaURL,thisrewritesthepathstringinSet-Cookieheaders.
ProxyPreserveHost
HTTPProxyPreserveHostOn|Off
ProxyPreserveHostOff
serverconfig,virtualhost(E)mod_proxyApache2.0.31
"Host:" ProxyPass
OffItismostly usefulinspecialconfigurationslikeproxiedmassname-basedvirtualhosting,wheretheoriginalHostheaderneedstobeevaluatedbythebackendserver.
ProxyReceiveBufferSize
HTTPFTP()ProxyReceiveBufferSizebytes
ProxyReceiveBufferSize0
serverconfig,virtualhost(E)mod_proxy
ProxyReceiveBufferSizeHTTPFTP(TCP/IP) 512" 0"
ProxyReceiveBufferSize2048
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
ProxyRemoteMatch
ProxyRemoteMatchregexremote-server
serverconfig,virtualhost(E)mod_proxy
ProxyRemoteMatchProxyRemoteURL
ProxyRequests
()ProxyRequestsOn|Off
ProxyRequestsOff
serverconfig,virtualhost(E)mod_proxy
Apache( OffProxyPass)
Off
HTTPFTP mod_proxy_httpmod_proxy_ftp
ProxyRequests
ProxyTimeout
ProxyTimeoutseconds
ProxyTimeout300
serverconfig,virtualhost(E)mod_proxyApache2.0.31
/
||||
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:"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_proxy_ajp
mod_proxyApacheJServProtocol(E)proxy_ajp_moduleproxy_ajp.cApache2.1
Thismodulerequirestheserviceofmod_proxy.ItprovidessupportfortheApacheJServProtocolversion1.3(hereafterAJP13).
Thus,inordertogettheabilityofhandlingAJP13protocol,mod_proxymod_proxy_ajphavetobepresentintheserver.
Internet
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
Sendasetofheadersbacktothebrowser.SEND_BODY_CHUNKSendachunkofbodydatabacktothebrowser.GET_BODY_CHUNKGetfurtherdatafromtherequestifithasn'tallbeentransferredyet.Thisisnecessarybecausethepacketshaveafixedmaximumsizeandarbitraryamountsofdatacanbeincludedthebodyofarequest(foruploadedfiles,forexample).(Note:thisisunrelatedtoHTTPchunkedtranfer).END_RESPONSEFinishtherequest-handlingcycle.
Eachmessageisaccompaniedbyadifferentlyformattedpacketofdata.SeeResponsePacketStructuresbelowfordetails.
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
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:
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
Chunk beentransferredyet.9 CPong
ReplyThereplytoaCPingrequest
Eachoftheabovemessageshasadifferentinternalstructure,detailedbelow.
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)
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
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):
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.
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,
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.
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
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.
||||
GetBodyChunkThecontainerasksformoredatafromtherequest(Ifthebodywastoolargetofitinthefirstpacketsentoverorwhentherequestischuncked).Theserverwillsendabodypacketbackwithanamountofdatawhichistheminimumoftherequest_length,themaximumsendbodysize(8186(8Kbytes-6)),andthenumberofbytesactuallylefttosendfromtherequestbody.Ifthereisnomoredatainthebody(i.e.theservletcontaineristryingtoreadpasttheendofthebody),theserverwillsendbackanemptypacket,whichisabodypacketwithapayloadlengthof0.(0x12,0x34,0x00,0x00)
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_proxy_balancer
mod_proxy
(E)proxy_balancer_moduleproxy_balancer.cApache2.1
Thismodulerequirestheserviceofmod_proxy.ItprovidesloadbalancingsupportforHTTP,FTPAJP13protocols
Thus,inordertogettheabilityofloadbalancing,mod_proxymod_proxy_balancerhavetobepresentintheserver.
Internet
Loadbalancerscheduleralgorithm
Atpresent,thereare2loadbalancerscheduleralgorithmsavailableforuse:RequestCountingandWeightedTrafficCounting.ThesearecontrolledviathelbmethodvalueoftheBalancerdefinition.SeetheProxydirectiveformoreinformation.
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
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
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.
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.
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006128|
||||
Apachemod_proxy_connect
mod_proxyHTTP CONNECT
(E)proxy_connect_moduleproxy_connect.c
mod_proxyHTTP CONNECTSSL
CONNECT mod_proxymod_proxy_connect
Internet
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006128|
Apachemod_proxy_ftp
mod_proxyFTP(E)proxy_ftp_moduleproxy_ftp.c
FTP mod_proxyFTP mod_proxymod_proxy_ftp
FTPGET
Internet
xxxFTP
mimeapplication/octet-stream
application/octet-streambindmslhalzhexeclasstgztaz
DefaultTypeapplication/octet-stream
xxxFTPASCII
FTP ASCII( binary)" ;type=a" mod_proxyASCIIFTPASCII
FTP
mod_proxyFTPGETFTPApacheHTTP(POSTPUT)
homeFTP
FTPURIhome"/../"(.)FTPApacheFTP" Squid%2fhack" SquidProxyCache" /%2f"FTP" /"(home)
/etc/motdURL
ftp://user@host/%2f/etc/motd
||||
URLFTP
FTPApacheURLApacheFTP
user:anonymous
password:apache_proxy@
FTP
URL
ftp://username@host/myfile
FTP()Apache" 401"()/
ftp://username:password@host/myfile
Apachebase64ApacheFTPHTTPFTP(FTP)
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006128|
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_rewrite
URL(E)rewrite_modulemod_rewrite.cApache1.3
URLURLURLHTTPURL
URL()( httpd.conf)(.htaccess)
URL
Apache1.3.20 TestStringSubstitution(\)() Substitution" \$"mod_rewrite
()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/
URLURLURL
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
/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
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
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
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.
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
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
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
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.
RewriteEngine
EnablesordisablesruntimerewritingengineRewriteEngineon|off
RewriteEngineoff
serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_rewrite
RewriteEnginedirectiveenablesordisablestheruntimerewritingengine.Ifitissettooffthismoduledoesnoruntimeprocessingatall.ItdoesnotevenupdatetheSCRIPT_URxenvironmentvariables.
UsethisdirectivetodisablethemoduleinsteadofcommentingoutalltheRewriteRuledirectives!
Notethat,bydefault,rewriteconfigurationsarenotinherited.ThismeansthatyouneedtohaveaRewriteEngineondirectiveforeachvirtualhostinwhichyouwishtouseit.
RewriteLock
SetsthenameofthelockfileusedforRewriteMapsynchronizationRewriteLockfile-path
serverconfig(E)mod_rewrite
Thisdirectivesetsthefilenameforasynchronizationlockfilewhichmod_rewriteneedstocommunicatewithRewriteMapprograms.Setthislockfiletoalocalpath(notonaNFS-mounteddevice)whenyouwanttousearewritingmap-program.Itisnotrequiredforothertypesofrewritingmaps.
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"
RewriteLogLevel
SetstheverbosityofthelogfileusedbytherewriteengineRewriteLogLevelLevel
RewriteLogLevel0
serverconfig,virtualhost(E)mod_rewrite
RewriteLogLeveldirectivesetstheverbosityleveloftherewritinglogfile.Thedefaultlevel0meansnologging,while9ormoremeansthatpracticallyallactionsarelogged.
TodisabletheloggingofrewritingactionssimplysetLevelto0.Thisdisablesallrewriteactionlogs.
UsingahighvalueforLevelwillslowdownyourApacheserverdramatically!UsetherewritinglogfileataLevelgreaterthan2onlyfordebugging!
RewriteLogLevel3
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:
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
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
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:
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:
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!
RewriteOptions
SetssomespecialoptionsfortherewriteengineRewriteOptionsOptions
serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_rewriteMaxRedirectsisnolongeravailableinversion2.1
RewriteOptionsdirectivesetssomespecialoptionsforthecurrentper-serverorper-directoryconfiguration.TheOptionstringcanbecurrentlyonlyone:
inherit
Thisforcesthecurrentconfigurationtoinherittheconfigurationoftheparent.Inper-virtual-servercontextthismeansthatthemaps,conditionsandrulesofthemainserverareinherited.Inper-directorycontextthismeansthatconditionsandrulesoftheparentdirectory's.htaccessconfigurationareinherited.
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)
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
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
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
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
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'.
'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
/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.
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!
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
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
||||
^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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006129|
Apachemod_setenvif
(B)setenvif_modulemod_setenvif.c
mod_setenvif
mozillaMSIE netscape
BrowserMatch^Mozillanetscape
BrowserMatchMSIE!netscape
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
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
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
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
||||
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")
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006129|
Apachemod_so
DSO(E)so_modulemod_so.cWindows()
ApacheDSO
Unix( .so)Windows .so.dll
Apache1.3Apache2.0
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
LoadFile
LoadFilefilename[filename]...
serverconfig(E)mod_so
FilenameServerRoot
LoadFilelibexec/libxmlparse.so
||||
LoadModule
LoadModulemodulefilename
serverconfig(E)mod_so
filenamemodule modulemodule (ModuleIdentifier)
LoadModulestatus_modulemodules/mod_status.so
ServerRoot
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
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,
||||
whichisnotwhatwasintended.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_ssl
(SSL)(TLS)(E)ssl_modulemod_ssl.c
ThismoduleprovidesSSLv2/v3andTLSv1supportfortheApacheHTTPServer.ItwascontributedbyRalfS.Engeschallbasedonhismod_sslprojectandoriginallyderivedfromworkbyBenLaurie.
ThismodulereliesonOpenSSLtoprovidethecryptographyengine.
Furtherdetails,discussion,andexamplesareprovidedintheSSLdocumentation.
EnvironmentVariables
ThismoduleprovidesalotofSSLinformationasadditionalenvironmentvariablestotheSSIandCGInamespace.Thegeneratedvariablesarelistedinthetablebelow.Forbackwardcompatibilitytheinformationcanbemadeavailableunderdifferentnames,too.LookintheCompatibilitychapterfordetailsonthecompatibilityvariables.
VariableName: ValueType:
Description:
HTTPS flag HTTPSisbeingused.SSL_PROTOCOL string TheSSLprotocolversion
(SSLv2,SSLv3,TLSv1)SSL_SESSION_ID string Thehex-encodedSSL
sessionidSSL_CIPHER string Thecipherspecification
nameSSL_CIPHER_EXPORT string 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
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
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.
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"
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
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/
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
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/
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
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/
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
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
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
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
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
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
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
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
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
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
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.
SSLHonorCipherOrder
Optiontoprefertheserver'scipherpreferenceorderSSLHonorCiperOrderflag
serverconfig,virtualhost(E)mod_sslApache2.1andlater,ifusingOpenSSL0.9.7orlater
WhenchoosingacipherduringanSSLv3orTLSv1handshake,normallytheclient'spreferenceisused.Ifthisdirectiveisenabled,theserver'spreferencewillbeusedinstead.
SSLHonorCipherOrderon
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
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
APRsupportsatleastoneofthe2.
default|yes
ThisdirectivetellstheSSLModuletopickthedefaultlockingimplementationasdeterminedbytheplatformandAPR.
SSLMutexfile:/usr/local/apache/logs/ssl_mutex
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
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
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>
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
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.
SSLPassPhraseDialog
exec:/usr/local/apache/sbin/pp-filter
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
combinationwiththeminussignonaprotocolastheexampleaboveshows.
#enableSSLv3andTLSv1,butnotSSLv2
SSLProtocolall-SSLv2
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
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/
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
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/
SSLProxyCipherSuite
CipherSuiteavailablefornegotiationinSSLproxyhandshakeSSLProxyCipherSuitecipher-spec
SSLProxyCipherSuite
ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP
serverconfig,virtualhost,directory,.htaccessAuthConfig(E)mod_ssl
EquivalenttoSSLCipherSuite,butfortheproxyconnection.PleaserefertoSSLCipherSuiteforadditionalinformation.
SSLProxyEngine
SSLProxyEngineOperationSwitchSSLProxyEngineon|off
SSLProxyEngineoff
serverconfig,virtualhost(E)mod_ssl
ThisdirectivetogglestheusageoftheSSL/TLSProtocolEngineforproxy.Thisisusuallyusedinsidea<VirtualHost>sectiontoenableSSL/TLSforproxyusageinaparticularvirtualhost.BydefaulttheSSL/TLSProtocolEngineisdisabledforproxyimagebothforthemainserverandallconfiguredvirtualhosts.
<VirtualHost_default_:443>
SSLProxyEngineon
...
</VirtualHost>
SSLProxyMachineCertificateFile
FileofconcatenatedPEM-encodedclientcertificatesandkeystobeusedbytheproxySSLProxyMachineCertificateFilefilename
serverconfigNotapplicable(E)mod_ssl
Thisdirectivesetstheall-in-onefilewhereyoukeepthecertificatesandkeysusedforauthenticationoftheproxyservertoremoteservers.
ThisreferencedfileissimplytheconcatenationofthevariousPEM-encodedcertificatefiles,inorderofpreference.UsethisdirectivealternativelyoradditionallytoSSLProxyMachineCertificatePath.
Currentlythereisnosupportforencryptedprivatekeys
SSLProxyMachineCertificateFile
/usr/local/apache2/conf/ssl.crt/proxy.pem
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/
SSLProxyProtocol
ConfigureusableSSLprotocolflavorsforproxyusageSSLProxyProtocol[+|-]protocol...
SSLProxyProtocolall
serverconfig,virtualhostOptions(E)mod_ssl
ThisdirectivecanbeusedtocontroltheSSLprotocolflavorsmod_sslshouldusewhenestablishingitsserverenvironmentforproxy.Itwillonlyconnecttoserversusingoneoftheprovidedprotocols.
PleaserefertoSSLProtocolforadditionalinformation.
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
require:theremoteserverhastopresentavalidCertificateoptional_no_ca:theremoteservermaypresentavalidCertificatebutitneednottobe(successfully)verifiable.
Inpracticeonlylevelsnonerequirearereallyinteresting,becauseleveloptionaldoesn'tworkwithallserversandleveloptional_no_caisactuallyagainsttheideaofauthentication(butcanbeusedtoestablishSSLtestpages,etc.)
SSLProxyVerifyrequire
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
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
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.
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
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
|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."\
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
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
SSLRequireSSL
DenyaccesswhenSSLisnotusedfortheHTTPrequestSSLRequireSSL
directory,.htaccessAuthConfig(E)mod_ssl
ThisdirectiveforbidsaccessunlessHTTPoverSSL(i.e.HTTPS)isenabledforthecurrentconnection.ThisisveryhandyinsidetheSSL-enabledvirtualhostordirectoriesfordefendingagainstconfigurationerrorsthatexposestuffthatshouldbeprotected.WhenthisdirectiveispresentallrequestsaredeniedwhicharenotusingSSL.
SSLRequireSSL
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
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)
SSLSessionCacheTimeout
NumberofsecondsbeforeanSSLsessionexpiresintheSessionCacheSSLSessionCacheTimeoutseconds
SSLSessionCacheTimeout300
serverconfig,virtualhost(E)mod_ssl
Thisdirectivesetsthetimeoutinsecondsfortheinformationstoredintheglobal/inter-processSSLSessionCacheandtheOpenSSLinternalmemorycache.Itcanbesetaslowas15fortesting,butshouldbesettohighervalueslike300inreallife.
SSLSessionCacheTimeout600
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
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
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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"
(*)"astheinstrumentationrequiredforobtainingthesestatisticsdoesnotexistwithinstandardApache.
EnablingStatusSupport
Toenablestatusreportsonlyforbrowsersfromthefoo.comdomainaddthiscodetoyourhttpd.confconfigurationfile
<Location/server-status>
SetHandlerserver-status
OrderDeny,Allow
Denyfromall
Allowfrom.foo.com
</Location>
YoucannowaccessserverstatisticsbyusingaWebbrowsertoaccessthepagehttp://your.server.name/server-status
AutomaticUpdates
Youcangetthestatuspagetoupdateitselfautomaticallyifyouhaveabrowserthatsupports"refresh".Accessthepagehttp://your.server.name/server-status?refresh=NtorefreshthepageeveryNseconds.
MachineReadableStatusFile
Amachine-readableversionofthestatusfileisavailablebyaccessingthepagehttp://your.server.name/server-status?auto.Thisisusefulwhenautomaticallyrun,seethePerlprograminthe/supportdirectoryofApache,log_server_status.
Itshouldbenotedthatifmod_statusiscompiledintotheserver,itshandlercapabilityisavailableinallconfigurationfiles,includingper-directoryfiles( .htaccess).Thismayhavesecurity-relatedramificationsforyoursite.
||||
ExtendedStatus
KeeptrackofextendedstatusinformationforeachrequestExtendedStatusOn|Off
ExtendedStatusOff
serverconfig(B)mod_statusExtendedStatusisonlyavailableinApache1.3.2
Thissettingappliestotheentireserver,andcannotbeenabledordisabledonavirtualhost-by-virtualhostbasis.Thecollectionofextendedstatusinformationcanslowdowntheserver.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006129|
Apachemod_suexec
webCGISSI(E)suexec_modulemod_suexec.cApache2.0
suexecCGI
||||
SuexecUserGroup
CGISuexecUserGroupUserGroup
serverconfig,virtualhost(E)mod_suexecApache2.0
SuexecUserGroupCGICGIUserApache1.3VirtualHostsUserGroup
SuexecUserGroupnobodynogroup
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_unique_id
(E)unique_id_modulemod_unique_id.c
Thismoduleprovidesamagictokenforeachrequestwhichisguaranteedtobeuniqueacross"all"requestsunderveryspecificconditions.Theuniqueidentifierisevenuniqueacrossmultiplemachinesinaproperlyconfiguredclusterofmachines.TheenvironmentvariableUNIQUE_IDissettotheidentifierforeachrequest.Uniqueidentifiersareusefulforvariousreasonswhicharebeyondthescopeofthisdocument.
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
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
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
||||
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).
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006129|
Apachemod_userdir
("/~username")(B)userdir_modulemod_userdir.c
http://example.com/~user/
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
||||
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"
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apachemod_usertrack
Session(Cookie)(E)usertrack_modulemod_usertrack.c
PreviousreleasesofApachehaveincludedamodulewhichgeneratesa'clickstream'logofuseractivityonasiteusingcookies.Thiswascalledthe"cookies"module,mod_cookies.InApache1.2andlaterthismodulehasbeenrenamedthe"usertracking"module,mod_usertrack.Thismodulehasbeensimplifiedandnewdirectivesadded.
Logging
Previously,thecookiesmodule(nowtheusertrackingmodule)diditsownlogging,usingtheCookieLogdirective.Inthisrelease,thismoduledoesnologgingatall.Instead,aconfigurablelogformatfileshouldbeusedtologuserclick-streams.Thisispossiblebecausetheloggingmodulenowallowsmultiplelogfiles.Thecookieitselfisloggedbyusingthetext%{cookie}ninthelogfileformat.Forexample:
CustomLoglogs/clickstream"%{cookie}n%r%t"
ForbackwardcompatibilitytheconfigurablelogmoduleimplementstheoldCookieLogdirective,butthisshouldbeupgradedtotheaboveCustomLogdirective.
2-digitor4-digitdatesforcookies?
(thefollowingisfrommessage<[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".
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.
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.
CookieName
NameofthetrackingcookieCookieNametoken
CookieNameApache
serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_usertrack
Thisdirectiveallowsyoutochangethenameofthecookiethismoduleusesforitstrackingpurposes.Bydefaultthecookieisnamed"Apache".
Youmustspecifyavalidcookiename;resultsareunpredictableifyouuseanamecontainingunusualcharacters.ValidcharactersincludeA-Z,a-z,0-9,"_",and"-".
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.
||||
CookieTracking
EnablestrackingcookieCookieTrackingon|off
CookieTrackingoff
serverconfig,virtualhost,directory,.htaccessFileInfo(E)mod_usertrack
Whentheusertrackmoduleiscompiledin,and"CookieTrackingon"isset,Apachewillstartsendingauser-trackingcookieforallnewrequests.Thisdirectivecanbeusedtoturnthisbehavioronoroffonaper-serverorper-directorybasis.Bydefault,compilingmod_usertrackwillnotactivatecookies.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
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.
<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
||||
=== versionhastheform/regex/~ versionhastheformregex
<IfVersion=/^2.1.[01234]$/>
#e.g.workaroundforbuggyversions
</IfVersion>
Inordertoreversethemeaning,alloperatorscanbeprecededbyanexclamationmark(!):
<IfVersion!~^2.1.[01234]$>
#notforthoseversions
</IfVersion>
Iftheoperatorisomitted,itisassumedtobe=.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006129|
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/
("name")( UseCanonicalName)""IP printf
%% (%)%p
%N.M ()
NMname Nname MN M"0" M
0 name1
2
-1
-2
2+
-2+
1+-1+ 0
NM
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
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
VirtualDocumentRoot
VirtualDocumentRootinterpolated-directory|none
VirtualDocumentRootnone
serverconfig,virtualhost(E)mod_vhost_alias
VirtualDocumentRootApache interpolated-directoryDocumentRoot interpolated-directorynoneVirtualDocumentRoot VirtualDocumentRootIP
VirtualDocumentRootIP
IPVirtualDocumentRootIPinterpolated-directory|none
VirtualDocumentRootIPnone
serverconfig,virtualhost(E)mod_vhost_alias
VirtualDocumentRootIPVirtualDocumentRootIP
VirtualScriptAlias
CGIVirtualScriptAliasinterpolated-directory|none
VirtualScriptAliasnone
serverconfig,virtualhost(E)mod_vhost_alias
VirtualScriptAliasApacheCGI VirtualDocumentRoot
/cgi-bin/URI" ScriptAlias/cgi-bin/"
||||
VirtualScriptAliasIP
IPCGIVirtualScriptAliasIPinterpolated-directory|none
VirtualScriptAliasIPnone
serverconfig,virtualhost(E)mod_vhost_alias
VirtualScriptAliasIPVirtualScriptAliasIP
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apache1.3APInotes
Warning
Thisdocumenthasnotbeenupdatedtotakeintoaccountchangesmadeinthe2.0versionoftheApacheHTTPServer.Someoftheinformationmaystillberelevant,butpleaseuseitwithcare.
ThesearesomenotesontheApacheAPIandthedatastructuresyouhavetodealwith,etc.Theyarenotyetnearlycomplete,buthopefully,theywillhelpyougetyourbearings.KeepinmindthattheAPIisstillsubjecttochangeaswegainexperiencewithit.(SeetheTODOfileforwhatmightbecoming).However,itwillbeeasytoadaptmodulestoanychangesthataremade.(Wehavemoremodulestoadaptthanyoudo).
Afewnotesongeneralpedagogicalstylehere.Intheinterestofconciseness,allstructuredeclarationshereareincomplete--therealoneshavemoreslotsthatI'mnottellingyouabout.Forthemostpart,thesearereservedtoonecomponentoftheservercoreoranother,andshouldbealteredbymoduleswithcaution.However,insomecases,theyreallyarethingsIjusthaven'tgottenaroundtoyet.Welcometothebleedingedge.
Finally,here'sanoutline,togiveyousomebareideaofwhat'scomingup,andinwhatorder:
Basicconcepts.Handlers,Modules,andRequestsAbrieftourofamodule
HowhandlersworkAbrieftouroftherequest_recWhererequest_recstructurescomefrom
Handlingrequests,declining,andreturningerrorcodesSpecialconsiderationsforresponsehandlersSpecialconsiderationsforauthenticationhandlersSpecialconsiderationsforlogginghandlers
ResourceallocationandresourcepoolsConfiguration,commandsandthelike
Per-directoryconfigurationstructuresCommandhandlingSidenotes---per-serverconfiguration,virtualservers,etc.
Basicconcepts
WebeginwithanoverviewofthebasicconceptsbehindtheAPI,andhowtheyaremanifestedinthecode.
Handlers,Modules,andRequestsApachebreaksdownrequesthandlingintoaseriesofsteps,moreorlessthesamewaytheNetscapeserverAPIdoes(althoughthisAPIhasafewmorestagesthanNetSitedoes,ashooksforstuffIthoughtmightbeusefulinthefuture).Theseare:
URI->FilenametranslationAuthIDchecking[istheuserwhotheysaytheyare?]Authaccesschecking[istheuserauthorizedhere?]AccesscheckingotherthanauthDeterminingMIMEtypeoftheobjectrequested'Fixups'--therearen'tanyoftheseyet,butthephaseisintendedasahookforpossibleextensionslikeSetEnv,whichdon'treallyfitwellelsewhere.Actuallysendingaresponsebacktotheclient.Loggingtherequest
Thesephasesarehandledbylookingateachofasuccessionofmodules,lookingtoseeifeachofthemhasahandlerforthephase,andattemptinginvokingitifso.Thehandlercantypicallydooneofthreethings:
Handletherequest,andindicatethatithasdonesobyreturningthemagicconstantOK.Declinetohandletherequest,byreturningthemagicintegerconstantDECLINED.Inthiscase,theserverbehavesinallrespectsasifthehandlersimplyhadn'tbeenthere.Signalanerror,byreturningoneoftheHTTPerrorcodes.Thisterminatesnormalhandlingoftherequest,althoughanErrorDocumentmaybeinvokedtotrytomopup,anditwillbe
loggedinanycase.
Mostphasesareterminatedbythefirstmodulethathandlesthem;however,forlogging,'fixups',andnon-accessauthenticationchecking,allhandlersalwaysrun(barringanerror).Also,theresponsephaseisuniqueinthatmodulesmaydeclaremultiplehandlersforit,viaadispatchtablekeyedontheMIMEtypeoftherequestedobject.Modulesmaydeclarearesponse-phasehandlerwhichcanhandleanyrequest,bygivingitthekey*/*(i.e.,awildcardMIMEtypespecification).However,wildcardhandlersareonlyinvokediftheserverhasalreadytriedandfailedtofindamorespecificresponsehandlerfortheMIMEtypeoftherequestedobject(eithernoneexisted,ortheyalldeclined).
Thehandlersthemselvesarefunctionsofoneargument(arequest_recstructure.videinfra),whichreturnsaninteger,asabove.
AbrieftourofamoduleAtthispoint,weneedtoexplainthestructureofamodule.Ourcandidatewillbeoneofthemessierones,theCGImodule--thishandlesbothCGIscriptsandtheScriptAliasconfigfilecommand.It'sactuallyagreatdealmorecomplicatedthanmostmodules,butifwe'regoingtohaveonlyoneexample,itmightaswellbetheonewithitsfingersineveryplace.
Let'sbeginwithhandlers.InordertohandletheCGIscripts,themoduledeclaresaresponsehandlerforthem.BecauseofScriptAlias,italsohashandlersforthenametranslationphase(torecognizeScriptAliasedURIs),thetype-checkingphase(anyScriptAliasedrequestistypedasaCGIscript).
Themoduleneedstomaintainsomeper(virtual)serverinformation,namely,theScriptAliasesineffect;themodulestructuretherefore
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},
{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*/
cgi_cmds,/*commandtable*/
cgi_handlers,/*handlers*/
translate_scriptalias,/*filenametranslation*/
NULL,/*check_user_id*/
NULL,/*checkauth*/
NULL,/*checkaccess*/
type_scriptalias,/*type_checker*/
NULL,/*fixups*/
NULL,/*logger*/
NULL/*headerparser*/
};
Howhandlerswork
Thesoleargumenttohandlersisarequest_recstructure.Thisstructuredescribesaparticularrequestwhichhasbeenmadetotheserver,onbehalfofaclient.Inmostcases,eachconnectiontotheclientgeneratesonlyonerequest_recstructure.
Abrieftouroftherequest_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";
Finally,therearepointerstotwodatastructureswhich,inturn,pointtoper-moduleconfigurationstructures.Specifically,theseholdpointerstothedatastructureswhichthemodulehasbuilttodescribethewayithasbeenconfiguredtooperateinagivendirectory(via.htaccessfilesor<Directory>sections),forprivatedataithasbuiltinthecourseofservicingtherequest(somodules'handlersforonephasecanpass'notes'totheirhandlersforotherphases).Thereisanothersuchconfigurationvectorintheserver_recdatastructurepointedtobytherequest_rec,whichcontainsper(virtual)serverconfigurationdata.
Hereisanabridgeddeclaration,givingthefieldsmostcommonlyused:
structrequest_rec{
pool*pool;
conn_rec*connection;
server_rec*server;
/*Whatobjectisbeingrequested*/
char*uri;
char*filename;
char*path_info;
char*args;/*QUERY_ARGS,ifany*/
structstatfinfo;/*Setbyservercore;
*st_modesettozeroifnosuchfile*/
char*content_type;
char*content_encoding;
/*MIMEheaderenvironments,inandout.Also,
*anarraycontainingenvironmentvariablesto
*bepassedtosubprocesses,sopeoplecanwrite
*modulestoaddtothatenvironment.
*
*Thedifferencebetweenheaders_outand
*err_headers_outisthatthelatterareprinted
*evenonerror,andpersistacrossinternal
*redirects(sotheheadersprintedfor
*ErrorDocumenthandlerswillhavethem).*/
table*headers_in;table*headers_out;table*err_headers_out;table*subprocess_env;
/*Infoabouttherequestitself...*/
intheader_only;/*HEADrequest,asopposedtoGET*/
char*protocol;/*Protocol,asgiventous,orHTTP/0.9*/
char*method;/*GET,HEAD,POST,etc.*/
intmethod_number;/*M_GET,M_POST,etc.*/
/*Infoforlogging*/
char*the_request;
intbytes_sent;
/*Aflagwhichmodulescanset,toindicatethat
*thedatabeingreturnedisvolatile,and
clients
*shouldbetoldnottocacheit.
*/
intno_cache;
/*Variousotherconfiginfowhichmaychange
*with.htaccessfiles
*Theseareconfigvectors,withonevoid*
*pointerforeachmodule(thethingpointed
*tobeingthemodule'sbusiness).
*/
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
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.
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;
}
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).
SpecialconsiderationsforlogginghandlersWhenarequesthasinternallyredirected,thereisthequestionofwhattolog.Apachehandlesthisbybundlingtheentirechainofredirectsintoalistofrequest_recstructureswhicharethreadedthroughther->prevandr->nextpointers.Therequest_recwhichispassedtothelogginghandlersinsuchcasesistheonewhichwasoriginallybuiltfortheinitialrequestfromtheclient;notethatthebytes_sentfieldwillonlybecorrectinthelastrequestinthechain(theoneforwhicharesponsewasactuallysent).
Resourceallocationandresourcepools
Oneoftheproblemsofwritinganddesigningaserver-poolserveristhatofpreventingleakage,thatis,allocatingresources(memory,openfiles,etc.),withoutsubsequentlyreleasingthem.Theresourcepoolmachineryisdesignedtomakeiteasytopreventthisfromhappening,byallowingresourcetobeallocatedinsuchawaythattheyareautomaticallyreleasedwhentheserverisdonewiththem.
Thewaythisworksisasfollows:thememorywhichisallocated,fileopened,etc.,todealwithaparticularrequestaretiedtoaresourcepoolwhichisallocatedfortherequest.Thepoolisadatastructurewhichitselftrackstheresourcesinquestion.
Whentherequesthasbeenprocessed,thepooliscleared.Atthatpoint,allthememoryassociatedwithitisreleasedforreuse,allfilesassociatedwithitareclosed,andanyotherclean-upfunctionswhichareassociatedwiththepoolarerun.Whenthisisover,wecanbeconfidentthatalltheresourcetiedtothepoolhavebeenreleased,andthatnoneofthemhaveleaked.
Serverrestarts,andallocationofmemoryandresourcesforper-serverconfiguration,arehandledinasimilarway.Thereisaconfigurationpool,whichkeepstrackofresourceswhichwereallocatedwhilereadingtheserverconfigurationfiles,andhandlingthecommandstherein(forinstance,thememorythatwasallocatedforper-servermoduleconfiguration,logfilesandotherfilesthatwereopened,andsoforth).Whentheserverrestarts,andhastorereadtheconfigurationfiles,theconfigurationpooliscleared,andsothememoryandfiledescriptorswhichweretakenupbyreadingthemthelasttimearemadeavailableforreuse.
Itshouldbenotedthatuseofthepoolmachineryisn'tgenerallyobligatory,exceptforsituationslikelogginghandlers,whereyoureallyneedtoregistercleanupstomakesurethatthelogfilegetsclosedwhentheserverrestarts(thisismosteasilydonebyusingthe
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,
anddoarangecheck.
(Italsoraisesthepossibilitythatheavyuseofap_palloccouldcauseaserverprocesstogrowexcessivelylarge.Therearetwowaystodealwiththis,whicharedealtwithbelow;briefly,youcanusemalloc,andtrytobesurethatallofthememorygetsexplicitlyfreed,oryoucanallocateasub-poolofthemainpool,allocateyourmemoryinthesub-pool,andclearitoutperiodically.Thelattertechniqueisdiscussedinthesectiononsub-poolsbelow,andisusedinthedirectory-indexingcode,inordertoavoidexcessivestorageallocationwhenlistingdirectorieswiththousandsoffiles).
AllocatinginitializedmemoryTherearefunctionswhichallocateinitializedmemory,andarefrequentlyuseful.Thefunctionap_pcallochasthesameinterfaceasap_palloc,butclearsoutthememoryitallocatesbeforeitreturnsit.Thefunctionap_pstrduptakesaresourcepoolandachar*asarguments,andallocatesmemoryforacopyofthestringthepointerpointsto,returningapointertothecopy.Finallyap_pstrcatisavarargs-stylefunction,whichtakesapointertoaresourcepool,andatleasttwochar*arguments,thelastofwhichmustbeNULL.Itallocatesenoughmemorytofitcopiesofeachofthestrings,asaunit;forinstance:
ap_pstrcat(r->pool,"foo","/","bar",NULL);
returnsapointerto8bytesworthofmemory,initializedto"foo/bar".
Commonly-usedpoolsintheApacheWebserverApoolisreallydefinedbyitslifetimemorethananythingelse.Therearesomestaticpoolsinhttp_mainwhicharepassedtovariousnon-http_mainfunctionsasargumentsatopportunetimes.Heretheyare:
permanent_pool
neverpassedtoanythingelse,thisistheancestorofallpools
pconf
subpoolofpermanent_poolcreatedatthebeginningofaconfig"cycle";existsuntiltheserveristerminatedorrestarts;passedtoallconfig-timeroutines,eitherviacmd->pool,orasthe"pool*p"argumentonthosewhichdon'ttakepoolspassedtothemoduleinit()functions
ptemp
sorryIlie,thispoolisn'tcalledthiscurrentlyin1.3,Irenameditthisinmypthreadsdevelopment.I'mreferringtotheuseofptransintheparent...contrastthiswiththelaterdefinitionofptransinthechild.subpoolofpermanent_poolcreatedatthebeginningofaconfig"cycle";existsuntiltheendofconfigparsing;passedtoconfig-timeroutinesviacmd->temp_pool.Somewhatofa"bastardchild"becauseitisn'tavailableeverywhere.Usedfortemporaryscratchspacewhichmaybeneededbysomeconfigroutinesbutwhichisdeletedattheendofconfig.
pchild
subpoolofpermanent_poolcreatedwhenachildisspawned(orathreadiscreated);livesuntilthatchild(thread)isdestroyedpassedtothemodulechild_initfunctionsdestructionhappensrightafterthechild_exitfunctionsarecalled...(whichmayexplainwhyIthinkchild_exitisredundantandunneeded)
ptrans
shouldbeasubpoolofpchild,butcurrentlyisasubpoolofpermanent_pool,seeabove
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.
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.
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
ap_destroy_sub_req,whichfreestheresourcepool.Beforecallingthisfunction,besuretocopyanythingthatyoucareaboutwhichmightbeallocatedinthesub-request'sresourcepoolintosomeplacealittlelessvolatile(forinstance,thefilenameinitsrequest_recstructure).
(Again,undermostcircumstances,youshouldn'tfeelobligedtocallthisfunction;only2Kofmemoryorsoareallocatedforatypicalsubrequest,anditwillbefreedanywaywhenthemainrequestpooliscleared.Itisonlywhenyouareallocatingmany,manysub-requestsforasinglemainrequestthatyoushouldseriouslyconsidertheap_destroy_...functions).
Configuration,commandsandthelike
OneofthedesigngoalsforthisserverwastomaintainexternalcompatibilitywiththeNCSA1.3server---thatis,toreadthesameconfigurationfiles,toprocessallthedirectivesthereincorrectly,andingeneraltobeadrop-inreplacementforNCSA.Ontheotherhand,anotherdesigngoalwastomoveasmuchoftheserver'sfunctionalityintomoduleswhichhaveaslittleaspossibletodowiththemonolithicservercore.Theonlywaytoreconcilethesegoalsistomovethehandlingofmostcommandsfromthecentralserverintothemodules.
However,justgivingthemodulescommandtablesisnotenoughtodivorcethemcompletelyfromtheservercore.Theserverhastorememberthecommandsinordertoactonthemlater.Thatinvolvesmaintainingdatawhichisprivatetothemodules,andwhichcanbeeitherper-server,orper-directory.Mostthingsareper-directory,includinginparticularaccesscontrolandauthorizationinformation,butalsoinformationonhowtodeterminefiletypesfromsuffixes,whichcanbemodifiedbyAddTypeandDefaultTypedirectives,andsoforth.Ingeneral,thegoverningphilosophyisthatanythingwhichcanbemadeconfigurablebydirectoryshouldbe;per-serverinformationisgenerallyusedinthestandardsetofmodulesforinformationlikeAliasesandRedirectswhichcomeintoplaybeforetherequestistiedtoaparticularplaceintheunderlyingfilesystem.
AnotherrequirementforemulatingtheNCSAserverisbeingabletohandletheper-directoryconfigurationfiles,generallycalled.htaccessfiles,thoughevenintheNCSAservertheycancontaindirectiveswhichhavenothingatalltodowithaccesscontrol.Accordingly,afterURI->filenametranslation,butbeforeperforminganyotherphase,theserverwalksdownthedirectoryhierarchyoftheunderlyingfilesystem,followingthetranslatedpathname,toreadany.htaccessfileswhichmightbepresent.Theinformationwhichisreadinthenhastobemergedwiththeapplicableinformationfromthe
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.
(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
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
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).
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
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,
&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
||||
(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;
}
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
DebuggingMemoryAllocationinAPR
TheallocationmechanismswithinAPRhaveanumberofdebuggingmodesthatcanbeusedtoassistinfindingmemoryproblems.Thisdocumentdescribesthemodesavailableandgivesinstructionsonactivatingthem.
Availabledebuggingoptions
AllocationDebugging-ALLOC_DEBUG
Debuggingsupport:Definethistoenablecodewhichhelpsdetectre-useoffree()dmemoryandothersuchnonsense.
Thetheoryissimple.TheFILL_BYTE(0xa5)iswrittenoverallmalloc'dmemoryaswereceiveit,andiswrittenovereverythingthatwefreeupduringaclear_pool.WecheckthatblocksonthefreelistalwayshavetheFILL_BYTEinthem,andwecheckduringpalloc()thatthebytesstillhaveFILL_BYTEinthem.IfyoueverseegarbageURLsorwhatnotcontaininglotsof0xa5sthenyouknowsomethinguseddatathat'sbeenfreedoruninitialized.
MallocSupport-ALLOC_USE_MALLOC
Ifdefinedallallocationswillbedonewithmalloc()andfree()dappropriatelyattheend.
ThisisintendedtobeusedwithsomethinglikeElectricFenceorPurifytohelpdetectmemoryproblems.Notethatifyou'reusingefencethenyoushouldalsoaddinALLOC_DEBUG.Butdon'taddinALLOC_DEBUGifyou'reusingPurifybecauseALLOC_DEBUGwouldhidealltheuninitializedreaderrorsthatPurifycandiagnose.
PoolDebugging-POOL_DEBUG
Thisisintendedtodetectcaseswherethewrongpoolisusedwhenassigningdatatoanobjectinanotherpool.
Inparticular,itcausesthetable_{set,add,merge}nroutinestocheckthattheirargumentsaresafefortheapr_table_tthey're
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.
AllowableCombinations
Notalltheoptionsoutlinedabovecanbeactivatedatthesametime.thefollowingtablegivesmoreinformation.
ALLOCDEBUG
ALLOCUSEMALLOC
POOLDEBUG
MAKETABLEPROFILE
ALLOCSTATS
ALLOCDEBUG
- No Yes Yes Yes
ALLOCUSEMALLOC
No - No No No
POOLDEBUG
Yes No - Yes Yes
MAKETABLEPROFILE
Yes No Yes - Yes
ALLOCSTATS
Yes No Yes Yes -
Additionallythedebuggingoptionsarenotsuitableformulti-threadedversionsoftheserver.Whentryingtodebugwiththeseoptionstheservershouldbestartedinsingleprocessmode.
ActivatingDebuggingOptions
Thevariousoptionsfordebuggingmemoryarenowenabledintheapr_general.hheaderfileinAPR.Thevariousoptionsareenabledbyuncommentingthedefinefortheoptionyouwishtouse.Thesectionofthecodecurrentlylookslikethis(containedinsrclib/apr/include/apr_pools.h)
/*
#defineALLOC_DEBUG
#definePOOL_DEBUG
#defineALLOC_USE_MALLOC
#defineMAKE_TABLE_PROFILE
#defineALLOC_STATS
*/
typedefstructap_pool_t{
unionblock_hdr*first;
unionblock_hdr*last;
structcleanup*cleanups;
structprocess_chain*subprocesses;
structap_pool_t*sub_pools;
structap_pool_t*sub_next;
structap_pool_t*sub_prev;
structap_pool_t*parent;
char*free_first_avail;
#ifdefALLOC_USE_MALLOC
void*allocation_list;
#endif
#ifdefPOOL_DEBUG
structap_pool_t*joined;
#endif
int(*apr_abort)(intretcode);
structdatastruct*prog_data;
}ap_pool_t;
Toenableallocationdebuggingsimplymovethe#define
||||
ALLOC_DEBUGabovethestartofthecommentsblockandrebuildtheserver.
Note
Inordertousethevariousoptionstheservermustberebuiltaftereditingtheheaderfile.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
DocumentingApache2.0
Apache2.0usesDoxygentodocumenttheAPIsandglobalvariablesinthethecode.ThiswillexplainthebasicsofhowtodocumentusingDoxygen.
BriefDescription
Tostartadocumentationblock,use/**Toendadocumentationblock,use*/
Inthemiddleoftheblock,therearemultipletagswecanuse:
Descriptionofthisfunctionspurpose
@paramparameter_namedescription
@returndescription
@deffuncsignatureofthefunction
deffuncisnotalwaysnecessary.DoxyGendoesnothaveafullparserinit,soanyprototypethatuseamacrointhereturntypedeclarationistoocomplexforscandoc.Thosefunctionsrequireadeffunc.Anexample(using>ratherthan>):
/**
*returnthefinalelementofthepathname
*@parampathnameThepathtogetthefinal
elementof
*@returnthefinalelementofthepath
*@tipExamples:
*<pre>
*"/foo/bar/gum"->"gum"
*"/foo/bar/gum/"->""
*"gum"->"gum"
*"wi\\n32\\stuff"->"stuff"
*</pre>
*@deffuncconstchar*
ap_filename_of_pathname(constchar*pathname)
*/
Atthetopoftheheaderfile,alwaysinclude:
/**
||||
*@packageNameoflibraryheader
*/
DoxygenusesanewHTMLfileforeachpackage.TheHTMLfilesarenamed{Name_of_library_header}.html,sotrytobeconcisewithyournames.
ForafurtherdiscussionofthepossibilitiespleaserefertotheDoxygensite.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apache2.0HookFunctions
Warning
Thisdocumentisstillindevelopmentandmaybepartiallyoutofdate.
Ingeneral,ahookfunctionisonethatApachewillcallatsomepointduringtheprocessingofarequest.Modulescanprovidefunctionsthatarecalled,andspecifywhentheygetcalledincomparisontoothermodules.
Creatingahookfunction
Inordertocreateanewhook,fourthingsneedtobedone:
DeclarethehookfunctionUsetheAP_DECLARE_HOOKmacro,whichneedstobegiventhereturntypeofthehookfunction,thenameofthehook,andthearguments.Forexample,ifthehookreturnsanintandtakesarequest_rec*andanintandiscalleddo_something,thendeclareitlikethis:
AP_DECLARE_HOOK(int,do_something,(request_rec
*r,intn))
Thisshouldgoinaheaderwhichmoduleswillincludeiftheywanttousethehook.
CreatethehookstructureEachsourcefilethatexportsahookhasaprivatestructurewhichisusedtorecordthemodulefunctionsthatusethehook.Thisisdeclaredasfollows:
APR_HOOK_STRUCT(
APR_HOOK_LINK(do_something)
...
)
ImplementthehookcallerThesourcefilethatexportsthehookhastoimplementafunctionthatwillcallthehook.Therearecurrentlythreepossiblewaystodothis.Inallcases,thecallingfunctioniscalledap_run_hookname().
Voidhooks
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:
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);
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
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
||||
APR_HOOK_ORDERispreserved,asfarasispossible.
BenLaurie,15thAugust1999
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
ConvertingModulesfromApache1.3toApache2.0
ThisisafirstattemptatwritingthelessonsIlearnedwhentryingtoconvertthemod_mmap_staticmoduletoApache2.0.It'sbynomeansdefinitiveandprobablywon'tevenbecorrectinsomeways,butit'sastart.
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
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
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*/
/*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*/
/*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
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
RequestProcessinginApache2.0
Warning
Warning-thisisafirst(fast)draftthatneedsfurtherrevision!
SeveralchangesinApache2.0affecttheinternalrequestprocessingmechanics.Moduleauthorsneedtobeawareofthesechangessotheymaytakeadvantageoftheoptimizationsandsecurityenhancements.
Thefirstmajorchangeistothesubrequestandredirectmechanisms.TherewereanumberofdifferentcodepathsinApache1.3toattempttooptimizesubrequestorredirectbehavior.Aspatcheswereintroducedto2.0,theseoptimizations(andtheserverbehavior)werequicklybrokenduetothisduplicationofcode.Allduplicatecodehasbeenfoldedbackintoap_process_request_internal()topreventthecodefromfallingoutofsyncagain.
Thismeansthatmuchoftheexistingcodewas'unoptimized'.ItistheApacheHTTPProject'sfirstgoaltocreatearobustandcorrectimplementationoftheHTTPserverRFC.Additionalgoalsincludesecurity,scalabilityandoptimization.Newmethodsweresoughttooptimizetheserver(beyondtheperformanceofApache1.3)withoutintroducingfragileorinsecurecode.
TheRequestProcessingCycle
Allrequestspassthroughap_process_request_internal()inrequest.c,includingsubrequestsandredirects.Ifamoduledoesn'tpassgeneratedrequeststhroughthiscode,theauthoriscautionedthatthemodulemaybebrokenbyfuturechangestorequestprocessing.
Tostreamlinerequests,themoduleauthorcantakeadvantageofthehooksofferedtodropoutoftherequestcycleearly,ortobypasscoreApachehookswhichareirrelevant(andcostlyintermsofCPU.)
TheRequestParsingPhase
UnescapestheURLTherequest'sparsed_uripathisunescaped,onceandonlyonce,atthebeginningofinternalrequestprocessing.
Thisstepisbypassediftheproxyreqflagisset,ortheparsed_uri.pathelementisunset.Themodulehasnofurthercontrolofthisone-timeunescapeoperation,eitherfailingtounescapeormultiplyunescapingtheURLleadstosecurityreprecussions.
StripsParentandThisElementsfromtheURIAll/..//./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.
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.
TheSecurityPhase
NeedsDocumentation.Codeis:
switch(ap_satisfies(r)){
caseSATISFY_ALL:
caseSATISFY_NOSPEC:
if((access_status=ap_run_access_checker(r))!=0){
returndecl_die(access_status,"checkaccess",r);
}
if(ap_some_auth_required(r)){
if(((access_status=ap_run_check_user_id(r))!=0)
||!ap_auth_type(r)){
returndecl_die(access_status,ap_auth_type(r)
?"checkuser.Nouserfile?"
:"performauthentication.AuthTypenotset!",
r);
}
if(((access_status=ap_run_auth_checker(r))!=0)
||!ap_auth_type(r)){
returndecl_die(access_status,ap_auth_type(r)
?"checkaccess.Nogroupsfile?"
:"performauthentication.AuthTypenotset!",
r);
}
}
break;
caseSATISFY_ANY:
if(((access_status=ap_run_access_checker(r))!=0)){
if(!ap_some_auth_required(r)){
returndecl_die(access_status,"checkaccess",r);
}
if(((access_status=ap_run_check_user_id(r))!=0)
||!ap_auth_type(r)){
returndecl_die(access_status,ap_auth_type(r)
?"checkuser.Nouserfile?"
:"performauthentication.AuthTypenotset!",
r);
}
if(((access_status=ap_run_auth_checker(r))!=0)
||!ap_auth_type(r)){
returndecl_die(access_status,ap_auth_type(r)
?"checkaccess.Nogroupsfile?"
:"performauthentication.AuthTypenotset!",
r);
}
}
break;
}
ThePreparationPhase
Hook:type_checkerThemoduleshaveanopportunitytotesttheURIorfilenameagainstthetargetresource,andsetmimeinformationfortherequest.Bothmod_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.
||||
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
HowfiltersworkinApache2.0
Warning
Thisisacut'npastejobfromanemail(<022501c1c529$f63a9550$7f00000a@KOJ>)andonlyreformattedforbetterreadability.It'snotuptodatebutmaybeagoodstartforfurtherresearch.
FilterTypes
Therearethreebasicfiltertypes(eachoftheseisactuallybrokendownintotwocategories,butthatcomeslater).
CONNECTION
Filtersofthistypearevalidforthelifetimeofthisconnection.(AP_FTYPE_CONNECTION,AP_FTYPE_NETWORK)
PROTOCOL
Filtersofthistypearevalidforthelifetimeofthisrequestfromthepointofviewoftheclient,thismeansthattherequestisvalidfromthetimethattherequestissentuntilthetimethattheresponseisreceived.(AP_FTYPE_PROTOCOL,AP_FTYPE_TRANSCODE)
RESOURCE
Filtersofthistypearevalidforthetimethatthiscontentisusedtosatisfyarequest.Forsimplerequests,thisisidenticaltoPROTOCOL,butinternalredirectsandsub-requestscanchangethecontentwithoutendingtherequest.(AP_FTYPE_RESOURCE,AP_FTYPE_CONTENT_SET)
Itisimportanttomakethedistinctionbetweenaprotocolandaresourcefilter.Aresourcefilteristiedtoaspecificresource,itmayalsobetiedtoheaderinformation,butthemainbindingistoaresource.Ifyouarewritingafilterandyouwanttoknowifitisresourceorprotocol,thecorrectquestiontoaskis:"Canthisfilterberemovediftherequestisredirectedtoadifferentresource?"Iftheanswerisyes,thenitisaresourcefilter.Ifitisno,thenitismostlikelyaprotocolorconnectionfilter.Iwon'tgointoconnectionfilters,becausetheyseemtobewellunderstood.Withthisdefinition,afewexamplesmighthelp:
ByterangeWehavecodedittobeinsertedforallrequests,anditisremovedifnotused.Becausethisfilterisactiveatthebeginning
ofallrequests,itcannotberemovedifitisredirected,sothisisaprotocolfilter.
http_headerThisfilteractuallywritestheheaderstothenetwork.Thisisobviouslyarequiredfilter(exceptintheasiscasewhichisspecialandwillbedealtwithbelow)andsoitisaprotocolfilter.
DeflateTheadministratorconfiguresthisfilterbasedonwhichfilehasbeenrequested.Ifwedoaninternalredirectfromanautoindexpagetoanindex.htmlpage,thedeflatefiltermaybeaddedorremovedbasedonconfig,sothisisaresourcefilter.
Thefurtherbreakdownofeachcategoryintotwomorefiltertypesisstrictlyforordering.Wecouldremoveit,andonlyallowforonefiltertype,buttheorderwouldtendtobewrong,andwewouldneedtohackthingstomakeitwork.Currently,theRESOURCEfiltersonlyhaveonefiltertype,butthatshouldchange.
Howarefiltersinserted?
Thisisactuallyrathersimpleintheory,butthecodeiscomplex.Firstofall,itisimportantthateverybodyrealizethattherearethreefilterlistsforeachrequest,buttheyareallconcatenatedtogether.So,thefirstlistisr->output_filters,thenr->proto_output_filters,andfinallyr->connection->output_filters.ThesecorrespondtotheRESOURCE,PROTOCOL,andCONNECTIONfiltersrespectively.Theproblempreviously,wasthatweusedasinglylinkedlisttocreatethefilterstack,andwestartedfromthe"correct"location.ThismeansthatifIhadaRESOURCEfilteronthestack,andIaddedaCONNECTIONfilter,theCONNECTIONfilterwouldbeignored.Thisshouldmakesense,becausewewouldinserttheconnectionfilteratthetopofthec->output_filterslist,buttheendofr->output_filterspointedtothefilterthatusedtobeatthefrontofc->output_filters.Thisisobviouslywrong.Thenewinsertioncodeusesadoublylinkedlist.Thishastheadvantagethatweneverloseafilterthathasbeeninserted.Unfortunately,itcomeswithaseparatesetofheadaches.
Theproblemisthatwehavetwodifferentcaseswereweusesubrequests.Thefirstistoinsertmoredataintoaresponse.Thesecondistoreplacetheexistingresponsewithaninternalredirect.Thesearetwodifferentcasesandneedtobetreatedassuch.
Inthefirstcase,wearecreatingthesubrequestfromwithinahandlerorfilter.Thismeansthatthenextfiltershouldbepassedtomake_sub_requestfunction,andthelastresourcefilterinthesub-requestwillpointtothenextfilterinthemainrequest.Thismakessense,becausethesub-request'sdataneedstoflowthroughthesamesetoffiltersasthemainrequest.Agraphicalrepresentationmighthelp:
Default_handler-->includes_filter-->byterange-->...
Iftheincludesfiltercreatesasubrequest,thenwedon'twantthedatafromthatsub-requesttogothroughtheincludesfilter,becauseitmightnotbeSSIdata.So,thesubrequestaddsthefollowing:
Default_handler-->includes_filter-/->byterange-->...
/
Default_handler-->sub_request_core
WhathappensifthesubrequestisSSIdata?Well,that'seasy,theincludes_filterisaresourcefilter,soitwillbeaddedtothesubrequestinbetweentheDefault_handlerandthesub_request_corefilter.
Thesecondcaseforsub-requestsiswhenonesub-requestisgoingtobecometherealrequest.Thishappenswheneverasub-requestiscreatedoutsideofahandlerorfilter,andNULLispassedasthenextfiltertothemake_sub_requestfunction.
Inthiscase,theresourcefiltersnolongermakesenseforthenewrequest,becausetheresourcehaschanged.So,insteadofstartingfromscratch,wesimplypointthefrontoftheresourcefiltersforthesub-requesttothefrontoftheprotocolfiltersfortheoldrequest.Thismeansthatwewon'tloseanyoftheprotocolfilters,neitherwillwetrytosendthisdatathroughafilterthatshouldn'tseeit.
Theproblemisthatweareusingadoubly-linkedlistforourfilterstacksnow.But,youshouldnoticethatitispossiblefortwoliststointersectinthismodel.So,youdoyouhandlethepreviouspointer?Thisisaverydifficultquestiontoanswer,becausethereisno"right"answer,eithermethodisequallyvalid.Ilookedatwhyweusethepreviouspointer.Theonlyreasonforitistoallowforeasieradditionofnewservers.Withthatbeingsaid,thesolutionIchosewastomakethepreviouspointeralwaysstayontheoriginalrequest.
Thiscausessomemorecomplexlogic,butitworksforallcases.Myconcerninhavingitmovetothesub-request,isthatforthemorecommoncase(whereasub-requestisusedtoadddatatoaresponse),themainfilterchainwouldbewrong.Thatdidn'tseemlikeagoodideatome.
Asis
Thefinaltopic.:-)Mod_Asisisabitofahack,butthehandlerneedstoremoveallfiltersexceptforconnectionfilters,andsendthedata.Ifyouareusingmod_asis,allotherbetsareoff.
||||
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200613|
Apache
(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
(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)
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,
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
(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
||||
(VirtualHosting)Apache IP(IPvirtualhosting)IP (name-basedvirtualhosting)IP
Apache
X.509(ITU)SSL/TLS
SSL/TLS
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006121|
Apache
A|B|C|D|E|F|G|H|I|K|L|M|N|O|P|R|S|T|U|V|W|X
AcceptFilterAcceptMutexAcceptPathInfoAccessFileNameActionAddAltAddAltByEncodingAddAltByTypeAddCharsetAddDefaultCharsetAddDescriptionAddEncodingAddHandlerAddIconAddIconByEncodingAddIconByTypeAddInputFilterAddLanguageAddModuleInfoAddOutputFilterAddOutputFilterByTypeAddTypeAliasAliasMatchAllow
AllowCONNECTAllowEncodedSlashesAllowOverrideAnonymousAnonymous_LogEmailAnonymous_MustGiveEmailAnonymous_NoUserIDAnonymous_VerifyEmailAuthBasicAuthoritativeAuthBasicProviderAuthDBDUserPWQueryAuthDBDUserRealmQueryAuthDBMGroupFileAuthDBMTypeAuthDBMUserFileAuthDefaultAuthoritativeAuthDigestAlgorithmAuthDigestDomainAuthDigestNcCheckAuthDigestNonceFormatAuthDigestNonceLifetimeAuthDigestProviderAuthDigestQopAuthDigestShmemSizeAuthGroupFileAuthLDAPBindDNAuthLDAPBindPasswordAuthLDAPCharsetConfigAuthLDAPCompareDNOnServerAuthLDAPDereferenceAliasesAuthLDAPGroupAttributeAuthLDAPGroupAttributeIsDNAuthLDAPRemoteUserIsDNAuthLDAPUrl
AuthName<AuthnProviderAlias>AuthTypeAuthUserFileAuthzDBMAuthoritativeAuthzDBMTypeAuthzDefaultAuthoritativeAuthzGroupFileAuthoritativeAuthzLDAPAuthoritativeAuthzOwnerAuthoritativeAuthzUserAuthoritativeBrowserMatchBrowserMatchNoCaseBufferedLogsCacheDefaultExpireCacheDirLengthCacheDirLevelsCacheDisableCacheEnableCacheFileCacheIgnoreCacheControlCacheIgnoreHeadersCacheIgnoreNoLastModCacheLastModifiedFactorCacheMaxExpireCacheMaxFileSizeCacheMinFileSizeCacheNegotiatedDocsCacheRootCacheStoreNoStoreCacheStorePrivateCGIMapExtensionCharsetDefaultCharsetOptions
CharsetSourceEncCheckSpellingContentDigestCookieDomainCookieExpiresCookieLogCookieNameCookieStyleCookieTrackingCoreDumpDirectoryCustomLogDavDavDepthInfinityDavGenericLockDBDavLockDBDavMinTimeoutDBDExptimeDBDKeepDBDMaxDBDMinDBDParamsDBDPersistDBDPrepareSQLDBDriverDefaultIconDefaultLanguageDefaultTypeDeflateBufferSizeDeflateCompressionLevelDeflateFilterNoteDeflateMemLevelDeflateWindowSizeDeny<Directory>
DirectoryIndex<DirectoryMatch>DirectorySlashDocumentRootDumpIOInputDumpIOOutputEnableExceptionHookEnableMMAPEnableSendfileErrorDocumentErrorLogExampleExpiresActiveExpiresByTypeExpiresDefaultExtendedStatusExtFilterDefineExtFilterOptionsFileETag<Files><FilesMatch>FilterChainFilterDeclareFilterProtocolFilterProviderFilterTraceForceLanguagePriorityForceTypeForensicLogGracefulShutdownTimeoutGroupHeaderHeaderNameHostnameLookups
IdentityCheckIdentityCheckTimeout<IfDefine><IfModule><IfVersion>ImapBaseImapDefaultImapMenuIncludeIndexIgnoreIndexOptionsIndexOrderDefaultIndexStyleSheetISAPIAppendLogToErrorsISAPIAppendLogToQueryISAPICacheFileISAPIFakeAsyncISAPILogNotSupportedISAPIReadAheadBufferKeepAliveKeepAliveTimeoutLanguagePriorityLDAPCacheEntriesLDAPCacheTTLLDAPConnectionTimeoutLDAPOpCacheEntriesLDAPOpCacheTTLLDAPSharedCacheFileLDAPSharedCacheSizeLDAPTrustedClientCertLDAPTrustedGlobalCertLDAPTrustedModeLDAPVerifyServerCert<Limit>
<LimitExcept>LimitInternalRecursionLimitRequestBodyLimitRequestFieldsLimitRequestFieldSizeLimitRequestLineLimitXMLRequestBodyListenListenBackLogLoadFileLoadModule<Location><LocationMatch>LockFileLogFormatLogLevelMaxClientsMaxKeepAliveRequestsMaxMemFreeMaxRequestsPerChildMaxRequestsPerThreadMaxSpareServersMaxSpareThreadsMaxThreadsMCacheMaxObjectCountMCacheMaxObjectSizeMCacheMaxStreamingBufferMCacheMinObjectSizeMCacheRemovalAlgorithmMCacheSizeMetaDirMetaFilesMetaSuffixMimeMagicFile
MinSpareServersMinSpareThreadsMMapFileModMimeUsePathInfoMultiviewsMatchNameVirtualHostNoProxyNWSSLTrustedCertsNWSSLUpgradeableOptionsOrderPassEnvPidFileProtocolEcho<Proxy>ProxyBadHeaderProxyBlockProxyDomainProxyErrorOverrideProxyIOBufferSize<ProxyMatch>ProxyMaxForwardsProxyPassProxyPassReverseProxyPassReverseCookieDomainProxyPassReverseCookiePathProxyPreserveHostProxyReceiveBufferSizeProxyRemoteProxyRemoteMatchProxyRequestsProxyTimeoutProxyViaReadmeName
ReceiveBufferSizeRedirectRedirectMatchRedirectPermanentRedirectTempRemoveCharsetRemoveEncodingRemoveHandlerRemoveInputFilterRemoveLanguageRemoveOutputFilterRemoveTypeRequestHeaderRequireRewriteBaseRewriteCondRewriteEngineRewriteLockRewriteLogRewriteLogLevelRewriteMapRewriteOptionsRewriteRuleRLimitCPURLimitMEMRLimitNPROCSatisfyScoreBoardFileScriptScriptAliasScriptAliasMatchScriptInterpreterSourceScriptLogScriptLogBuffer
ScriptLogLengthScriptSockSecureListenSendBufferSizeServerAdminServerAliasServerLimitServerNameServerPathServerRootServerSignatureServerTokensSetEnvSetEnvIfSetEnvIfNoCaseSetHandlerSetInputFilterSetOutputFilterSSIEndTagSSIErrorMsgSSIStartTagSSITimeFormatSSIUndefinedEchoSSLCACertificateFileSSLCACertificatePathSSLCADNRequestFileSSLCADNRequestPathSSLCARevocationFileSSLCARevocationPathSSLCertificateChainFileSSLCertificateFileSSLCertificateKeyFileSSLCipherSuiteSSLCryptoDevice
SSLEngineSSLHonorCipherOrderSSLMutexSSLOptionsSSLPassPhraseDialogSSLProtocolSSLProxyCACertificateFileSSLProxyCACertificatePathSSLProxyCARevocationFileSSLProxyCARevocationPathSSLProxyCipherSuiteSSLProxyEngineSSLProxyMachineCertificateFileSSLProxyMachineCertificatePathSSLProxyProtocolSSLProxyVerifySSLProxyVerifyDepthSSLRandomSeedSSLRequireSSLRequireSSLSSLSessionCacheSSLSessionCacheTimeoutSSLUserNameSSLVerifyClientSSLVerifyDepthStartServersStartThreadsSuexecUserGroupThreadLimitThreadsPerChildThreadStackSizeTimeOutTraceEnableTransferLog
||||
TypesConfigUnsetEnvUseCanonicalNameUseCanonicalPhysicalPortUserUserDirVirtualDocumentRootVirtualDocumentRootIP<VirtualHost>VirtualScriptAliasVirtualScriptAliasIPWin32DisableAcceptExXBitHack
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |???|
()"+"
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-
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]...
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
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
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
<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
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
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
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
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
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>
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
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
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
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]
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
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
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
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
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]
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)
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]
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+
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
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
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
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
||||
accept()AcceptEx()XBitHackon|off|full offParseSSIdirectivesinfileswiththeexecutebitset
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
“Apache2.0”Apache2.2[]kajaabiAjifeisuncjsDanielflytoseaforehead
LinuxFans.Orgsejishikong[]
LinuxSir.Orgbingzhou[]
chmpdf
Apache2.2http://lamp.linux.gov.cn/Apache/ApacheMenu/index.html
Apache2.2http://www.dogdoghome.com/lamp/Apache/ApacheMenu/index.html
rarbz2zippdfchmrarbz2zippdfchm
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006121|
Apache
coreApacheHTTP
mpm_common(MPM)
beosBeOS(MPM)
eventworkerMPM
mpm_netwareNovellNetWare(MPM)
mpmt_os2OS/2(MPM)
preforkMPM
mpm_winntWindowsNT/2000/XP/2003MPM
workerMPMMPM
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
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
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
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
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
||||
mod_vhost_alias
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |200617|
FAQApache< http://httpd.apache.org/docs/2.2/faq/>
Apache1.3FAQ
ApacheHTTPServer
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
"......"
"......"Apache
Apache()/usr/local/apache2/logs/error_logErrorLog
FAQ!ApacheApache
ApachebugApachebugbug ( ) ""
Apache
FreenodeIRC#apache
bughttpd bug
dump backtrace()
60Apache
Apache
||||
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
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2
|| |200616|
ApacheHTTPServerVersion2.2
1.32.02.02.2Apache2.1/2.2Apache2.0ApacheLicense
ApacheHTTP
ApacheApache
DirectoryLocationFiles
URL
(DSO)
Apache(MPM)ApacheApache
suEXEC
URL
Apache
IP
DNSApache
Apache
(//)
ApacheSSL/TLS
SSL/TLSSSL/TLSSSL/TLS...SSL/TLS
CGI(SSI).htaccess
MicrosoftWindowsApacheMicrosoftWindowsApacheNovellNetWareApacheHPUXApacheEBCDIC
ApacheHTTP
httpdabapachectlapxsconfiguredbmmanagehtcachecleanhtdbmhtdigesthtpasswdlogresolverotatelogssuexec
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
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
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
ApacheAPIAPRApache2.0Apache2.0HookApache1.3Apache2.0Apache2.0Apache2.0
||||
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006114|
ApacheHTTP
httpd
Apache
apachectl
ApacheHTTP
ab
ApacheHTTP
apxs
APache
configure
dbmmanage
DBM
htcacheclean
htdigest
htdbm
DBM
htpasswd
httxt2dbm
RewriteMapdbm
logresolve
ApacheIP
rotatelogs
Apache
suexec
Exec
||||
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>SSL/TLS
|| |2006116|
ApacheSSL/TLS
ApacheHTTPmod_ssl(SecureSocketsLayer)(TransportLayerSecurity) OpenSSLRalfS.Engelschall mod_ssl
...
||||
mod_ssl
mod_ssl
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006118|
Apache
" "( www.company1.comwww.company2.com)IP"IP"IP" "
ApacheIP1.1IP" "" IP"
Apache1.3
(IP)IP(IP)
()
||||
<VirtualHost>
NameVirtualHost
ServerName
ServerAlias
ServerPath
Apache -S
/usr/local/apache2/bin/httpd-S
ApacheIP( httpd)
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
DeveloperDocumentationforApache2.0
ManyofthedocumentsontheseDeveloperpagesareliftedfromApache1.3'sdocumentation.WhiletheyareallbeingupdatedtoApache2.0,theyareindifferentstagesofprogress.Pleasebepatient,andpointoutanydiscrepanciesorerrorsonthedeveloper/[email protected].
Topics
Apache1.3APINotesApache2.0HookFunctionsRequestProcessinginApache2.0HowfiltersworkinApache2.0ConvertingModulesfromApache1.3toApache2.0DebuggingMemoryAllocationinAPRDocumentingApache2.0Apache2.0ThreadSafetyIssues
||||
ExternalResources
ToolsprovidedbyIanHolsman:Apache2crossreferenceAutogeneratedApache2codedocumentation
ModuleDevelopmentTutorialsbyKevinO'DonnellIntegratingamoduleintotheApachebuildsystemHandlingconfigurationdirectives
SomenotesonApachemoduledevelopmentbyRyanBloomDeveloperarticlesatapachetutorinclude:
RequestProcessinginApacheConfigurationforModulesResourceManagementinApacheConnectionPoolinginApacheIntroductiontoBucketsandBrigades
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |200619|
||||
Apacheweb
ApacheHTTP2.2
Apache
Apache
Apacheweb
URL
mod_rewrite mod_rewriteURL
Apache
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006114|
httxt2dbm-RewriteMapdbm
httxt2dbmRewriteMapdbm( dbm)
httxt2dbm[-v][-fDBM_TYPE]-iSOURCE_TXT-o
OUTPUT_DBM
-v
-f
DBM APRGDBMGDBMSDBMSDBMDBberkeleyDBNDBMNDBMdefault
-i
dbmkeyvalue
RewriteMap
-o
dbm
||||
httxt2dbm-irewritemap.txt-orewritemap.dbm
httxt2dbm-fSDBM-irewritemap.txt-o
rewritemap.dbm
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006112|
MicrosoftWindows
ApacheWindowsApache2.0
MicrosoftWindowsApache
ApacheWindowsApache
MicrosoftWindowsApache
||||
NovellNetWareNovellNetWare5.1Apache2.0
NovellNetWareApache
HP-UXHP-UXApache
HP-UXApache
EBCDICApacheHTTP1.3EBCDICASCII
ApacheHTTP2.0
TheApacheEBCDICPort
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
|| |2006114|
suexec-
suexecApacheHTTPCGI rootApache root
suexecrootsetuid root
suexec suexec)
suexec-V
||||
-V
rootsuexec
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>.../
|| |200619|
.../
||||
.../
(Authentication)(Authorization)
CGICGI()webCGICGIApachewebCGICGI
CGI
.htaccess
.htaccess("")
See:.htaccess
SSIHTMLHTMLCGI
See:(SSI)
UserDirURL http://example.com/~username/" username" UserDir
See:(public_html)
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL
||< >|???|
Apachemod_rewrite
"Thegreatthingaboutmod_rewriteisitgivesyoualltheconfigurabilityandflexibilityofSendmail.Thedownsidetomod_rewriteisthatitgivesyoualltheconfigurabilityandflexibilityofSendmail."
--BrianBehlendorfApacheGroup
"Despitethetonsofexamplesanddocs,mod_rewriteisvoodoo.Damnedcoolvoodoo,butstillvoodoo."
Welcometomod_rewrite,theSwissArmyKnifeofURLmanipulation!
Thismoduleusesarule-basedrewritingengine(basedonaregular-expressionparser)torewriterequestedURLsonthefly.ItsupportsanunlimitednumberofrulesandanunlimitednumberofattachedruleconditionsforeachruletoprovideareallyflexibleandpowerfulURLmanipulationmechanism.TheURLmanipulationscandependonvarioustests,forinstanceservervariables,environmentvariables,HTTPheaders,timestampsandevenexternaldatabaselookupsinvariousformatscanbeusedtoachievegranularURLmatching.
ThismoduleoperatesonthefullURLs(includingthepath-infopart)bothinper-servercontext(httpd.conf)andper-directorycontext(.htaccess)andcanevengeneratequery-stringpartsonresult.Therewrittenresultcanleadtointernalsub-processing,externalrequestredirectionoreventoaninternalproxythroughput.
Butallthisfunctionalityandflexibilityhasitsdrawback:complexity.
Sodon'texpecttounderstandthisentiremoduleinjustoneday.
||||
Documentation
mod_rewritereferencedocumentation
TechnicaldetailsPracticalsolutionstocommonproblemsPracticalsolutionstoadvancedproblemsGlossary
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL
||< >|???|
URLRewritingGuide
Thisdocumentsupplementsthemod_rewritereferencedocumentation.ItdescribeshowonecanuseApache'smod_rewritetosolvetypicalURL-basedproblemswithwhichwebmastersarecommononyconfronted.WegivedetaileddescriptionsonhowtosolveeachproblembyconfiguringURLrewritingrulesets.
ATTENTION:Dependingonyourserverconfigurationitmaybenecessarytoslightlychangetheexamplesforyoursituation,e.g.addingthe[PT]flagwhenadditionallyusingmod_aliasmod_userdir,etc.Orrewritingarulesettofitin.htaccesscontextinsteadofper-servercontext.Alwaystrytounderstandwhataparticularrulesetreallydoesbeforeyouuseit.Thisavoidsmanyproblems.
CanonicalURLs
Description:OnsomewebserverstherearemorethanoneURLforaresource.UsuallytherearecanonicalURLs(whichshouldbeactuallyusedanddistributed)andthosewhicharejustshortcuts,internalones,etc.IndependentofwhichURLtheusersuppliedwiththerequestheshouldfinallyseethecanonicaloneonly.
Solution:WedoanexternalHTTPredirectforallnon-canonicalURLstofixtheminthelocationviewoftheBrowserandforallsubsequentrequests.Intheexamplerulesetbelowwereplace/~userbythecanonical/u/userandfixamissingtrailingslashfor/u/user.
RewriteRule^/~([^/]+)/?(.*)/u/$1/$2[R]
RewriteRule^/([uge])/([^/]+)$/$1/$2/[R]
CanonicalHostnames
Description:Thegoalofthisruleistoforcetheuseofaparticularhostname,inpreferencetootherhostnameswhichmaybeusedtoreachthesamesite.Forexample,ifyouwishtoforcetheuseofwww.example.cominsteadofexample.com,youmightuseavariantofthefollowingrecipe.
Solution:Forsitesrunningonaportotherthan80:
RewriteCond%{HTTP_HOST}!^fully\.qualified\.domain\.name[NC]
RewriteCond%{HTTP_HOST}!^$
RewriteCond%{SERVER_PORT}!^80$
RewriteRule^/(.*)http://fully.qualified.domain.name:%{SERVER_PORT}/$1[L,R]
Andforasiterunningonport80
RewriteCond%{HTTP_HOST}!^fully\.qualified\.domain\.name[NC]
RewriteCond%{HTTP_HOST}!^$
RewriteRule^/(.*)http://fully.qualified.domain.name/$1[L,R]
MovedDocumentRoot
Description:UsuallytheDocumentRootofthewebserverdirectlyrelatestotheURL"/".Butoftenthisdataisnotreallyoftop-levelpriority.Forexample,youmaywishforvisitors,onfirstenteringasite,togotoaparticularsubdirectory/about/.Thismaybeaccomplishedusingthefollowingruleset:
Solution:WeredirecttheURL/to/about/:
RewriteEngineon
RewriteRule^/$/about/[R]
NotethatthiscanalsobehandledusingtheRedirectMatchdirective:
RedirectMatch^/$http://example.com/e/www/
TrailingSlashProblem
Description:Thevastmajorityof"trailingslash"problemscanbedealtwithusingthetechniquesdiscussedintheFAQentry.However,occasionally,thereisaneedtousemod_rewritetohandleacasewhereamissingtrailingslashcausesaURLtofail.Thiscanhappen,forexample,afteraseriesofcomplexrewriterules.
Solution:Thesolutiontothissubtleproblemistolettheserveraddthetrailingslashautomatically.Todothiscorrectlywehavetouseanexternalredirect,sothebrowsercorrectlyrequestssubsequentimagesetc.Ifweonlydidainternalrewrite,thiswouldonlyworkforthedirectorypage,butwouldgowrongwhenanyimagesareincludedintothispagewithrelativeURLs,becausethebrowserwouldrequestanin-linedobject.Forinstance,arequestforimage.gifin/~quux/foo/index.htmlwouldbecome/~quux/image.gifwithouttheexternalredirect!
So,todothistrickwewrite:
RewriteEngineon
RewriteBase/~quux/
RewriteRule^foo$foo/[R]
Alternately,youcanputthefollowinginatop-level.htaccessfileinthecontentdirectory.Butnotethatthiscreatessomeprocessingoverhead.
RewriteEngineon
RewriteBase/~quux/
RewriteCond%{REQUEST_FILENAME}-d
RewriteRule^(.+[^/])$$1/[R]
MoveHomedirstoDifferentWebserver
Description:Manywebmastershaveaskedforasolutiontothefollowingsituation:Theywantedtoredirectjustallhomedirsonawebservertoanotherwebserver.Theyusuallyneedsuchthingswhenestablishinganewerwebserverwhichwillreplacetheoldoneovertime.
Solution:Thesolutionistrivialwithmod_rewrite.Ontheoldwebserverwejustredirectall/~user/anypathURLstohttp://newserver/~user/anypath.
RewriteEngineon
RewriteRule^/~(.+)http://newserver/~$1[R,L]
Searchpagesinmorethanonedirectory
Description:Sometimesitisnecessarytoletthewebserversearchforpagesinmorethanonedirectory.HereMultiViewsorothertechniquescannothelp.
Solution:Weprogramaexplicitrulesetwhichsearchesforthefilesinthedirectories.
RewriteEngineon
#firsttrytofinditincustom/...
#...andiffoundstopandbehappy:
RewriteCond/your/docroot/dir1/%{REQUEST_FILENAME}-f
RewriteRule^(.+)/your/docroot/dir1/$1[L]
#secondtrytofinditinpub/...
#...andiffoundstopandbehappy:
RewriteCond/your/docroot/dir2/%{REQUEST_FILENAME}-f
RewriteRule^(.+)/your/docroot/dir2/$1[L]
#elsegoonforotherAliasorScriptAliasdirectives,
#etc.
RewriteRule^(.+)-[PT]
SetEnvironmentVariablesAccordingToURLParts
Description:PerhapsyouwanttokeepstatusinformationbetweenrequestsandusetheURLtoencodeit.Butyoudon'twanttouseaCGIwrapperforallpagesjusttostripoutthisinformation.
Solution:WeusearewriteruletostripoutthestatusinformationandrememberitviaanenvironmentvariablewhichcanbelaterdereferencedfromwithinXSSIorCGI.ThiswayaURL/foo/S=java/bar/getstranslatedto/foo/bar/andtheenvironmentvariablenamedSTATUSissettothevalue"java".
RewriteEngineon
RewriteRule^(.*)/S=([^/]+)/(.*)$1/$3[E=STATUS:$2
VirtualUserHosts
Description:Assumethatyouwanttoprovidewww.username.host.domain.comforthehomepageofusernameviajustDNSArecordstothesamemachineandwithoutanyvirtualhostsonthismachine.
Solution:ForHTTP/1.0requeststhereisnosolution,butforHTTP/1.1requestswhichcontainaHost:HTTPheaderwecanusethefollowingrulesettorewritehttp://www.username.host.com/anypathinternallyto/home/username/anypath:
RewriteEngineon
RewriteCond%{HTTP_HOST}^www\.[^.]+
RewriteRule^(.+)%{HTTP_HOST}$1[C]
RewriteRule^www\.([^.]+)\.host\.com(.*)/home/$1
RedirectHomedirsForForeigners
Description:WewanttoredirecthomedirURLstoanotherwebserverwww.somewhere.comwhentherequestinguserdoesnotstayinthelocaldomainourdomain.com.Thisissometimesusedinvirtualhostcontexts.
Solution:Justarewritecondition:
RewriteEngineon
RewriteCond%{REMOTE_HOST}!^.+\.ourdomain\.com$
RewriteRule^(/~.+)http://www.somewhere.com/$1[R,L]
RedirectingAnchors
Description:Bydefault,redirectingtoanHTMLanchordoesn'twork,becausemod_rewriteescapesthe#character,turningitinto%23.This,inturn,breakstheredirection.
Solution:Usethe[NE]flagontheRewriteRule.NEstandsforNoEscape.
Time-DependentRewriting
Description:Whentricksliketime-dependentcontentshouldhappenalotofwebmastersstilluseCGIscriptswhichdoforinstanceredirectstospecializedpages.Howcanitbedoneviamod_rewrite?
Solution:TherearealotofvariablesnamedTIME_xxxforrewriteconditions.Inconjunctionwiththespeciallexicographiccomparisonpatterns<STRING,>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...
BackwardCompatibilityforYYYYtoXXXXmigration
Description:HowcanwemakeURLsbackwardcompatible(stillexistingvirtually)aftermigratingdocument.YYYYtodocument.XXXX,e.g.aftertranslatingabunchof.htmlfilesto.phtml?
Solution:Wejustrewritethenametoitsbasenameandtestforexistenceofthenewextension.Ifitexists,wetakethatname,elsewerewritetheURLtoitsoriginalstate.
#backwardcompatibilityrulesetfor
#rewritingdocument.htmltodocument.phtml
#whenandonlywhendocument.phtmlexists
#butnolongerdocument.html
RewriteEngineon
RewriteBase/~quux/
#parseoutbasename,butrememberthefact
RewriteRule^(.*)\.html$$1[C,E=WasHTML:yes]
#rewritetodocument.phtmlifexists
RewriteCond%{REQUEST_FILENAME}.phtml-f
RewriteRule^(.*)$$1.phtml[S=1]
#elsereversethepreviousbasenamecutout
RewriteCond%{ENV:WasHTML}^yes$
RewriteRule^(.*)$$1.html
ContentHandling
FromOldtoNew(intern)Description:
Assumewehaverecentlyrenamedthepagefoo.htmltobar.htmlandnowwanttoprovidetheoldURLforbackwardcompatibility.ActuallywewantthatusersoftheoldURLevennotrecognizethatthepageswasrenamed.
Solution:WerewritetheoldURLtothenewoneinternallyviathefollowingrule:
RewriteEngineon
RewriteBase/~quux/
RewriteRule^foo\.html$bar.html
FromOldtoNew(extern)Description:
Assumeagainthatwehaverecentlyrenamedthepagefoo.htmltobar.htmlandnowwanttoprovidetheoldURLforbackwardcompatibility.ButthistimewewantthattheusersoftheoldURLgethintedtothenewone,i.e.theirbrowsersLocationfieldshouldchange,too.
Solution:WeforceaHTTPredirecttothenewURLwhichleadstoachangeofthebrowsersandthustheusersview:
RewriteEngineon
RewriteBase/~quux/
RewriteRule^foo\.html$bar.html[R]
FromStatictoDynamicDescription:
Howcanwetransformastaticpagefoo.htmlintoadynamicvariantfoo.cgiinaseamlessway,i.e.withoutnoticebythebrowser/user.
Solution:WejustrewritetheURLtotheCGI-scriptandforcethecorrectMIME-typesoitgetsreallyrunasaCGI-script.Thiswayarequestto/~quux/foo.htmlinternallyleadstotheinvocationof/~quux/foo.cgi.
RewriteEngineon
RewriteBase/~quux/
RewriteRule^foo\.html$foo.cgi[T=application/x-httpd-cgi
AccessRestriction
BlockingofRobotsDescription:
Howcanweblockareallyannoyingrobotfromretrievingpagesofaspecificwebarea?A/robots.txtfilecontainingentriesofthe"RobotExclusionProtocol"istypicallynotenoughtogetridofsucharobot.
Solution:WeusearulesetwhichforbidstheURLsofthewebarea/~quux/foo/arc/(perhapsaverydeepdirectoryindexedareawheretherobottraversalwouldcreatebigserverload).Wehavetomakesurethatweforbidaccessonlytotheparticularrobot,i.e.justforbiddingthehostwheretherobotrunsisnotenough.Thiswouldblockusersfromthishost,too.WeaccomplishthisbyalsomatchingtheUser-AgentHTTPheaderinformation.
RewriteCond%{HTTP_USER_AGENT}^NameOfBadRobot.*
RewriteCond%{REMOTE_ADDR}^123\.45\.67\.[8-9]
RewriteRule^/~quux/foo/arc/.+-[F]
BlockedInline-ImagesDescription:
Assumewehaveunderhttp://www.quux-corp.de/~quux/somepageswithinlinedGIFgraphics.Thesegraphicsarenice,soothersdirectlyincorporatethemviahyperlinkstotheirpages.Wedon'tlikethispracticebecauseitaddsuselesstraffictoourserver.
Solution:Whilewecannot100%protecttheimagesfrominclusion,wecanatleastrestrictthecaseswherethebrowsersendsaHTTPRefererheader.
RewriteCond%{HTTP_REFERER}!^$
RewriteCond%{HTTP_REFERER}!^http://www.quux-corp.de/~quux/.*$[NC]
RewriteRule.*\.gif$-[F]
RewriteCond%{HTTP_REFERER}!^$
RewriteCond%{HTTP_REFERER}!.*/foo-with-gif\.html$
RewriteRule^inlined-in-foo\.gif$-[F]
ProxyDenyDescription:
HowcanweforbidacertainhostorevenauserofaspecialhostfromusingtheApacheproxy?
Solution:Wefirsthavetomakesuremod_rewriteisbelow(!)mod_proxyintheConfigurationfilewhencompilingtheApachewebserver.Thiswayitgetscalledbeforemod_proxy.Thenweconfigurethefollowingforahost-dependentdeny...
RewriteCond%{REMOTE_HOST}^badhost\.mydomain\.com$
RewriteRule!^http://[^/.]\.mydomain.com.*-[F]
...andthisoneforauser@host-dependentdeny:
RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}^badguy@badhost\.mydomain\.com$
RewriteRule!^http://[^/.]\.mydomain.com.*-[F]
Other
ExternalRewritingEngineDescription:
AFAQ:HowcanwesolvetheFOO/BAR/QUUX/etc.problem?Thereseemsnosolutionbytheuseofmod_rewrite...
Solution:UseanexternalRewriteMap,i.e.aprogramwhichactslikeaRewriteMap.ItisrunonceonstartupofApachereceivestherequestedURLsonSTDINandhastoputtheresulting(usuallyrewritten)URLonSTDOUT(sameorder!).
RewriteEngineon
RewriteMapquux-mapprg:/path/to/map.quux.pl
RewriteRule^/~quux/(.*)$/~quux/${quux-map:$1}
#!/path/to/perl
#disablebufferedI/Owhichwouldlead
#todeadloopsfortheApacheserver
$|=1;
#readURLsoneperlinefromstdinand
#generatesubstitutionURLonstdout
while(<>){
s|^foo/|bar/|;
print$_;
}
Thisisademonstration-onlyexampleandjustrewritesallURLs/~quux/foo/...to/~quux/bar/....Actuallyyoucanprogramwhateveryoulike.Butnoticethatwhilesuchmapscanbeusedalsobyanaverageuser,onlythesystemadministrator
||||
candefineit.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL
||< >|???|
URLRewritingGuide-Advancedtopics
Thisdocumentsupplementsthemod_rewritereferencedocumentation.ItdescribeshowonecanuseApache'smod_rewritetosolvetypicalURL-basedproblemswithwhichwebmastersarecommononyconfronted.WegivedetaileddescriptionsonhowtosolveeachproblembyconfiguringURLrewritingrulesets.
ATTENTION:Dependingonyourserverconfigurationitmaybenecessarytoslightlychangetheexamplesforyoursituation,e.g.addingthe[PT]flagwhenadditionallyusingmod_aliasmod_userdir,etc.Orrewritingarulesettofitin.htaccesscontextinsteadofper-servercontext.Alwaystrytounderstandwhataparticularrulesetreallydoesbeforeyouuseit.Thisavoidsmanyproblems.
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
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\
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
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
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
Thefirstruleisforrequestswhichmissthetrailingslash!Thesecondruledoestherealthing.Andthencomesthekillerconfigurationwhichstaysintheper-directoryconfigfile/e/netsw/.www/.wwwacl:
OptionsExecCGIFollowSymLinksIncludesMultiViews
RewriteEngineon
#wearereachedvia/net.sw/prefix
RewriteBase/net.sw/
#firstwerewritetherootdirto
#thehandlingcgiscript
RewriteRule^$netsw-home.cgi[L]
RewriteRule^index\.html$netsw-home.cgi[L]
#stripoutthesubdirswhen
#thebrowserrequestsusfromperdirpages
RewriteRule^.+/(netsw-[^/]+/.+)$$1[L]
#andnowbreaktherewritingforlocalfiles
RewriteRule^netsw-home\.cgi.*-[L]
RewriteRule^netsw-changes\.cgi.*-[L]
RewriteRule^netsw-search\.cgi.*-[L]
RewriteRule^netsw-tree\.cgi$-[L]
RewriteRule^netsw-about\.html$-[L]
RewriteRule^netsw-img/.*$-[L]
#anythingelseisasubdirwhichgetshandled
#byanothercgiscript
RewriteRule!^netsw-lsdir\.cgi.*-[C]
RewriteRule(.*)netsw-lsdir.cgi/$1
Somehintsforinterpretation:
1. NoticetheL(last)flagandnosubstitutionfield('-')intheforthpart
2. Noticethe!(not)characterandtheC(chain)flagatthefirstruleinthelastpart
3. Noticethecatch-allpatterninthelastrule
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.
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##
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
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
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?
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
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:
#!/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.
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.
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
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
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"<b>ERROR</b>:Nofilegiven\n";
exit(0);
}
if(!-f$QS_f){
print"HTTP/1.0200OK\n";
print"Content-type:text/html\n\n";
print"<b>ERROR</b>:File$QS_fnotfound\n";
exit(0);
}
subprint_http_headers_multipart_begin{
print"HTTP/1.0200OK\n";
$bound="ThisRandomString12345";
print"Content-type:multipart/x-mixed-replace;boundary=$bound\n";
&print_http_headers_multipart_next;
}
subprint_http_headers_multipart_next{
print"\n--$bound\n";
}
subprint_http_headers_multipart_end{
print"\n--$bound--\n";
}
subdisplayhtml{
local($buffer)=@_;
$len=length($buffer);
print"Content-type:text/html\n";
print"Content-length:$len\n\n";
print$buffer;
}
subreadfile{
local($file)=@_;
local(*FP,$size,$buffer,$bytes);
($x,$x,$x,$x,$x,$x,$x,$size)=stat($file);
$size=sprintf("%d",$size);
open(FP,"<$file");
$bytes=sysread(FP,$buffer,$size);
close(FP);
return$buffer;
}
$buffer=&readfile($QS_f);
&print_http_headers_multipart_begin;
&displayhtml($buffer);
submystat{
local($file)=$_[0];
local($time);
($x,$x,$x,$x,$x,$x,$x,$x,$x,$mtime)=stat($file);
return$mtime;
}
$mtimeL=&mystat($QS_f);
$mtime=$mtime;
for($n=0;$n<$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
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
RewriteMapvhosttxt:/path/to/vhost.map
#Nowdotheactualvirtualhostmapping
#viaahugeandcomplicatedsinglerule:
#
#1.makesurewedon'tmapforcommonlocations
RewriteCond%{REQUEST_URI}!^/commonurl1/.*
RewriteCond%{REQUEST_URI}!^/commonurl2/.*
:
RewriteCond%{REQUEST_URI}!^/commonurlN/.*
#
#2.makesurewehaveaHostheader,because
#currentlyourapproachonlysupports
#virtualhostingthroughthisheader
RewriteCond%{HTTP_HOST}!^$
#
#3.lowercasethehostname
RewriteCond${lowercase:%{HTTP_HOST}|NONE}^(.+)$
#
#4.lookupthishostnameinvhost.mapand
#rememberitonlywhenitisapath
#(andnot"NONE"fromabove)
RewriteCond${vhost:%1}^(/.*)$
#
#5.finallywecanmaptheURLtoitsdocrootlocation
#andrememberthevirtualhostforloggingpuposes
RewriteRule^/(.*)$%1/$1[E=VHOST:${lowercase:%{HTTP_HOST}}]
:
AccessRestriction
HostDenyDescription:
Howcanweforbidalistofexternallyconfiguredhostsfromusingourserver?
Solution:ForApache>=1.3b6:
RewriteEngineon
RewriteMaphosts-denytxt:/path/to/hosts.deny
RewriteCond${hosts-deny:%{REMOTE_HOST}|NOT-FOUND}!=NOT-FOUND[OR]
RewriteCond${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND}!=NOT-FOUND
RewriteRule^/.*-[F]
ForApache<=1.3b6:
RewriteEngineon
RewriteMaphosts-denytxt:/path/to/hosts.deny
RewriteRule^/(.*)$${hosts-deny:%{REMOTE_HOST}|NOT-FOUND}/$1
RewriteRule!^NOT-FOUND/.*-[F]
RewriteRule^NOT-FOUND/(.*)$${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND}/$1
RewriteRule!^NOT-FOUND/.*-[F]
RewriteRule^NOT-FOUND/(.*)$/$1
##
##hosts.deny
##
##ATTENTION!Thisisamap,notalist,evenwhenwetreatitassuch.
##mod_rewriteparsesitforkey/valuepairs,soatleasta
##dummyvalue"-"mustbepresentforeachentry.
##
193.102.180.41-
bsdti1.sdm.de-
192.76.162.40-
ProxyDenyDescription:
HowcanweforbidacertainhostorevenauserofaspecialhostfromusingtheApacheproxy?
Solution:Wefirsthavetomakesuremod_rewriteisbelow(!)mod_proxyintheConfigurationfilewhencompilingtheApachewebserver.Thiswayitgetscalledbeforemod_proxy.Thenweconfigurethefollowingforahost-dependentdeny...
RewriteCond%{REMOTE_HOST}^badhost\.mydomain\.com$
RewriteRule!^http://[^/.]\.mydomain.com.*-[F]
...andthisoneforauser@host-dependentdeny:
RewriteCond%{REMOTE_IDENT}@%{REMOTE_HOST}^badguy@badhost\.mydomain\.com$
RewriteRule!^http://[^/.]\.mydomain.com.*-[F]
SpecialAuthenticationVariantDescription:
Sometimesaveryspecialauthenticationisneeded,forinstanceaauthenticationwhichchecksforasetofexplicitlyconfiguredusers.Onlytheseshouldreceiveaccessandwithoutexplicitprompting(whichwouldoccurwhenusingtheBasicAuthviamod_auth_basic).
Solution:Weusealistofrewriteconditionstoexcludeallexceptourfriends:
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/
||||
Thisautomaticallyredirectstherequestbacktothereferringpage(when"-"isusedasthevalueinthemap)ortoaspecificURL(whenanURLisspecifiedinthemapasthesecondargument).
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>
||< >|???|
Apache2.0ThreadSafetyIssues
WhenusinganyofthethreadedmpmsinApache2.0itisimportantthateveryfunctioncalledfromApachebethreadsafe.Whenlinkingin3rdpartyextensionsitcanbedifficulttodeterminewhethertheresultingserverwillbethreadsafe.Casualtestinggenerallywon'ttellyouthiseitherasthreadsafetyproblemscanleadtosubtleraceconditonsthatmayonlyshowupincertainconditionsunderheavyload.
Globalandstaticvariables
Whenwritingyourmoduleorwhentryingtodetermineifamoduleor3rdpartylibraryisthreadsafetherearesomecommonthingstokeepinmind.
First,youneedtorecognizethatinathreadedmodeleachindividualthreadhasitsownprogramcounter,stackandregisters.Localvariablesliveonthestack,sothosearefine.Youneedtowatchoutforanystaticorglobalvariables.Thisdoesn'tmeanthatyouareabsolutelynotallowedtousestaticorglobalvariables.Therearetimeswhenyouactuallywantsomethingtoaffectallthreads,butgenerallyyouneedtoavoidusingthemifyouwantyourcodetobethreadsafe.
Inthecasewhereyouhaveaglobalvariablethatneedstobeglobalandaccessedbyallthreads,beverycarefulwhenyouupdateit.If,forexample,itisanincrementingcounter,youneedtoatomicallyincrementittoavoidraceconditionswithotherthreads.Youdothisusingamutex(mutualexclusion).Lockthemutex,readthecurrentvalue,incrementitandwriteitbackandthenunlockthemutex.Anyotherthreadthatwantstomodifythevaluehastofirstcheckthemutexandblockuntilitiscleared.
IfyouareusingAPR,havealookattheapr_atomic_*functionsandtheapr_thread_mutex_*functions.
errno
Thisisacommonglobalvariablethatholdstheerrornumberofthelasterrorthatoccurred.Ifonethreadcallsalow-levelfunctionthatsetserrnoandthenanotherthreadchecksit,wearebleedingerrornumbersfromonethreadintoanother.Tosolvethis,makesureyourmoduleorlibrarydefines_REENTRANToriscompiledwith-D_REENTRANT.Thiswillmakeerrnoaper-threadvariableandshouldhopefullybetransparenttothecode.Itdoesthisbydoingsomethinglikethis:
#defineerrno(*(__errno_location()))
whichmeansthataccessingerrnowillcall__errno_location()whichisprovidedbythelibc.Setting_REENTRANTalsoforcesredefinitionofsomeotherfunctionstotheir*_requivalentsandsometimeschangesthecommongetc/putcmacrosintosaferfunctioncalls.Checkyourlibcdocumentationforspecifics.Insteadof,orinadditionto_REENTRANTthesymbolsthatmayaffectthisare_POSIX_C_SOURCE,_THREAD_SAFE,_SVID_SOURCE,and_BSD_SOURCE.
Commonstandardtroublesomefunctions
Notonlydothingshavetobethreadsafe,buttheyalsohavetobereentrant.strtok()isanobviousone.Youcallitthefirsttimewithyourdelimiterwhichitthenremembersandoneachsubsequentcallitreturnsthenexttoken.Obviouslyifmultiplethreadsarecallingityouwillhaveaproblem.Mostsystemshaveareentrantversionofofthefunctioncalledstrtok_r()whereyoupassinanextraargumentwhichcontainsanallocatedchar*whichthefunctionwilluseinsteadofitsownstaticstorageformaintainingthetokenizingstate.IfyouareusingAPRyoucanuseapr_strtok().
crypt()isanotherfunctionthattendstonotbereentrant,soifyourunacrosscallstothatfunctioninalibrary,watchout.Onsomesystemsitisreentrantthough,soitisnotalwaysaproblem.Ifyoursystemhascrypt_r()chancesareyoushouldbeusingthat,orifpossiblesimplyavoidthewholemessbyusingmd5instead.
Common3rdPartyLibraries
Thefollowingisalistofcommonlibrariesthatareusedby3rdpartyApachemodules.Youcanchecktoseeifyourmoduleisusingapotentiallyunsafelibrarybyusingtoolssuchasldd(1)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
forindividualsymbolsinthemodule.
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 ?
||||
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.
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL
||< >|???|
Apachemod_rewriteIntroduction
Thisdocumentsupplementsthemod_rewritereferencedocumentation.Itdescribesthebasicconceptsnecessaryforuseofmod_rewrite.Otherdocumentsgointogreaterdetail,butthisdocshouldhelpthebeginnergettheirfeetwet.
TheApachemodulemod_rewriteisaverypowerfulandsophisticatedmodulewhichprovidesawaytodoURLmanipulations.Withit,youcandonearlyalltypesofURLrewritingthatyoumayneed.Itis,however,somewhatcomplex,andmaybeintimidatingtothebeginner.Thereisalsoatendencytotreatrewriterulesasmagicincantation,usingthemwithoutactuallyunderstandingwhattheydo.
Thisdocumentattemptstogivesufficientbackgroundsothatwhatfollowsisunderstood,ratherthanjustcopiedblindly.
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.
Figure2:Theback-referenceflowthrougharule.
RewriteRulebasics
BasicanatomyofaRewriteRule,withexhaustivelyannotatedsimpleexamples.
RewriteFlags
DiscussionoftheflagstoRewriteRule,andwhenandwhyonemightusethem.
Rewriteconditions
DiscussionofRewriteCond,looping,andotherrelatedconcepts.
Rewritemaps
DiscussionofRewriteMap,includingsimple,butheavilyannotated,examples.
.htaccessfiles
Discussionofthedifferencesbetweenrewriterulesinhttpd.confandin.htaccessfiles.
||||
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/
||||
ApacheHTTPServer2.2Apache>HTTPServer>>2.2>URL
||< >|???|
Apachemod_rewriteTechnicalDetails
Thisdocumentdiscussessomeofthetechnicaldetailsofmod_rewriteandURLmatching.
InternalProcessing
Theinternalprocessingofthismoduleisverycomplexbutneedstobeexplainedonceeventotheaverageusertoavoidcommonmistakesandtoletyouexploititsfullfunctionality.
APIPhases
FirstyouhavetounderstandthatwhenApacheprocessesaHTTPrequestitdoesthisinphases.AhookforeachofthesephasesisprovidedbytheApacheAPI.Mod_rewriteusestwoofthesehooks:theURL-to-filenametranslationhookwhichisusedaftertheHTTPrequesthasbeenreadbutbeforeanyauthorizationstartsandtheFixuphookwhichistriggeredaftertheauthorizationphasesandaftertheper-directoryconfigfiles(.htaccess)havebeenread,butbeforethecontenthandlerisactivated.
So,afterarequestcomesinandApachehasdeterminedthecorrespondingserver(orvirtualserver)therewritingenginestartsprocessingofallmod_rewritedirectivesfromtheper-serverconfigurationintheURL-to-filenamephase.Afewstepslaterwhenthefinaldatadirectoriesarefound,theper-directoryconfigurationdirectivesofmod_rewritearetriggeredintheFixupphase.Inbothsituationsmod_rewriterewritesURLseithertonewURLsortofilenames,althoughthereisnoobviousdistinctionbetweenthem.ThisisausageoftheAPIwhichwasnotintendedtobethiswaywhentheAPIwasdesigned,butasofApache1.xthisistheonlywaymod_rewritecanoperate.Tomakethispointmoreclearrememberthefollowingtwopoints:
1. Althoughmod_rewriterewritesURLstoURLs,URLstofilenamesandevenfilenamestofilenames,theAPIcurrentlyprovidesonlyaURL-to-filenamehook.InApache2.0thetwomissinghookswillbeaddedtomaketheprocessingmoreclear.Butthispointhasnodrawbacksfortheuser,itisjustafactwhichshouldberemembered:ApachedoesmoreintheURL-to-filenamehookthantheAPIintendsforit.
2. Unbelievablymod_rewriteprovidesURLmanipulationsinper-directorycontext,i.e.,within.htaccessfiles,althoughthesearereachedaverylongtimeaftertheURLshavebeentranslatedtofilenames.Ithastobethiswaybecause.htaccessfileslivein
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!
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
||||
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.