Anda di halaman 1dari 7

7/4/2016

HTTPD - Apache2 Web Server

HTTPDApache2WebServer
ApacheisthemostcommonlyusedWebserveronLinuxsystems.WebserversareusedtoserveWebpages
requestedbyclientcomputers.ClientstypicallyrequestandviewWebpagesusingWebbrowserapplications
suchasFirefox,Opera,Chromium,orInternetExplorer.
UsersenteraUniformResourceLocator(URL)topointtoaWebserverbymeansofitsFullyQualified
DomainName(FQDN)andapathtotherequiredresource.Forexample,toviewthehomepageofthe
UbuntuWebsiteauserwillenteronlytheFQDN:
www.ubuntu.com
Toviewthecommunitysubpage,auserwillentertheFQDNfollowedbyapath:
www.ubuntu.com/community
ThemostcommonprotocolusedtotransferWebpagesistheHyperTextTransferProtocol(HTTP).Protocols
suchasHyperTextTransferProtocoloverSecureSocketsLayer(HTTPS),andFileTransferProtocol(FTP),a
protocolforuploadinganddownloadingfiles,arealsosupported.
ApacheWebServersareoftenusedincombinationwiththeMySQLdatabaseengine,theHyperText
Preprocessor(PHP)scriptinglanguage,andotherpopularscriptinglanguagessuchasPythonandPerl.This
configurationistermedLAMP(Linux,Apache,MySQLandPerl/Python/PHP)andformsapowerfulandrobust
platformforthedevelopmentanddeploymentofWebbasedapplications.
Ataterminalpromptenterthefollowingcommand:
sudo apt install apache2

Configuration
Apache2isconfiguredbyplacingdirectivesinplaintextconfigurationfiles.Thesedirectivesareseparated
betweenthefollowingfilesanddirectories:
apache2.conf:themainApache2configurationfile.ContainssettingsthatareglobaltoApache2.
httpd.conf:historicallythemainApache2configurationfile,namedafterthehttpddaemon.Nowthefiledoes
notexist.InolderversionsofUbuntuthefilemightbepresent,butempty,asallconfigurationoptionshave
beenmovedtothebelowreferenceddirectories.
confavailable:thisdirectorycontainsavailableconfigurationfiles.Allfilesthatwerepreviouslyin
/etc/apache2/conf.dshouldbemovedto/etc/apache2/confavailable.
confenabled:holdssymlinkstothefilesin/etc/apache2/confavailable.Whenaconfigurationfileis
symlinked,itwillbeenabledthenexttimeapache2isrestarted.
https://help.ubuntu.com/lts/serverguide/httpd.html

1/7

7/4/2016

HTTPD - Apache2 Web Server

envvars:filewhereApache2environmentvariablesareset.
modsavailable:thisdirectorycontainsconfigurationfilestobothloadmodulesandconfigurethem.Notall
moduleswillhavespecificconfigurationfiles,however.
modsenabled:holdssymlinkstothefilesin/etc/apache2/modsavailable.Whenamoduleconfigurationfile
issymlinkeditwillbeenabledthenexttimeapache2isrestarted.
ports.conf:housesthedirectivesthatdeterminewhichTCPportsApache2islisteningon.
sitesavailable:thisdirectoryhasconfigurationfilesforApache2VirtualHosts.VirtualHostsallowApache2
tobeconfiguredformultiplesitesthathaveseparateconfigurations.
sitesenabled:likemodsenabled,sitesenabledcontainssymlinkstothe/etc/apache2/sitesavailable
directory.Similarlywhenaconfigurationfileinsitesavailableissymlinked,thesiteconfiguredbyitwillbe
activeonceApache2isrestarted.
magic:instructionsfordeterminingMIMEtypebasedonthefirstfewbytesofafile.
Inaddition,otherconfigurationfilesmaybeaddedusingtheIncludedirective,andwildcardscanbeusedto
includemanyconfigurationfiles.Anydirectivemaybeplacedinanyoftheseconfigurationfiles.Changesto
themainconfigurationfilesareonlyrecognizedbyApache2whenitisstartedorrestarted.
TheserveralsoreadsafilecontainingmimedocumenttypesthefilenameissetbytheTypesConfigdirective,
typicallyvia/etc/apache2/modsavailable/mime.conf,whichmightalsoincludeadditionsandoverrides,andis
/etc/mime.typesbydefault.

BasicSettings
ThissectionexplainsApache2serveressentialconfigurationparameters.RefertotheApache2
Documentationformoredetails.
Apache2shipswithavirtualhostfriendlydefaultconfiguration.Thatis,itisconfiguredwithasingledefault
virtualhost(usingtheVirtualHostdirective)whichcanbemodifiedorusedasisifyouhaveasinglesite,or
usedasatemplateforadditionalvirtualhostsifyouhavemultiplesites.Ifleftalone,thedefaultvirtualhost
willserveasyourdefaultsite,orthesiteuserswillseeiftheURLtheyenterdoesnotmatchthe
ServerNamedirectiveofanyofyourcustomsites.Tomodifythedefaultvirtualhost,editthefile
/etc/apache2/sitesavailable/000default.conf.
Thedirectivessetforavirtualhostonlyapplytothatparticularvirtualhost.Ifadirectiveissetserverwide
andnotdefinedwithinthevirtualhostsettings,thedefaultsettingisused.Forexample,youcandefinea
Webmasteremailaddressandnotdefineindividualemailaddressesforeachvirtualhost.
Ifyouwishtoconfigureanewvirtualhostorsite,copythatfileintothesamedirectorywithanameyou
choose.Forexample:
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sitesavailable/mynewsite.conf

https://help.ubuntu.com/lts/serverguide/httpd.html

2/7

7/4/2016

HTTPD - Apache2 Web Server

Editthenewfiletoconfigurethenewsiteusingsomeofthedirectivesdescribedbelow.
TheServerAdmindirectivespecifiestheemailaddresstobeadvertisedfortheserver'sadministrator.The
defaultvalueiswebmaster@localhost.Thisshouldbechangedtoanemailaddressthatisdeliveredtoyou
(ifyouaretheserver'sadministrator).Ifyourwebsitehasaproblem,Apache2willdisplayanerrormessage
containingthisemailaddresstoreporttheproblemto.Findthisdirectiveinyoursite'sconfigurationfilein
/etc/apache2/sitesavailable.
TheListendirectivespecifiestheport,andoptionallytheIPaddress,Apache2shouldlistenon.IftheIP
addressisnotspecified,Apache2willlistenonallIPaddressesassignedtothemachineitrunson.The
defaultvaluefortheListendirectiveis80.Changethisto127.0.0.1:80tocauseApache2tolistenonlyon
yourloopbackinterfacesothatitwillnotbeavailabletotheInternet,to(forexample)81tochangetheport
thatitlistenson,orleaveitasisfornormaloperation.Thisdirectivecanbefoundandchangedinitsown
file,/etc/apache2/ports.conf
TheServerNamedirectiveisoptionalandspecifieswhatFQDNyoursiteshouldanswerto.Thedefault
virtualhosthasnoServerNamedirectivespecified,soitwillrespondtoallrequeststhatdonotmatcha
ServerNamedirectiveinanothervirtualhost.Ifyouhavejustacquiredthedomainnameubunturocks.com
andwishtohostitonyourUbuntuserver,thevalueoftheServerNamedirectiveinyourvirtualhost
configurationfileshouldbeubunturocks.com.Addthisdirectivetothenewvirtualhostfileyoucreated
earlier(/etc/apache2/sitesavailable/mynewsite.conf).
Youmayalsowantyoursitetorespondtowww.ubunturocks.com,sincemanyuserswillassumethewww
prefixisappropriate.UsetheServerAliasdirectiveforthis.YoumayalsousewildcardsintheServerAlias
directive.
Forexample,thefollowingconfigurationwillcauseyoursitetorespondtoanydomainrequestendingin
.ubunturocks.com.
ServerAlias *.ubunturocks.com
TheDocumentRootdirectivespecifieswhereApache2shouldlookforthefilesthatmakeupthesite.The
defaultvalueis/var/www/html,asspecifiedin/etc/apache2/sitesavailable/000default.conf.Ifdesired,
changethisvalueinyoursite'svirtualhostfile,andremembertocreatethatdirectoryifnecessary!
EnablethenewVirtualHostusingthea2ensiteutilityandrestartApache2:
sudo a2ensite mynewsite
sudo systemctl restart apache2.service
BesuretoreplacemynewsitewithamoredescriptivenamefortheVirtualHost.Onemethodistonamethefile
aftertheServerNamedirectiveoftheVirtualHost.
Similarly,usethea2dissiteutilitytodisablesites.Thisiscanbeusefulwhentroubleshootingconfiguration
problemswithmultipleVirtualHosts:
sudo a2dissite mynewsite
https://help.ubuntu.com/lts/serverguide/httpd.html

3/7

7/4/2016

HTTPD - Apache2 Web Server

sudo systemctl restart apache2.service

DefaultSettings
ThissectionexplainsconfigurationoftheApache2serverdefaultsettings.Forexample,ifyouaddavirtual
host,thesettingsyouconfigureforthevirtualhosttakeprecedenceforthatvirtualhost.Foradirectivenot
definedwithinthevirtualhostsettings,thedefaultvalueisused.
TheDirectoryIndexisthedefaultpageservedbytheserverwhenauserrequestsanindexofadirectoryby
specifyingaforwardslash(/)attheendofthedirectoryname.
Forexample,whenauserrequeststhepagehttp://www.example.com/this_directory/,heorshewillget
eithertheDirectoryIndexpageifitexists,aservergenerateddirectorylistifitdoesnotandtheIndexes
optionisspecified,oraPermissionDeniedpageifneitheristrue.Theserverwilltrytofindoneofthefiles
listedintheDirectoryIndexdirectiveandwillreturnthefirstoneitfinds.Ifitdoesnotfindanyofthesefiles
andifOptionsIndexesissetforthatdirectory,theserverwillgenerateandreturnalist,inHTMLformat,of
thesubdirectoriesandfilesinthedirectory.Thedefaultvalue,foundin/etc/apache2/modsavailable/dir.conf
is"index.htmlindex.cgiindex.plindex.phpindex.xhtmlindex.htm".Thus,ifApache2findsafileina
requesteddirectorymatchinganyofthesenames,thefirstwillbedisplayed.
TheErrorDocumentdirectiveallowsyoutospecifyafileforApache2touseforspecificerrorevents.For
example,ifauserrequestsaresourcethatdoesnotexist,a404errorwilloccur.Bydefault,Apache2will
simplyreturnaHTTP404Returncode.Read/etc/apache2/confavailable/localizederrorpages.conffor
detailedinstructionsforusingErrorDocument,includinglocationsofexamplefiles.
Bydefault,theserverwritesthetransferlogtothefile/var/log/apache2/access.log.Youcanchangethison
apersitebasisinyourvirtualhostconfigurationfileswiththeCustomLogdirective,oromitittoacceptthe
default,specifiedin/etc/apache2/confavailable/othervhostsaccesslog.conf.Youmayalsospecifythefile
towhicherrorsarelogged,viatheErrorLogdirective,whosedefaultis/var/log/apache2/error.log.Theseare
keptseparatefromthetransferlogstoaidintroubleshootingproblemswithyourApache2server.Youmay
alsospecifytheLogLevel(thedefaultvalueis"warn")andtheLogFormat(see/etc/apache2/apache2.conf
forthedefaultvalue).
Someoptionsarespecifiedonaperdirectorybasisratherthanperserver.Optionsisoneofthese
directives.ADirectorystanzaisenclosedinXMLliketags,likeso:
<Directory /var/www/html/mynewsite>
...
</Directory>
TheOptionsdirectivewithinaDirectorystanzaacceptsoneormoreofthefollowingvalues(amongothers),
separatedbyspaces:
ExecCGIAllowexecutionofCGIscripts.CGIscriptsarenotexecutedifthisoptionisnotchosen.
MostfilesshouldnotbeexecutedasCGIscripts.Thiswouldbeverydangerous.CGIscriptsshouldkept
inadirectoryseparatefromandoutsideyourDocumentRoot,andonlythisdirectoryshouldhavethe
https://help.ubuntu.com/lts/serverguide/httpd.html

4/7

7/4/2016

HTTPD - Apache2 Web Server

ExecCGIoptionset.Thisisthedefault,andthedefaultlocationforCGIscriptsis/usr/lib/cgibin.
IncludesAllowserversideincludes.ServersideincludesallowanHTMLfiletoincludeotherfiles.See
ApacheSSIdocumentation(Ubuntucommunity)formoreinformation.
IncludesNOEXECAllowserversideincludes,butdisablethe#execand#includecommandsinCGI
scripts.
IndexesDisplayaformattedlistofthedirectory'scontents,ifnoDirectoryIndex(suchasindex.html)
existsintherequesteddirectory.
Forsecurityreasons,thisshouldusuallynotbeset,andcertainlyshouldnotbesetonyour
DocumentRootdirectory.Enablethisoptioncarefullyonaperdirectorybasisonlyifyouarecertainyou
wantuserstoseetheentirecontentsofthedirectory.
MultiviewSupportcontentnegotiatedmultiviewsthisoptionisdisabledbydefaultforsecurityreasons.
SeetheApache2documentationonthisoption.
SymLinksIfOwnerMatchOnlyfollowsymboliclinksifthetargetfileordirectoryhasthesameowneras
thelink.

httpdSettings
Thissectionexplainssomebasichttpddaemonconfigurationsettings.
LockFileTheLockFiledirectivesetsthepathtothelockfileusedwhentheserveriscompiledwitheither
USE_FCNTL_SERIALIZED_ACCEPTorUSE_FLOCK_SERIALIZED_ACCEPT.Itmustbestoredonthelocal
disk.ItshouldbelefttothedefaultvalueunlessthelogsdirectoryislocatedonanNFSshare.Ifthisisthe
case,thedefaultvalueshouldbechangedtoalocationonthelocaldiskandtoadirectorythatisreadable
onlybyroot.
PidFileThePidFiledirectivesetsthefileinwhichtheserverrecordsitsprocessID(pid).Thisfileshouldonly
bereadablebyroot.Inmostcases,itshouldbelefttothedefaultvalue.
UserTheUserdirectivesetstheuseridusedbytheservertoanswerrequests.Thissettingdeterminesthe
server'saccess.Anyfilesinaccessibletothisuserwillalsobeinaccessibletoyourwebsite'svisitors.The
defaultvalueforUseris"wwwdata".
Unlessyouknowexactlywhatyouaredoing,donotsettheUserdirectivetoroot.UsingrootastheUserwill
createlargesecurityholesforyourWebserver.
GroupTheGroupdirectiveissimilartotheUserdirective.Groupsetsthegroupunderwhichtheserverwill
answerrequests.Thedefaultgroupisalso"wwwdata".

Apache2Modules
Apache2isamodularserver.Thisimpliesthatonlythemostbasicfunctionalityisincludedinthecoreserver.
ExtendedfeaturesareavailablethroughmoduleswhichcanbeloadedintoApache2.Bydefault,abasesetof
modulesisincludedintheserveratcompiletime.Iftheserveriscompiledtousedynamicallyloadedmodules,
https://help.ubuntu.com/lts/serverguide/httpd.html

5/7

7/4/2016

HTTPD - Apache2 Web Server

thenmodulescanbecompiledseparately,andaddedatanytimeusingtheLoadModuledirective.Otherwise,
Apache2mustberecompiledtoaddorremovemodules.
UbuntucompilesApache2toallowthedynamicloadingofmodules.Configurationdirectivesmaybe
conditionallyincludedonthepresenceofaparticularmodulebyenclosingtheminan<IfModule>block.
YoucaninstalladditionalApache2modulesandusethemwithyourWebserver.Forexample,runthe
followingcommandataterminalprompttoinstalltheMySQLAuthenticationmodule:
sudo apt install libapache2-mod-auth-mysql
Seethe/etc/apache2/modsavailabledirectory,foradditionalmodules.
Usethea2enmodutilitytoenableamodule:
sudo a2enmod auth_mysql
sudo systemctl restart apache2.service
Similarly,a2dismodwilldisableamodule:
sudo a2dismod auth_mysql
sudo systemctl restart apache2.service

HTTPSConfiguration
Themod_sslmoduleaddsanimportantfeaturetotheApache2servertheabilitytoencryptcommunications.
Thus,whenyourbrowseriscommunicatingusingSSL,thehttps://prefixisusedatthebeginningofthe
UniformResourceLocator(URL)inthebrowsernavigationbar.
Themod_sslmoduleisavailableinapache2commonpackage.Executethefollowingcommandataterminal
prompttoenablethemod_sslmodule:
sudo a2enmod ssl
ThereisadefaultHTTPSconfigurationfilein/etc/apache2/sitesavailable/defaultssl.conf.Inorderfor
Apache2toprovideHTTPS,acertificateandkeyfilearealsoneeded.ThedefaultHTTPSconfigurationwill
useacertificateandkeygeneratedbythesslcertpackage.Theyaregoodfortesting,buttheautogenerated
certificateandkeyshouldbereplacedbyacertificatespecifictothesiteorserver.Forinformationon
generatingakeyandobtainingacertificateseeCertificates
ToconfigureApache2forHTTPS,enterthefollowing:
sudo a2ensite default-ssl
Thedirectories/etc/ssl/certsand/etc/ssl/privatearethedefaultlocations.Ifyouinstallthecertificateandkeyin
anotherdirectorymakesuretochangeSSLCertificateFileandSSLCertificateKeyFileappropriately.
https://help.ubuntu.com/lts/serverguide/httpd.html

6/7

7/4/2016

HTTPD - Apache2 Web Server

WithApache2nowconfiguredforHTTPS,restarttheservicetoenablethenewsettings:
sudo systemctl restart apache2.service
DependingonhowyouobtainedyourcertificateyoumayneedtoenterapassphrasewhenApache2starts.
Youcanaccessthesecureserverpagesbytypinghttps://your_hostname/url/inyourbrowseraddressbar.

SharingWritePermission
Formorethanoneusertobeabletowritetothesamedirectoryitwillbenecessarytograntwritepermission
toagrouptheyshareincommon.Thefollowingexamplegrantssharedwritepermissionto/var/www/htmlto
thegroup"webmasters".
sudo chgrp -R webmasters /var/www/html
sudo find /var/www/html -type d -exec chmod g=rwxs "{}" \;
sudo find /var/www/html -type f -exec chmod g=rw "{}" \;
Thesecommandsrecursivelysetthegrouppermissiononallfilesanddirectoriesin/var/www/htmltoread
writeandsetuserid.Thishastheeffectofhavingthefilesanddirectoriesinherittheirgroupandpermission
fromtheirparrent.Manyadminsfindthisusefulforallowingmultipleuserstoeditfilesinadirectorytree.
Ifaccessmustbegrantedtomorethanonegroupperdirectory,enableAccessControlLists(ACLs).

References
Apache2DocumentationcontainsindepthinformationonApache2configurationdirectives.Also,seethe
apache2docpackagefortheofficialApache2docs.
SeetheModSSLDocumentationsiteformoreSSLrelatedinformation.
O'Reilly'sApacheCookbookisagoodresourceforaccomplishingspecificApache2configurations.
ForUbuntuspecificApache2questions,askinthe#ubuntuserverIRCchannelonfreenode.net.
UsuallyintegratedwithPHPandMySQLtheApacheMySQLPHPUbuntuWikipageisagoodresource.

https://help.ubuntu.com/lts/serverguide/httpd.html

7/7

Anda mungkin juga menyukai