apache and php course

Upload: hari-sankar

Post on 03-Jun-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Apache and Php Course

    1/57

    Compiling, installing and configuringApache and PHP on LinuxElliot Smith, moochlabs.com

    Table of Contents

    Introduction..........................................................................................................................................3Compiling Apache................................................................................................................................3

    Pre-compilation decisions................................................................................................................3Preparation.......................................................................................................................................4

    Preparation on Fedora.................................................................................................................4Compiling........................................................................................................................................4Controlling Apache..........................................................................................................................5Modules...........................................................................................................................................6

    Disabling modules.......................................................................................................................!nabling modules........................................................................................................................"

    #ther con$igure options..................................................................................................................."#ther use$ul modules %e&re not using.............................................................................................."'hich Multi-Processing Module(...................................................................................................)#ur uber con$igure command..........................................................................................................)*ecompiling...................................................................................................................................+,

    +. pgrading the main httpd binar..........................................................................................+,/. Compiling modules staticall into the main Apache binar.................................................+,3. Compiling ne% shared modules............................................................................................++

    Patching.........................................................................................................................................+/Con$iguring Apache............................................................................................................................+3

    De$ault con$iguration.....................................................................................................................+30ie%ing all loaded modules...........................................................................................................+3Initial con$iguration.......................................................................................................................+41tarting2stopping automaticall.....................................................................................................+5

    1tarting2stopping automaticall using chcon$ig on Fedora.....................................................+6eneral serer limits......................................................................................................................+6MPM settings.................................................................................................................................+File laout......................................................................................................................................+"

    1ummar o$ $ilesstem laout..................................................................................................+"ogging..........................................................................................................................................+)

    Adding logging con$iguration.................................................................................................../,

    og rotation using rotatelogs and pipes..................................................................................../+og rotation using logrotate....................................................................................................../+Custom log rotation scripts.......................................................................................................//

    Con$iguring $ile sering................................................................................................................./31a$e de$aults $or sering directories........................................................................................../3#ptions on directories.............................................................................................................../4Allo%#erride7 oerriding serer con$iguration in a director................................................/68iding important $iles.............................................................................................................../61etting the de$ault home page.................................................................................................../1etting the right MIM! tpes..................................................................................................../Compressing content sent to the client...................................................................................../"

    8iding the serer&s identit............................................................................................................/"

    +

  • 8/12/2019 Apache and Php Course

    2/57

    chrooting......................................................................................................................................../)CI.....................................................................................................................................................3,

    Apache and CI.............................................................................................................................3,Improing securit %ith su!9!C and FastCI............................................................................3+

    11.....................................................................................................................................................3/Creating a sel$-signed certi$icate...................................................................................................3/

    Con$iguring Apache to use 11.....................................................................................................33Adding P8P........................................................................................................................................36Pre-installation...............................................................................................................................36Preparation.....................................................................................................................................36Compiling P8P..............................................................................................................................3

    A note on 1!inu:....................................................................................................................3)*emoing P8P..............................................................................................................................3)!:tensions......................................................................................................................................3)*ecompiling P8P..........................................................................................................................4,

    +. Adding a ne% e:tension........................................................................................................4,/. *ecompiling the P8P binar.................................................................................................4,

    Con$iguring P8P............................................................................................................................4,;esting P8P < M1=..................................................................................................................4/;esting P8P&s D e:tension..........................................................................................................43

    .htaccess $iles......................................................................................................................................451etting up authentication b username and pass%ord...................................................................45Authorisation b group..................................................................................................................46*e%riting *s.............................................................................................................................46

    0irtual hosts........................................................................................................................................41etting up >elica.com......................................................................................................................4

    1etting up logging and CI $or a irtual host...........................................................................4)Allo% $ollo%ing o$ smlins....................................................................................................5,Allo%ing directie oerrides.....................................................................................................5,

    0irtual host P8P con$iguration.................................................................................................5,;he $inal con$iguration $ile $or our irtual host.............................................................................5+Fi:ing localhost..............................................................................................................................5/

    ;roubleshooting..................................................................................................................................55ogs...............................................................................................................................................551tatus reports..................................................................................................................................551tandard tools................................................................................................................................56More adanced tools......................................................................................................................56

    icense................................................................................................................................................5

    /

  • 8/12/2019 Apache and Php Course

    3/57

    Introduction;his document outlines ho% to compile? install? and con$igure Apache and P8P on inu:. It is not acomplete manual to the process? but goes through the process step b step? e:plaining the decisionsto be made along the %a.

    'e are %oring to%ards the $ollo%ing scenario7

    A secure? custom built and con$igured Apache %eb serer %ith support $or P8P 5 @includingthe M1= and D e:tensions plus irtual hosts

    11 support $or our main %ebsite

    A de$ault @pacage managed M1= installation? accessible to the Apache serer

    1ome P8P scripts to proe %e can connect to the M1= serer $rom P8P? and that %e canuse the D graphics toolit

    A laout $or irtual hosts7 %e&re going to assume one client? %ith their o%n %ebsite at>elica.com

    A user account $or the irtual host? isolated $rom the main Apache con$iguration? allo%ingthe user to login and edit their %ebsite

    Bote that I %rote these instructions based on buntu? but the should be portable to other inu:distributions. In particular? I hae outlined Fedora-speci$ic issues? as the materials %ere %ritten $or atraining course run using machines installed %ith Fedora.

    Compiling Apache

    Pre-compilation decisions'hich ersion o$ Apache(

    +.:8as been around $or ears? and is a no%n uantit. A sa$e choice.

    /.:Code is much improed? and man o$ the modules hae been reamped. Con$iguration isalso more consistent? and the $ormat $or directies improed. 8o%eer? some people haereserations about using it. Although it is possible to run in a hbrid multi-process2multi-thread mode @using the %orer MPM? man o$ the libraries ou&re liel to use %ith it ma

    not be @e.g. P8P e:tensions. 8o%eer? under normal conditions @i.e. up to tens o$ thousandso$ hits per da? rather than millions? this ersion o$ Apache is liel to be a better solutionthan Apache +.:.

    inar or source(

    1ource E more control ou can patch %hen ou %ant ou can add $eatures %hen ou lie

    inar E easier to manage automatic updates less control

    ia pacage management tool @using indiidual components? e.g. Apt on Debian? *PMon Fedora

    ia a pre-pacaged stac containing all components? e.g. 9AMPP

    @http722apache$riends.org2en2:ampp.html - also gies some o$ the adantages o$ a source

    3

    http://apachefriends.org/en/xampp.htmlhttp://apachefriends.org/en/xampp.html
  • 8/12/2019 Apache and Php Course

    4/57

    installation? as ou can compile ne% modules into it

    ia a pre-pacaged stac? %ith optional certi$ication and support? e.g. 1pie1ource@http722%%%.spiesource.com2do%nloads.html? [email protected](pageEso$t%areGsubEamp

    'e&ll do it $rom source? using ersion /./

    PreparationPreparing the machine ou&re going to install on

    gcc

    #pen11

    #pen11 deelopment headers @libssl-de on buntu

    ntpdate to ensure serer time is accurate

    Perl 5 H allo%s ou to use some o$ the support scripts lie ap:s @$or building and installing

    shared modulesDo%nload the source and chec the archie&s integrit using md5sum lie this7

    root@lily:/home/ell/download# md5sum httpd-2.2.2.tar.bz2

    9c759a97444!de!a!aa2ddbc49d!e" httpd-2.2.2.tar.bz2

    Compare the string on the le$t to the MD5 hash listed on the Apache do%nload site. ;he shouldmatch. I$ the don&t? the do%nload has been corrupted? so do it again.

    Preparation on edora

    #n Fedora? I $ound I needed to install the $ollo%ing ia Add2*emoe 1o$t%are7 Deelopment J Deelopment ibraries < Deelopment ;ools < B#M! 1o$t%are

    Deelopment

    Compilingnpac the tarball

    Beed to get apr up and running $irst7

    cd httpd-/././2srclib2apr.2con$igure --pre$i:E2opt2apache-apr

    mae

    mae install

    ;hen apr-util7

    cd httpd-/././2srclib2apr-util

    .2con$igure --pre$i:E2opt2apache-apr-util --%ith-aprE2opt2apache-apr

    mae

    4

    http://sourcelabs.com/?page=software&sub=amphttp://sourcelabs.com/?page=software&sub=amp
  • 8/12/2019 Apache and Php Course

    5/57

    mae install

    ;hen Apache7

    cd httpd-/././

    .2con$igure --pre$i:E2opt2apache --%ith-aprE2opt2apache-apr --%ith-apr-utilE2opt2apache-apr-util

    mae

    mae install

    ;est7

    2opt2apache2bin2apachectl start @as root

    B ou need to be root i$ the port Apache listens on @isten directie is belo% +,/4 de$aultis port ",

    ;est b isiting http722localhost2 in a %eb bro%ser

    Controlling Apacheps to see the processes Apache starts

    'hen Apache starts? it establishes a parent process as the original user @e.g. root in our case it thenspa%ns child processes to handle reuests. ;he number o$ children is con$igurable @see later.

    ;he PID $ile stores the ID o$ the parent process. It can be sent a ariet o$ standard P#1I9 signalsto control it directl or @better it can be controlled through the apachectl script.

    ;he $iles in the log director are the de$ault Apache logs? as speci$ied b the auto-generated con$ig.

    $ile. errorKlog is use$ul $or debugging? and at the moment contains start2stop in$o. accessKlogrecords reuests sered.

    ;he apachectl script taes a ariet o$ s%itches

    startE start the parent process

    stop@;!*M signal E tell the parent to ill its children it does this immediatel then oncethe&e e:ited? the parent ills itsel$

    graceful@1*+ signal E instruct the parent process to adise the children to e:it theallo% all reuests being sered to complete then the stop then the parent stops then the parent

    restarts itsel$ the parent process then starts ne% children %ith the latest ersion o$ the con$iguration$ile

    graceful-stop@'IBC8 signal E as grace$ul? but no restart a$ter eerthing stops

    restart@8P signal E this restarts its children @as in ;!*M? but doesn&t stop the parentprocess the parent process >ust rereads its con$iguration $ile and carries on running

    statusE sho% short status report @B this needs ln: installed to %or? and modKstatus tobe enabled

    configtestE test %hether the con$ig. $ile is readable and correctl $ormatted

    5

  • 8/12/2019 Apache and Php Course

    6/57

    ModulesModules add e:tra $unctionalit to Apache. ;heir $unctionalit is managed ia Apachecon$iguration directies and each module maes di$$erent directies aailable.

    1tatic- s. dnamicall-loaded modules(

    1tatic E %hole serer < modules in one binar slightl $aster harder to compromise as oucan&t >ust lin ne% modules into it must recompile %hole thing each time ou update usesmore memor

    Dnamic7 ou need to hae modKso enabled @B modKperl should not be compiled as ashared module? according to http722%%%.$as.org2docs2apache-compile2apache.html

    'e&ll do as man as %e can as dnamic modules? %hile eeping the core static

    ;o see the list o$ modules compiled into the httpd binar7

    2opt2apache2bin2httpd -l

    8ere&s %hat I got7

    core.c @es - essential $or the serer to operate

    modKauthnK$ile.c @es - essential $or asic authentication

    modKauthnKde$ault.c @es - essential $or authentication

    modKauthLKhost.c @es - authoriLation b hostname2IP

    modKauthLKgroup$ile.c @es - authoriLation b groups de$ined in a $ile

    modKauthLKuser.c @es - authoriLation b users de$ined in a $ile

    modKauthLKde$ault.c @es - essential $or authoriLation

    modKauthKbasic.c @es - support $or asic authentication

    modKinclude.c @no - unless ou need serer-side includes

    modK$ilter.c @no - proides $iltering o$ resources be$ore the are returned in the response? e.g.Lipping the response bod? do%nsampling eer image sent bac $rom the serer

    modKlogKcon$ig.c @es - allo%s customisation o$ log output

    modKen.c @no - unless need to set and clear enironment ariables $or use %ith CI scripts - e.g.essential i$ running *ub on *ails applications %ith FastCI

    modKseteni$.c @es - supports a lot o$ other modules

    pre$or.c @es

    httpKcore.c @es

    modKmime.c @es - allo%s Apache to correctl delier content based on MIM! tpe

    modKstatus.c @no - sho%s serer status page

    modKautoinde:.c @no - unless ou %ant director inde:es to be sho%n $or directories %ith noinde: $ile

    modKasis.c @no - used to send a $ile %ithout appending response headers to it - so ou could hae a$ile %hich contains a %hole 8;;P response? including headers

    modKcgi.c @no - unless ou %ant CI script support

    6

  • 8/12/2019 Apache and Php Course

    7/57

    modKnegotiation.c @no - it proides a method $or negotiating the best content tpe to suit theclient&s capabilities

    modKdir.c @es - controls the DirectorInde: directie? used to set the de$ault $ile to sere $or adirector? e.g. inde:.php

    modKactions.c @no - triggers CI scripts based on the MIM! tpe o$ a resource reuested - e.g. allreuests $or image2>peg are handed o$$ to a speci$ic CI script

    modKuserdir.c @no - unless ou %ant 2publicKhtml directories $or user home sites

    modKalias.c @es - handles aliasing o$ *s to directories

    modKso.c @es - shared ob>ect support $or dnamic e:tension loading

    !isabling modules

    An modules %e %ant turned o$$ hae to be e:plictl disabled %ith this snta:7

    --disable-M#D!

    For our purposes7--disable-userdir

    --disable-actions

    --disable-negotiation

    --disable-cgi

    --disable-asis

    --disable-autoinde:

    --disable-status

    --disable-en

    --disable-$ilter

    --disable-include

    ; %e can also remoe the remaining modules and mae them dnamicall-loaded7

    --disable-modKauthnK$ile

    --disable-modKauthnKde$ault

    --disable-modKauthLKhost

    --disable-modKauthLKgroup$ile

    --disable-modKauthLKuser

    --disable-modKauthLKde$ault

    --disable-modKauthKbasic

    --disable-modKlogKcon$ig

    --disable-modKmime

    --disable-modKdir

    --disable-modKalias

    Bote %e didn&t disable a $e% o$ the modules? as %e do %ant them staticall compiled @e.g. modKso?%hich enables shared modules to be loaded

  • 8/12/2019 Apache and Php Course

    8/57

    Enabling modules

    !:tra modules %e %ant7

    ssl @support $or 11 - %e&ll put this in staticall

    seteni$ @set enironmental ariables conditional upon modules being loaded

    headers @enable modi$ication o$ reuest2response headersre%rite @$or re%riting reuests - used $or search-engine $riendl *s? $or e:ample

    de$late @$or Lipping content be$ore it is sent to client Nuse$ul i$ client supported gLippedstreams? e.g. Fire$o:O

    cgi @$or running CI scripts

    ;he tpical method @the one %e&ll use is to use shared modules rather than static ones

    'e do this b adding this option to .2con$igure? %ith the names o$ the modules %e %ant to enable7

    --enable-mods-sharedE&seteni$ headers re%rite de$late cgi&ut %e %ill enable 11 as a static module? to ensure it is al%as used and to minimise the

    possibilit o$ the librar being tro>aned.

    --enable-ssl

    'e can also add bac in the modules %hich %ere preiousl staticall-compiled but %hich %e areconerting to dnamicall-loaded modules7

    --enable-mods-sharedE&authnK$ile authnKde$ault authLKhost authLKgroup$ile authLKuserauthLKde$ault authKbasic logKcon$ig mime dir alias&

    Other configure optionsI$ ou %ant to be able to use ap:s? it&s a good idea to speci$ the path to Perl e:plicitl @>ust in casemultiple ersions are installed7

    --%ith-perlEpath to perl e:ecutableJ

    As %e hae turned on ssl? best to e:plicitl set %here #pen11 is installed7

    --%ith-sslEpath to openssl include director? e.g. 2usr2include2opensslJ

    Full list o$ options to con$igure7

    http722httpd.apache.org2docs2/./2programs2con$igure.html

    Other useful modules we're not using8ere are some modules %e&re missing out? but %hich can be er use$ul7

    modKda @'ebDA0 support

    modKldap @base module to support other modules? e.g DAP authentication modules

    modKpro: @use Apache as a pro: to other serers

    "

  • 8/12/2019 Apache and Php Course

    9/57

    modKpro:Kbalancer @$or load balancing

    modKcache @cache local or pro:ied content

    modKhostKalias @automatic mapping o$ *s onto irtual hosts

    Which Multi-Processing Module?pre$or is the de$ault $or inu: - stable? tolerant o$ dodg module code @one process at a timehandles each connection

    %orer is more light%eight? but less tolerant @uses multiple child processes? plus each child hasmultiple threads - each thread handles one connection

    pre$or is the recommended MPM to use i$ ou intend to run P8P as a module @seehttp722%%%.php.net2manual2en2$a.installation.phpQ$a.installation.apache/ ho%eer? i$ ou intendto use FastCI or similar to run P8P? the %orer MPM is stable.

    ;o enable %orer instead o$ pre$or on inu: add the $ollo%ing con$igure option7

    --%ith-mpmE%orer

    Our uber configure commandPutting all o$ this together gies us our master con$igure command7

    .2con$igure --pre$i:E2opt2apache --%ith-aprE2opt2apache-apr --%ith-apr-utilE2opt2apache-apr-util --%ith-perlE2usr2bin2perl --%ith-sslE2usr2include2openssl --disable-userdir --disable-actions --disable-negotiation --disable-cgi --disable-asis --disable-autoinde: --disable-status --disable-en --disable-$ilter --disable-include --disable-modKauthnK$ile --disable-modKauthnKde$ault --disable-modKauthLKhost --disable-modKauthLKgroup$ile --disable-modKauthLKuser --disable-modKauthLKde$ault --disable-modKauthKbasic --disable-modKlogKcon$ig --disable-modKmime --disable-modKdir --disable-modKalias --enable-mods-sharedE&cgi seteni$ headers re%rite de$lateauthnK$ile authnKde$ault authLKhost authLKgroup$ile authLKuser authLKde$ault authKbasiclogKcon$ig mime dir alias& --enable-ssl

    It %ould be a good idea to put this into a script? so ou hae it aailable each time ou recompileApache.

    *emember that once %e&e run con$igure? %e then need to do7

    mae

    mae install

    ;his per$orms the compilation @according to our con$iguration and installs the binaries into theappropriate location @under 2opt2apache.

    Recompiling*ecompiling a ne% ersion o$ Apache @gien an old ersion alread e:ists isn&t too arduous. ;here

    are seeral things %e might %ant to do7

    )

  • 8/12/2019 Apache and Php Course

    10/57

    +. pgrade Apache as a %hole @e.g. moing $rom ersion /./.55 to /./.5

    /. Compile modules staticall into the httpd binar @either ne% ones or e:isting shared ones %e%ant to moe into the core httpd binar

    3. Compile ne% shared modules @either completel ne% ones or e:isting staticall-compiledones

    1ee http722httpd.apache.org2docs2/./2install.html$or more details. #utlines o$ each process are gienbelo%.

    ". #pgrading the main httpd binar$

    Rou can onl do this $or minor ersion number changes? e.g. ersion /./., to /./.+ ou can&t do it togo bet%een ma>or ersion number changes? e.g. /., to /./.

    I$ ou are upgrading? it&s %orth doing it alongside our e:isting installation. Rou could do this bchanging the --pre$i: option to con$igure? so that the ne% ersion ends up in a di$$erent directorand setting a di$$erent isten directie inside the ne% httpd.con$ $ile so our ne% ersion runs on adi$$erent port. #ne ou&re happ? ou can re-run con$igure %ith the correct --pre$i: setting.

    8ere&s the procedure7

    +. Do%nload the ne% source distribution and unpac it

    /. Cop the config.nice$ile $rom our old source tree $or Apache into the top o$ the ne% sourcetree. ;his $ile is basicall a script %hich %ill repla all the con$igure options ou used to

    build the old ersion.

    3. *un the $ollo%ing commands7

    .2con$ig.nicemae

    mae install;he Apache mae $ile %ill not oer%rite e:isting $iles on the serer lie con$iguration [email protected]$ or $iles %hich hae changed. ut it %ill oer%rite the httpd binar and an modules%hich havechanged.

    %. Compiling modules staticall$ into the main Apache binar$

    et&s sa %e hae modKssl compiled as a shared module? and %ant to recompile our httpd binar tostaticall include it instead. 'e can do this as $ollo%s7

    +. Pass an edited set o$ options to the .2con$igure script. For e:ample? let&s sa %e had 11

    compiled as a shared module @a $ragment o$ our con$igure options lines7

    .2con$igure --enable-sslEshared ...

    Change this to compile the module staticall instead7

    .2con$igure --enable-ssl ...

    /. mae

    ;he mae command rebuilds the httpd binar @plus an other $iles %hich hae changed as aresult o$ our recon$iguration

    3. Manuall cop the ne% httpd binar @in the root o$ the build director into our e:isting

    +,

    http://httpd.apache.org/docs/2.2/install.htmlhttp://httpd.apache.org/docs/2.2/install.html
  • 8/12/2019 Apache and Php Course

    11/57

    Apache con$iguration? i.e.

    cp .2httpd 2opt2apache2bin2

    4. *eset the permissions on the ne% binar @see later

    5. *emember to remoe an oadModule lines $or the old shared ersion o$ the module? sothat the staticall-compiled module is used instead.

    6. @#ptional *emoe the shared module $rom the modules director? as it is no longer beingloaded.

    'e could $ollo% the same approach to enable a newstatic module in the httpd binar @rather thanmoe a module $rom being dnamic to static.

    Alternatiel? %e could recompile? then use ma$e installto oer%rite our installation %ith anchanged $iles @see aboe.

    &. Compiling ne' shared modules

    'e could do this to either add a completel ne% shared module? or to moe a static module to beinga shared module.

    ;he ap:s tool can be used to add ne% shared modules into an e:isting Apache installation. ;heprocedure ma ar slightl $rom module to module? but $or the ones %hich are part o$ the coreApache distribution it $ollo%s this pattern7

    +. ocate the module director @in the source tree? under modules. ;he modules are arrangedinto groups? e.g. pro: $or modules %hich handle pro:ing $unctions? mappers $or mappingmodules lie modKre%rite. 'hat %e&re looing $or is the appropriate .c $ile $or the module.

    /. *un the ap:s command %ith the -c @compile and -i @install $lags? e.g.

    2opt2apache2bin2ap:s -c -i -a modKre%rite.c

    ;his compiles up the ne% module binar @.so $ile and deposits it into 2opt2apache2modules.

    3. Bote that the -a s%itch to ap:s automaticall adds a oadModule line to httpd.con$. I$ oudon&t use this s%itch? ou %ill need to manuall add the oadModule directie to httpd.con$oursel$? something lie this7

    %oad&odule rewrite'module modules/mod'rewrite.so

    I$ %e %ant to moe a static module to become a shared module? %e %ill need to recompile the httpdbinar as %ell? and e:clude the old static module @see instructions aboe.

    'e can demonstrate ho% this %ors b compiling a simple module lie modKecho. ;his turns theApache serer into an echo serer %hich repeats bac %hateer ou send to it.

    +. cd Apache source rootJ2modules2echo

    /. 2opt2apache2bin2ap:s -c -i modKecho.c

    3. !dit 2opt2apache2con$2httpd.con$ and add these lines7

    %oad&odule echo'module modules/mod'echo.so(rotocol)cho *n

    4. *estart Apache

    ++

  • 8/12/2019 Apache and Php Course

    12/57

    5. ;est the module has loaded correctl using telnet7

    telnet localhost "+

    ;pe some commands? and the should be echoed bac to ou. ;his is Apache acting as anecho serer? using its ne%l-compiled echo module.

    ;he beaut o$ Apache&s modularit is that it is euall eas to remoe a shared module. 'e cansimpl remoe the oadModule directie in httpd.con$ and %e could additionall remoe the .so$ile itsel$ to be e:tra sa$e.

    Patching#ccasionall? bet%een releases o$ Apache ersions? o$$icial patches ma be released $or the currentersion. ;hese patches %ill tpicall implement important securit updates %hich are too ital to%ait until the ne:t $ull release. ;he are $airl rare? but ou should chec $or applicable patches

    be$ore compiling.

    ;o get the patches? go to the source do%nload director on one o$ the mirror sites? ia the ApacheDo%nloads lin. Inside the main distribution director is a patches director? e.g.

    http722%%%.mirrorserice.org2sites2$tp.apache.org2httpd2patches2

    ;his contains a series o$ directories %ith names in this $ormat7

    apply'to'2.2.+/

    Inside these directories are a series o$ patches $or each released ersion o$ Apache. ;o appl apatch7

    +. Do%nload the patch $ile

    /. Place it in the source director $or Apache3. Appl it to our source %ith7

    patch -s , ile.patch%here $ile.patch is the name o$ the patch $ile ou do%nloaded

    4. con$igure2mae2mae install @see the pgrading section aboe $or more details about thee$$ect o$ this

    +/

    http://www.mirrorservice.org/sites/ftp.apache.org/httpd/patches/http://www.mirrorservice.org/sites/ftp.apache.org/httpd/patches/apply_to_2.2.0/http://www.mirrorservice.org/sites/ftp.apache.org/httpd/patches/http://www.mirrorservice.org/sites/ftp.apache.org/httpd/patches/apply_to_2.2.0/
  • 8/12/2019 Apache and Php Course

    13/57

    Configuring Apache

    Default configuration

    ;he de$ault con$iguration $or our compiled Apache is in 2opt2apache2con$2httpd.con$. ;here areother use$ul $iles containing sample con$iguration $ragments in the 2opt2apache2con$2e:tradirector. ;he can be used $or re$erence or pulled into our main con$ig. $ile as the are? %ith littlemodi$ication.

    iewing all loaded modules;o sho% all loaded modules @including dnamicall-loaded modules once the serer is running7

    2opt2apache2bin2httpd -M

    'hich outputs7

    oaded Modules7

    coreKmodule @static

    mpmKpre$orKmodule @static

    httpKmodule @static

    soKmodule @static

    authnK$ileKmodule @shared

    authnKde$aultKmodule @shared

    authLKhostKmodule @shared

    authLKgroup$ileKmodule @shared

    authLKuserKmodule @shared

    authLKde$aultKmodule @shared

    authKbasicKmodule @shared

    de$lateKmodule @shared

    logKcon$igKmodule @shared

    mimeKmagicKmodule @sharedheadersKmodule @shared

    seteni$Kmodule @shared

    sslKmodule @shared

    mimeKmodule @shared

    dirKmodule @shared

    aliasKmodule @shared

    re%riteKmodule @shared

    1nta: #S

    +3

  • 8/12/2019 Apache and Php Course

    14/57

    B this also checs the snta: o$ the con$ig. $ile can do this %ithout displaing modules using7

    2opt2apache2bin2httpd -t

    !nitial configuration'e hae the option to use a single con$ig. $ile #* spread it out oer multiple $iles. Pros and cons7

    1ingle E eerthing in one place di$$icult to manage %ith lots o$ hosts

    Multiple E clear separation o$ di$$erent aspects o$ con$iguration

    'e&ll use a single $ile $or the main con$ig. plus a separate $ile $or the 11 con$ig.? and one $or eachirtual host.

    'e are also %riting a con$ig. $ile %hich onl %ors $or our compiled ersion o$ Apache. ;he de$aultgenerated $ile proided as an e:ample in the Apache distribution contains a ariet o$ conditionalstatements. ;hese appl di$$erent con$iguration directies depending on the underling operatingsstem? but %e are going to dispense %ith these as much as possible to get a streamlinedcon$iguration $ile.

    1tart %ith a blan con$ig $ile in

    2opt2apache2con$2httpd.con$

    ;hen add7

    # base o the web serer install

    erer0oot /opt/apache

    # name o the web serer 1can help preent

    # startup problems

    erer3ame localhost

    # email address o the administrator

    # 1shown in error messaes

    ererdmin ell@localhost

    # location o the root o the web serer document tree

    6ocument0oot /ar/www/htdocs

    # path to the process 6 1(6 ile8 which

    # stores the 6 o the main pache process

    (idile /ar/run/apache/httpd.pid

    # which port to listen on

    %isten "+

    # do not resole client ( addresses to names 1reduces oerhead

    +4

  • 8/12/2019 Apache and Php Course

    15/57

    ost3ame%oo$ups *

    # eectie user and roup

    ;ser apache

  • 8/12/2019 Apache and Php Course

    16/57

    ln -s 2opt2apache2bin2apachectl 2etc2rc/.d2S/,apache

    Rou also need to mae sure that the net%or is up and the hostname set be$ore ou start the Apacheserer? so a high number lie "5 is suitable.

    Starting(stopping automaticall$ using ch)config on edora

    #n Fedora? %e can use the chcon$ig to add Apache to the startup2shutdo%n seuence. chcon$iguses speciall-$ormatted comments in the start2stop script to determine %hen a serice is started7 at%hich runleels? and %here in the seuence o$ starting2stopping serices.

    +. Mae a smlin $rom the Apache control script to Fedora&s init script director7ln -s /opt/apache/bin/apachectl /etc/rc.d/init.d/apache

    /. Add these e:tra lines to the top o$ 2opt2apache2bin2apachectl7

    ## apache =ontrol script or the pache >>( erer#

    # ch$coni: 45 "5 5# description: pache web serer

    ;he chcon$ig line speci$ies7runKleelsJ startKprioritJ stopKprioritJ

    3. Add Apache to the serices managed b chcon$ig7ch$coni apache on

    4. Con$irm the con$iguration7ch$coni --list apache

    Rou should see something lie this7apache +:o :o 2:o :on 4:on 5:on !:o

    5. #nce %e hae a script in 2etc2rc.d2init.d? %e can use a shortcut to start2stop sericesmanuall7

    serice apache startserice apache stopserice apache restartserice apache raceul

    etc.

    %eneral ser&er limits;here are a range o$ directies %hich goern the generic operating capacit o$ the serer7 $ore:ample? the ma:imum length o$ time to spend %aiting $or a client? the ma:imum number o$ clientconnections allo%ed? %hether to use SeepAlie connections? and so on. ;he most important onesare7

    # time to wait or slow clients? deault is ++8

    # but settin this lower improes resilience

    +6

  • 8/12/2019 Apache and Php Course

    17/57

    # aainst 6* attac$s

    >ime*ut !+

    # $eep-alie allows multiple >>( reuests to be

    # sered oer a sinle >=( reuest?

    # the client needs to eAplicitly mar$ itsel

    # as bein capable o handlin this type o reuest

    # in a reuest header or pache to sere the reuest this way

    Beeplie *n

    # the maA. number o reuests to sere oer a sinle

    # >=( connection? deault is ++8 but the

    # pache manual recommends settin it hiher

    &aABeeplie0euests 2++

    # lenth o time to $eep a connection open while

    # waitin or the neAt reuest in a $eep-alie

    # seuence? deault is 5? lower it on heaily-loaded

    # serers to preent pache leain

    # connections idlin while they wait or clients

    Beeplie>imeout 5

    # maAimum size o reuest body 1+ C no limit

    %imit0euestDody +

    # number o header ields allowed in a reuest

    %imit0euestields ++

    # how lon header ields can be 1in bytes

    %imit0euestieldsize "9+

    # how lon the initial line o a reuest can be

    %imit0euest%ine "9+

    MPM settings'e also need some directies to control the actiit o$ the MPM. For the pre$or MPM @%hich%e&re using %e can speci$ the $ollo%ing7

    # number o spare serers to $eep runnin to

    # handle potential incomin reuests

    &inpareerers 5

    # maA. number o serers to leae idlin

    &aApareerers +

    +

  • 8/12/2019 Apache and Php Course

    18/57

  • 8/12/2019 Apache and Php Course

    19/57

    Path User:group ownership Directory permissions File Permissions

    2opt2apache2con$ root7root ,, -

    2ar2log2apache root7root ,, -

    2ar2run2apache root7root ,, -

    2ar2%%%2htdocs root7root 55 -

    2ar2%%%2cgi-bin root7root 55 -

    8ere are the commands to implement these settings7

    cho%n -* root7root 2opt2apache

    $ind 2opt2apache -tpe d U :args chmod 55$ind 2opt2apache -tpe $ U :args chmod 644

    $ind 2opt2apache2bin -tpe $ U :args chmod u

  • 8/12/2019 Apache and Php Course

    20/57

    !rror message

    ;he leel o$ logging is set in Apache con$ig. using theLogLeveldirectie. ;he possiblesettings are @in order o$ decreasing signi$icance7

    emer!mergencies - sstem is unusable. Child cannot open loc $ile. !:iting

    alertAction must be taen immediatel. getp%uid7 couldn&t determine user name $romuidcritCritical Conditions. socet7 Failed to get a socet? e:iting child

    error!rror conditions. Premature end o$ script headers

    warn'arning conditions. child process +/34 did not e:it? sending another 1I8P

    noticeBormal but signi$icant condition. httpd7 caught 1I1? attempting to dumpcore in ...inoIn$ormational. 1erer seems bus? @ou ma need to increase 1tart1erers? or

    Min2Ma:1pare1erers...debuDebug-leel messages #pening con$ig $ile ...

    1etting the ogeel tells Apache to log all messages o$ that seerit or higher. 1etting theogeel to crit? $or e:ample? %ill report emerg? alert and crit messages. ;he standardsetting is error.

    ;he log is %ritten to the $ile speci$ied b theErrorLogdirectie? %hich speci$ies the path $orthe log $ile? e.g. )rror%o /ar/lo/apache/error'lo

    /. Access log;his logs reuests made to the serer. It is set up b de$ining t%o directies7

    %oormat HIh Il Iu It JHIrJH IKs Ib JHIL0eererMiJHJHIL;ser-entMiJHH combined=ustom%o /ar/lo/apache/access'lo combined

    8ere I am using a standard log $ormat commonl no%n as combined. Bote that ou canre$erence an reuest header using the %{Header}isnta:. Rou can also record responseheaders %ith %{Header}o.

    VJs is the status sent in the response @e.g. /,,? 4,4? 3,/. I$ ou speci$ VJs? the $inalstatus is recorded i$ ou speci$ Vs? the initial status message sent to the reuest isrecorded.

    Adding logging configurationPutting this together $or our setting gies us the $ollo%ing e:tra lines $or httpd.con$7

    # load shared modules

    %oad&odule lo'coni'module modules/mod'lo'coni.so

    # error lo

    %o%eel ino

    )rror%o H/ar/lo/apache/error'loH

    /,

  • 8/12/2019 Apache and Php Course

    21/57

    ,&odule lo'coni'moduleK

    # access lo

    %oormat HIh Il Iu It JHIrJH IKs Ib JHIL0eererMiJHJHIL;ser-entMiJHH combined

    =ustom%o H/ar/lo/apache/access'loH combined

    ,/&oduleK

    Bote I sneaed in a directie to load a shared module here @modKlogKcon$ig.so. ;his is necessarbe$ore %e can start using the directies %hich that module maes aailable in our con$ig..

    I also put the directies %hich depend on this module inside a conditional I$ModuleJ directie.;his means that i$ %e decide to turn o$$ this module at some point? the directies relating to it areignored. ;his maes the con$ig. $ile more stable? and also maes it easier to trac dependencies

    bet%een modules and directies.

    Log rotation using rotatelogs and pipes

    Apache comes %ith a utilit $or rotating logs called rotatelogs. Rou can speci$ that this be used inthe Customog directie b speci$ing a pipe @ U $or the Customog7

    =ustom%o HN/opt/apache/bin/rotatelos -l/ar/lo/apache/access'lo-IO-Im-Id "!4++H common

    @;his command rotates the access log eer /4 hours? and calls the old log$ile accessKlog su$$i:ed%ith the $ull ear? month and da "64,, E /4 hours E 6, T 6, T /4 seconds the -l option $orces theserer to use local time $or the logs rather than M;

    It is also possible to rotate the logs based on siLe @replace the time speci$ication %ith a $ile siLe? e.g.

    5M

    ;here is another log rotation script called [email protected]? %hich o$$ers $iner-grainedcontrol oer logging? but %hich can be used in the same %a as rotatelogs @i.e. ia a pipe.

    Log rotation using logrotate

    logrotateis another solution aailable %ith most inu: distributions. It %ors e:ternall to theprograms it is rotating $or7 ou don&t con$igure it inside httpd.con$? but con$igure logrotate itsel$instead? telling it %hich logs to rotate. logrotate can be used to rotate logs $or an application? andruns as a daemon. 8ere&s a sample con$iguration script $or rotating our Apache logs @adapted $rombuntu&s logrotate con$iguration $or Apache7

    /ar/lo/apache/P'lo L

    # rotate on a daily basis

    daily

    # donQt return an error i there are no P'lo iles

    missino$

    # $eep + copies o los

    rotate +

    /+

  • 8/12/2019 Apache and Php Course

    22/57

    # compress rotated los

    compress

    # wait or another rotation beore compressin los

    delaycompress

    # create new lo iles with mode !++8 owner root8 and roup root

    create !++ root root

    sharedscripts

    # script to run ater rotatin los

    postrotate

    i E - /ar/run/apache/httpd.pid G? then

    /opt/apache/bin/apachectl raceul K /de/null

    i

    endscript

    M

    8ere&s a good re$erence $or creating our o%n logrotation scripts? and %hat the directies mean7

    http722%%%-u:sup.cs:.cam.ac.u2>%352courses2apache2html2:/+6.html

    ;he location to put the con$iguration $ile into depends on ho% the logrotate daemon is con$iguredon the machine in the case o$ Fedora? the aboe con$iguration script %ould be placed in7

    2etc2logrotate.d2apache

    Rou can test our logrotate script manuall using7

    logrotate -$ 2etc2logrotate.d2apache

    Custom log rotation scripts

    It&s prett eas to %rite our o%n log rotation script %hich %ors o$$line. ;his is more e$$icient thanusing piped logs? as it onl reuires a short-lied process %hich runs occasionall to archie the log$iles @unlie rotatelogs? %hich runs continuousl %ith Apache. 8o%eer? it ma be a lesssustainable choice than a dedicated application lie logrotate @see earlier? as ou hae to maintainthe script oursel$? though it should be easier to setup.

    8ere&s a sample script %e could use %ith cron @as the root user to rotate our logs on a dail basis7

    #R/usr/bin/python

    import time

    rom subprocess import call

    rom os import rename

    suiA C Q.Q S time.strtime1QIO-Im-IdQ

    access'lo C Q/ar/lo/apache/access'loQ

    archied'access'lo C access'lo S suiA

    //

    http://www-uxsup.csx.cam.ac.uk/~jw35/courses/apache/html/x2167.htmlhttp://www-uxsup.csx.cam.ac.uk/~jw35/courses/apache/html/x2167.html
  • 8/12/2019 Apache and Php Course

    23/57

    error'lo C Q/ar/lo/apache/error'loQ

    archied'error'lo C error'lo S suiA

    rename1access'lo8 archied'access'lo

    rename1error'lo8 archied'error'lo

    # do a raceul restart

    call1EQ/opt/apache/bin/apachectlQ8 QraceulQG

    'hile saing some CP ccles? this approach also has the adantage o$ eeping log $ile namessimple @>ust accessKlog and errorKlog? as logrotate does. ;his maes con$iguration easier later [email protected]. i$ %e %ant multiple irtual hosts to %rite to the same accessKlog? %e can >ust speci$ the$ilename accessKlog.

    ;he old log $iles are renamed b appending a date su$$i: onto the end o$ the original $ile name. Roucould re$ine this b remoing reall old logs? or Lipping the archied logs.

    NB there appears to be a bug %ith the grace$ul restart command $or Apache /./ @it is recorded onthe Apache bug tracer? %hich causes an error to appear in the logs %hen running the aboe script.8o%eer? this appears to hae no e$$ect on the serer&s operation.O

    Configuring file ser&ing

    Safe defaults for ser*ing directories

    de$ault? Apache %ill sere an $ile it can access. ;his could be problematic i$ a mis-con$iguration made it possible $or Apache to sere critical sstem $iles. 'e can set the de$ault toden access to the %hole $ilesstem b de$ault7

    ,6irectory /K

    *rder 6eny8llow

    6eny rom all

    ,/6irectoryK

    ;he DirectorJ directie allo%s ou to group a set o$ options %hich appl to a speci$ied directorin the $ilesstem @and all its sub-directories. In our case? %e are appling it to 2 @the root o$ the%hole $ilesstem.

    ;he #rder directie is part o$ the host based authentication module @modKauthLKhost. It speci$iesthe order in %hich Den and Allo% directies are applied. In this case? Den directies are applied$irst? then Allo% directies. Access is allo%ed b de$ault. An client %hich does not match a 6enydirectie or does match an llowdirectie %ill be allo%ed access to the director.

    ;he Den directie speci$ies that all hosts are denied access. It is possible to restrict access using IPaddresses? partial IP addresses? net%or2netmas pairs? or net%or2nnn CID* speci$ication? e.g.

    Allo% $rom "/.6".+)4.+5,

    Allo% $rom +,.+

    /3

    http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#denyhttp://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#allowhttp://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#denyhttp://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#allow
  • 8/12/2019 Apache and Php Course

    24/57

    Allo% $rom +,.+.,.,2/55./55.,.,

    Allo% $rom +,.+.,.,2+6

    Rou can also control access b enironment ariable using7

    Allo% $rom enEaccessKgranted

    sing seteni$? ou could set enironment ariables based on arbitrar $eatures o$ the reuest @e.g.particular user agents? re$erer? non-standard headers? %hich could then be used to grant2denaccess.

    'e no% need to allo% access to the de$ault %ebsite director so %e cansere $iles $rom it7

    ,6irectory /ar/www/htdocsK

    *rder llow86eny

    llow rom all

    ,/6irectoryK

    'e need to add these directies? plus the oadModule statement to pull in the module %hichcontrols authentication? to httpd.con$7

    ...

    %oad&odule authz'host'module modules/mod'authz'host.so

    ...

    ,6irectory /K

    *rder 6eny8llow

    6eny rom all

    ,/6irectoryK

    ,6irectory /ar/www/htdocsK

    *rder llow86eny

    llow rom all

    ,/6irectoryK

    'e no% hae enough in place to test %hether %e can sere $iles. All %e need to do no% is7

    +. Change to the root user

    /. Create a $ile in 2ar2%%%2htdocs called inde:.html @an content

    3. *estart Apache

    4. o to http722localhost2inde:.html7 ou should see our content

    +ptions on directories

    ;he #ptions directie coers $ile access con$iguration $or indiidual DirectorJ directies. It

    /4

    http://localhost/index.htmlhttp://localhost/index.html
  • 8/12/2019 Apache and Php Course

    25/57

    allo%s ou to goern $eatures lie e:ecution o$ $iles? $ollo%ing smlins? and sho%ing inde:es o$$iles in a director. 8ere are the options aailable7

    ExecCGI:CI scripts can be e:ecuted in the director

    Followym!in"s:smlins in the director can be $ollo%ed to their target? een i$ outside

    the %ebserer&s document tree @B this one is needed $or modKre%rite? %hich is erimportant $or * re%riting and used b man applications $or 1earch !ngine #ptimisationo$ *s

    ym!in"sIf#wner$atch:onl $ollo% smlins i$ the o%ner o$ the lin is the same as theo%ner o$ the $ile pointed to

    Inclu%es:allo%s serer-side includes

    Inclu%eE'EC:allo%s serer-side includes? but preents the e:ec command being usedin 11Is

    In%exes:%hen on? the serer %ill generate an inde: o$ $iles in a director i$ no de$ault

    resource @lied inde:.html is speci$ied $ulti(iews:allo%s content negotiation @i.e. sere $iles based on user&s language pre$erence

    All:all o$ the aboe are enabled e:cept Multi0ie%s

    &one:none o$ the aboe are enabled

    ;o enable or disable an option? use this snta:7

    *ptions Sollowym%in$s

    *ptions -ndeAes S)Aec=

  • 8/12/2019 Apache and Php Course

    26/57

    ;his no% becomes the de$ault setting $or an directories belo% the root o$ the $ilesstem? including2ar2%%%2htdocs.

    Allo'+*erride o*erriding ser*er configuration in a director$

    ;his directie goerns %hether parts o$ the serer con$iguration can be oerridden using $iles inside

    the %ebserer document tree. For e:ample? %e ma allo% users to speci$ their o%n authorisationdirecties in these $iles? to goern %hich hosts? users? and or groups can access their directories.Con$iguration is oerridden in )htaccess$iles.

    ;he $ollo%ing options speci$ %hich parts o$ the con$iguration can be oerridden in .htaccess $iles7

    #ption Controls o*erri%ing of this type of %irecti*e)))

    AuthCon$ig Authorisation? e.g. *euire? AuthserFile? Auth;pe

    FileIn$o Document tpe? e.g. 8eader? !rrorDocument? *e%ritease

    Inde:es Director inde:ing? e.g. Inde:#ptions? DirectorInde:? De$aultIcons

    imit 8ost access? e.g. Allo%? Den? #rder

    #ption ;he #ptions directie

    All An directie %hich can be oerridden in .htaccess $iles can be oerridden inthis director @i.e. all o$ the aboe

    Bone Bone o$ the aboe .htaccess $iles are ignored

    ;he #ptions oerride is probabl the most con$using7 i$ Allo%#erride #ptions is speci$ied? thenthe de$ault #ptions setting $or the director can be oerridden b a .htaccess $ile in that directorW

    Rou can speci$ %hich directie tpes can be oerridden lie so7

    llow*erride uth=oni %imit

    In our case? $or the root director? %e don&t %ant to allo% anthing to be oerridden7

    ,6irectory /K

    *rder 6eny8llow

    6eny rom all llow*erride 3one

    *ptions 3one

    ,/6irectoryK

    Hiding important files

    de$ault? Apache %ill sere an $ile reuested %hich is %ithin a isible director. ;his includes.htaccess $iles @discussed aboe %hich ma contain important con$iguration in$ormation plus itcould contain bacup $iles @commonl ending %ith .ba or starting %ith ? depending on the editor

    %hich produced them.

    /6

  • 8/12/2019 Apache and Php Course

    27/57

    ;r adding a .htaccess $ile to 2ar2%%%2htdocs? then $etch it in our %eb bro%ser. It should %or#S? %hich isn&t %hat %e %ant.

    'e can globall turn o$$ access to these $iles lie this b putting a FilesMatch directie at the topleel directie o$ our httpd.con$ $ile7

    ,iles&atch H1TJ.htNUVNJ.ba$VHK *rder 6eny8llow

    6eny rom ll

    ,/iles&atchK

    ;his directie can also be applied to indiidual irtual hosts or directories? and can be set in.htaccess $iles i$ Allo%#erride is set to All $or that director.

    Bo% tr getting our .htaccess $ile. It should be protected.

    ;here is also a DirectorMatch directie? %hich can be used to preent sering o$ directories %hosename matches a speci$ied regular e:pression.

    Setting the default home page

    #ne use$ul thing %e can do immediatel is de$ine the de$ault document to sere %hen the root o$ adirector is reuested? e.g. http722localhost2. 'e do this %ith the DirectorInde: directie? %hichneeds modKdir to be loaded7

    %oad&odule dir'module modules/mod'dir.so

    ,&odule dir'moduleK

    6irectoryndeA indeA.html

    ,/&oduleK

    @;est it at http722localhost2

    'hen %e add other tpes o$ $ile @e.g. P8P scripts? %e can add these onto the DirectorInde: tomae them aailable as the de$ault inde: page.

    Setting the right -I-E t$pes'hen ou $etch inde:.html? ou&ll probabl notice that it turns up as plain te:t. I$ ou chec theresponse headers %hen ou $etch inde:.html? ou&ll notice the resource is deliered %ith the MIM!tpe te:t2plain. 8o%eer? %e %ould e:pect an .html $ile to be treated as te:t2html. ;his is because%e haen&t con$igured MIM! handling. ;his $acilit is proided b modKmime? and actiated liethis7

    %oad&odule mime'module modules/mod'mime.so

    ### mime types

    /

    http://localhost/http://localhost/
  • 8/12/2019 Apache and Php Course

    28/57

    6eault>ype teAt/plain

    ,&odule mime'moduleK

    # location o the &&) types coniuration ile

    >ypes=oni con/mime.types

    ,/&oduleK

    ;he mime.tpes $ile maps $ile su$$i:es @.html? .php etc. to MIM! tpes @a MIM! tpe >ustdescribes the ind o$ content a $ile contains? and is used b the client to determine ho% to handle the$ile? e.g. displa in the bro%ser? do%nload? displa in a helper application. Bote that the;pesCon$ig directie is implicit and doesn&t hae to be speci$ied as %e hae here? and it %ill still%or. ut it&s %orth being e:plicit? again to remind us o$ the dependenc bet%een the module andthe mime.tpes $ile in the con$ director.

    ;here is another MIM! module called modKmimeKmagic? %hich uses hints in the $ile to determineits MIM! tpe? as %ell as the $ilename su$$i:. ;his could be help$ul in cases %here ou hae man

    unusual and esoteric $ile tpes? or hae $iles %ithout su$$i:es or incorrect su$$i:es.It is also possible to add our o%n custom MIM! tpes on top o$ the de$ault ones using modKmime.

    Compressing content sent to the client

    ;his is a use$ul option? and one %hich can reduce net%or band%idth usage. It enables Apache tocompress content sent to clients that are able to handle such compressed content @i.e. most modern

    bro%sers.

    +. !nable modKde$late7

    %oad&odule delate'module modules/mod'delate.so

    /. Con$igure compression $or common content tpes7

    dd*utputilterDy>ype 6)%>) teAt/html teAt/plain teAt/Aml

    It is possible to compress other tpes o$ content? but con$iguration is more comple: and reuiresbro%ser sni$$ing @see http722httpd.apache.org2docs2/./2mod2modKde$late.html. ;his con$iguration isstraight$or%ard and %ill %or %ith all bro%sers.

    B Apache %ill onl send compressed content to clients %hose reuests include the $ollo%ingheader7

    ccept-)ncodin: zip8delate

    'e can test this b reuesting our inde:.html $ile? then checing the response headers %hich comebac $rom Apache. ;he should include7

    =ontent-)ncodin: zip

    )iding the ser&er's identit$;he response %e get bac %hen %e reuest a resource on the serer gies a%a some in$ormationabout the serer. Bamel? the response contains a 1erer header %hich loos lie this7

    erer: pache/2.2.2 1;niA

    /"

    http://httpd.apache.org/docs/2.2/mod/mod_deflate.htmlhttp://httpd.apache.org/docs/2.2/mod/mod_deflate.html
  • 8/12/2019 Apache and Php Course

    29/57

    'e can see this using the ie8;;P8eaders in Fire$o:.

    An attacer could use this in$ormation to potentiall determine ulnerabilities in the serer? basedon the serer tpe? ersion? and underling operating sstem. ;here are t%o simple things %e can doto hide this in$ormation in httpd.con$7

    # this line controls whether pache adds inormation about# itsel to the end o serer-enerated documents

    # 1e.. directory indeA paes8 error messaes?

    # * is the deault8 but letQs ma$e it eAplicit

    ererinature *

    # the to$ens displayed in response headers?

    # this sets it to Wust show the serer name 1pache?

    # this can only be set at the serer leel 1not per host

    erer>o$ens (roduct*nly

    I$ ou are reall paranoid? and %ant to disguise the $act ou are using Apache at all? ou can changethe 1erer header in the response to %hateer ou lie using the modKsecurit module @%e&re notgoing to bother7

    erer>o$ens ull

    ecererinature H)lliotQs &iraculous Feb ererH

    Rou can get modKsecurit $rom7

    http722%%%.modsecurit.org2pro>ects2modsecurit2apache2inde:.html

    It&s er eas to install @using the instructions $or compiling ne% Apache shared modules - seeearlier.

    8o%eer? there are still certain aspects o$ the behaiour o$ the serer&s net%oring stac and the%a it $ormats responses %hich can enable the serer&s real identit to be discoered.

    chrootingChroot&ing Apache is another %a to add more securit? b constricting Apache to running in aspeci$ic director. Bo $iles outside the chroot director are accessible to Apache once running.

    ;he traditional method $or chroot&ing Apache is comple: ho%eer? modKchroot is an easier %a tochroot Apache %hich eep things simple7 http722core.seg$ault.pl2hobbit2modKchroot2

    /)

    http://core.segfault.pl/~hobbit/mod_chroot/http://core.segfault.pl/~hobbit/mod_chroot/
  • 8/12/2019 Apache and Php Course

    30/57

    CI;he Common ate%a Inter$ace @CI is a standard $or inter$acing e:ternal applications %ithin$ormation serers? such as 8;;P or 'eb serers. A plain 8;M document that the 'eb daemonretrie*esis static? %hich means it e:ists in a constant state7 a te:t $ile that doesn&t change. A CI

    program? on the other hand? is execute%in real-time? so that it can output %ynamicin$ormation.@$rom http:++hoohoo)ncsa)uiuc)e%u+cgi+intro)html,

    Apache and C%!CI scripts run as processes e:ternal to Apache? and run as the e$$ectie Apache user. !ach time aCI script is reuested b a client? a ne% process is $ired up to handle it. @;his is $airl ine$$icient?and seeral solutions e:ist to alleiate this? as described later. It also means that a poorl-%rittenCI script can hog memor and CP ccles7 again? the solutions described later go some %a tohelping %ith this.

    Common practice is to put CI scripts into a dedicated director. ;his is the most secure %a o$hosting scripts? but the least $le:ible $rom the user&s perspectie.

    +. Create a separate cgi-bin $older in 2ar2%%%2cgi-bin

    /. chmod 55 2ar2%%%2cgi-bin

    3. 1etup CI con$ig. $or that director in 2opt2apache2con$2httpd.con$7

    %oad&odule ci'module modules/mod'ci.so

    ,6irectory /ar/www/ci-binK *rder llow86eny

    llow rom all,/6irectoryK

    4. 'e need to load modKalias so %e can alias a director %hich holds CI scripts7

    %oad&odule alias'module modules/mod'alias.so

    5. Create an alias $or the cgi-bin director7

    criptlias /ci-bin/ /ar/www/ci-bin/

    ;his directie means that an $ile put into the 2ar2%%%2cgi-bin2 director is treated as aCI script also that an * o$ this $orm7

    http722localhost2cgi-bin2filename

    is mapped onto a script calledfilenamein the 2ar2%%%2cgi-bin2 director.

    6. Create a test CI script @I&m using Pthon in the cgi-bin director7

    #R/usr/bin/pythonprint H=ontent->ype: teAt/plainHprint HJnH

    print Hello worldH

    3,

    http://hoohoo.ncsa.uiuc.edu/cgi/intro.htmlhttp://localhost/cgi-bin/filenamehttp://localhost/cgi-bin/filenamehttp://localhost/cgi-bin/filenamehttp://hoohoo.ncsa.uiuc.edu/cgi/intro.htmlhttp://localhost/cgi-bin/filename
  • 8/12/2019 Apache and Php Course

    31/57

    . Mae the script e:ecutable7

    chmod 55 hello.p

    ". ;r accessing it at7 http722localhost2cgi-bin2hello.p

    It is sa$e to use 1criptAlias %here %e are setting up a director to e:ecute CI scripts %hich isoutside the document root $or the serer @i.e. the director is not aailable ia an means other thanthrough the 1criptAlias. 8o%eer? %here %e %ant to allo% CI e:ecution inside a director underthe document root? it is better to use the DirectorJ directie instead.

    For e:ample? i$ %e %anted to allo% Pthon CI scripts under 2ar2%%%2htdocs? %e could enablethem lie this7

    ,6irectory /ar/www/htdocsK

    *rder llow86eny llow rom all

    *ptions )Aec=

  • 8/12/2019 Apache and Php Course

    32/57

  • 8/12/2019 Apache and Php Course

    33/57

    Fill in the reuired in$ormation. ;he important $ields are7

    =ountry 3ame 12 letter code E

  • 8/12/2019 Apache and Php Course

    34/57

    ls 2opt2apache2con$2ssl

    Rou should see serer.e and serer.crt.

    4. 1et permissions on the director7

    cho%n root.root 2opt2apache2con$2ssl

    chmod ,, 2opt2apache2con$2ssl

    5. 1et permissions on the certi$icate and the e7

    chmod 6,, 2opt2apache2con$2ssl2serer.T

    6. Mae a ne% $ile to hold Apache&s 11 con$iguration7

    touch 2opt2apache2con$2ssl.con$chmod 6,, 2opt2apache2con$2ssl.con$

    . Mae a director to store the 11 session cache @this improes per$ormance as it cachessession data and preents unnecessar handshaes? e.g. i$ a single client creates multiple

    parallel connections to the serer7

    mdir 2opt2apache2cachecho%n root.root 2opt2apache2cachechmod ,, 2opt2apache2cache

    ". Put together a minimal 11 con$iguration in ssl.con$7

    %isten 44%=ertiicateile con/ssl/serer.crt%=ertiicateBeyile con/ssl/serer.$ey

    # switch o %2 1which is lawed%(rotocol ll -%2# only support hih-rade encryption%=ipheruite %%:R)X(:R3;%%:R6:R%*F# session cache: type:location1maA'size%ession=ache shmcb:/opt/apache/cache/sslcache152++%ession=ache>imeout ++

    # coniuration to handle bro$en % implementation# in )et)n ;ser-ent H.P&).PH J no$eepalie ssl-unclean-shutdown J

    downrade-.+ orce-response-.+

    # coniure the deault site to be aailable oer %# as well as standard >>(,Yirtualost localhost:44K %)nine on erer3ame localhost:44 6ocument0oot /ar/www/htdocs =ustom%o /ar/lo/apache/access'lo combined )rror%o /ar/lo/apache/error'lo,/YirtualostK

    34

  • 8/12/2019 Apache and Php Course

    35/57

    ). Pull the con$iguration $ile into the main httpd.con$ $ile7

    nclude /opt/apache/con/ssl.con

    +,. ;est at7

    https722localhost2

    Bote that ou %ill be prompted to accept the certi$icate? as it is sel$-signed and cannot betraced bac to a recognised certi$icate authorit.

    35

    https://localhost/https://localhost/
  • 8/12/2019 Apache and Php Course

    36/57

    Adding PHP

    Pre-installation

    ;here are seeral choices to mae7+. .hich *ersion: / or 0 or 1oth2

    P8P 5 is stable? and superior to ersion 4 in its support $or ob>ect-oriented programming. Itis also possible to run P8P 5 in ersion 4 compatibilit mode? %hich should proide near-

    per$ect support $or P8P 4 scripts.

    An alternatie is to install both? and select the ersion to use as $ollo%s7

    +. per-host @b setting an Add8andler directie $or a %hole irtual host %hich speci$ies theP8P ersion to use

    /. per-director @b setting an Add8andler directie inside a director? either in a .htaccess

    $ile or in httpd.con$

    3. per-$ile @b setting a handler $or $iles %ith a speci$ic $ile su$$i:? e.g. .php4? in httpd.con$or .htaccess

    'e are going to install P8P 5.

    /. Do you want we13 comman% line3 an%+or GUI2I$ ou don&t need command line or I support? leae them out %hen compiling P8P.

    3. .ill it 1e use% 1y untruste% users2In situations %here the serer %ill onl be used b trusted users? P8P can sa$el be run as amodule. In this situation? P8P runs inside the main serer process? under the Apache

    e$$ectie user. 'here some untrusted users ma be using the serer to run P8P scripts? asa$er setup is to use standard CI? CI %ith an e:ecution %rapper lie su!9!C? or P8Punder FastCI. ;his isolates the P8P process $rom Apache and is sa$er it also means thatApache is potentiall $aster? as it isn&t also running P8P? so static $ile delier ma bespeeded up.

    'e are going to install as a module? as this is the simplest approach? and good $or mostgeneral purpose use.

    Preparation

    Rou %ill need the $ollo%ing pieces o$ so$t%are to compile P8P on buntu7 $le:

    bison

    autocon$

    M1=

    M1=-de @libmslclient+4-de on buntu

    lib>peg-de? libpng-de? lib:pm-de? lib%m$-de? libungi$? lib$reetpe6-de etc. @to getsupport $or di$$erent image $ormats and truetpe $onts in D

    36

  • 8/12/2019 Apache and Php Course

    37/57

    Compiling P)PDo%nload $rom php.net

    Compare %ith the md5sum @as %e did $or Apache

    npac

    Connect to the unpaced director

    ;o compile P8P? %e need to re$erence a couple o$ graphics librar $iles. #n buntu? this isn&t aproblem but on Fedora @at least in ersion 5? the graphics libraries hae non-standard names %hichcause compilation to $ail. 'e can $i: this b smlining the real graphics libraries to correctl-named $iles lie this7

    ln -s 2usr2lib2lib>peg.so.6/ 2usr2lib2lib>peg.so

    ln -s 2usr2lib2lib9pm.so.4 2usr2lib2lib9pm.so

    *un the con$igure script lie this7

    .2con$igure --pre$i:E2opt2apache2php --%ith-ap:s/E2opt2apache2bin2ap:s --%ith-con$ig-$ile-pathE2opt2apache2con$ --enable-memor-limit --%ith-pearE2opt2apache2php2pear --%ithout-pgsl --%ith-mslEshared --%ith-msliEshared --%ith-pdo-mslEshared --%ith-gdEshared--%ith-LlibEshared --%ith-$reetpe-dirE2usr2lib --%ith-:pm-dirE2usr2lib --%ith->peg-dirE2usr2lib--%ith-gette:tE2usr2lib

    ;he options I&e used here speci$ the $ollo%ing7

    --pre$i: E %here to install

    --%ith-ap:s/ E location o$ the ap:s binar @$or installing the P8P module into Apache

    --%ith-con$ig-$ile-path E %here the php.ini $ile %ill be

    --enable-memor-limit E compile %ith memor limit support

    --%ith-pear E install pear @pacaging mechanism $or P8P e:tensions

    --%ithout-pgsl E disable support $or Postgre1=

    --%ith-!9;!B1I#BEshared E enable the $ollo%ing e:tensions as shared

    msl E include support $or M1=msli E improed M1= e:tension

    pdo-msl E enable PD# support $or M1= @PD# is a ne% database inter$ace in P8P 5

    Llib E enable support $or the Llib e:tension @stream compression support

    gd E enable P8P D support @$or image manipulation and creation

    --%ith-$reetpe-dir? --%ith-:pm-dir? --%ith->peg-dir E path to Freetpe29PM2XP! handlinglibraries @B compiling against Freetpe is the easiest %a to enable P8P $ont-rendering $unctions%ithin D

    --%ith-gette:t E location o$ the B gette:t libraries use$ul $or internationalisation

    3

  • 8/12/2019 Apache and Php Course

    38/57

    Bote that there is a de$ault set o$ e:tensions installed %ith P8P %hich is $airl sane? so %e %illleae them as is. I$ ou %ant to turn an o$ them o$$? use7

    --disable-!9;!B1I#B

    #*

    --%ithout-!9;!B1I#B

    @use ./coniure --helpto %or out %hich ou&ll need $or a gien e:tension

    ;hen run these commands to compile and install7

    mae

    mae install

    Be:t %e need to cop the recommended P8P con$ig. $ile to the location %here %e told ourcompiled P8P it %ould be7

    cp php.ini-recommended 2opt2apache2con$2php.inicho%n root7root 2opt2apache2con$2php.inichmod 6,, 2opt2apache2con$2php.ini

    'hen %e ran ma$e install? it added this line to 2opt2apache2con$2httpd.con$7

    %oad&odule php5'module modules/libphp5.so

    @I$ ou recompile P8P and do ma$e install? it ma add another line lie this to httpd.con$?%hich %ill brea Apache. Rou can $i: it b >ust remoing the repeated line.

    ;ell Apache %hich $iles to treat as P8P scripts7

    ddandler application/A-httpd-php .php

    And to treat inde:.php as a possible de$ault home page %hen a %ebsite root is reuested7

    6irectoryndeA indeA.html indeA.php

    ;o test our installation7

    +. cd 2ar2%%%2htdocs

    /. create a ne% $ile called in$o.php %ith this content7

    ,Zphp

    phpino1?

    ZK

    3. ;est at http722localhost2in$o.php

    Rou should see a screen %ith in$ormation about our P8P settings? loaded modules? etc.

    3"

    http://localhost/info.phphttp://localhost/info.php
  • 8/12/2019 Apache and Php Course

    39/57

  • 8/12/2019 Apache and Php Course

    40/57

    eAtensionCpdo'mysl.so

    eAtensionCd.so

    eAtensionCzlib.so

    I$ ou %ant to chec the e:tensions %hich hae been compiled in as shared? hae a loo in thee:tensionKdir @de$ined aboe. Rou should see a .so $ile $or each shared module.

    Rou can also see a list o$ all e:tensions b doing7

    2opt2apache2php2bin2php -m

    though this doesn&t discriminate bet%een shared and static e:tensions.

    Recompiling P)P

    ". Adding a ne' extension

    'e can compile ne% e:tensions into our P8P installation using the phpiLe tool. ;his is similar toap:s? but intended $or installing P8P e:tensions. 'e&ll install the mbstring e:tension this %a7

    +. o to the P8P source tree

    /. cd e:t2mbstring

    3. 2opt2apache2php2bin2phpiLe;his prepares the source in the current director $or compilation as a P8P e:tension

    4. .2con$igure --%ith-php-con$igE2opt2apache2php2bin2php-con$ig

    5. mae

    6. mae install

    . !dit 2opt2apache2con$2php.ini and add this line7

    eAtensionCmbstrin.so

    ". Chec the e:tension is loaded using7

    2opt2apache2php2bin2php -m

    or b using phpin$o@.

    %. /ecompiling the PHP binar$

    I$ %e re-run .2con$igure at the top o$ the source tree %ith e:tra options? the P8P binar %ill berecon$igured. As $ar as I can tell? it&s best to do a mae clean to clean the preiousl-compiledersion completel out o$ the build tree @B this doesn&t a$$ect the installed P8P? >ust the build tree.'e can then do the standard mae2mae install to update the P8P binar inside our Apacheinstallation.

    Configuring P)P'e&e alread checed our P8P con$iguration using the phpin$o@ command.

    ;he con$ig. $ile consists o$ a bunch o$ directies i$ the directie is commented %ith a semi-colon?

    4,

  • 8/12/2019 Apache and Php Course

    41/57

    the de$ault alue sho%n is set.

    Bo% %e are going to hae a loo at the con$iguration $ile and sstematicall cut it do%n and tightenit up.

    +. Mae a cop o$ the $ile @be$ore %e start butchering it.

    /. *emoe the big blocs o$ comments. ;his >ust maes the con$ig. $ile a bit easier to read.

    3. Delete an sections in the con$ig. $ile %hich don&t appl to our setup @i.e. $or con$iguringe:tensions %e&re not using. 1tart at the end o$ the $ile and remoe an sections headed NO%hich aren&t reuired.

    4. Add pear to the include path7

    include'path C H.:/php/includes:/opt/apache/php/pearH

    ;his ensures that i$ %e install an P!A* e:tensions? the are aailable to our P8P scripts.

    5. 1tarting $rom the top and %oring do%n7i. safe4mo%e:'hen sa$eKmode is on? P8P does a chec %hen a script calls a $unction

    %hich tries to access a $ile on the $ilesstem. I$ the o%ner o$ the script and the o%nero$ the $ile are di$$erent? P8P does not allo% the operation. @B this can be rela:edusing the sa$eKmodeKgid directie.

    ii. expose4php:turn it to #$$ i$ ou don&t %ant P8P to add itsel$ to the Apacheresponse headers.

    iii. memory4limit:"M is uite lo%? and ma cause problems %ith certain scripts asetting o$ 64M is more realistic.

    i. %isplay4errors:eae this o$$ on a production serer and log errors to a $ile instead.

    Rou can turn it on in indiidual scripts i$ ou need it %ith7

    ini'set1Hdisplay'errorsH8 ?

    Rou should also mae sure %isplay4startup4errors is set to #$$.

    . error4log:log errors into a $ile? rather than displaing them in the response7

    error'lo C H/ar/lo/php/php'loH

    B logKerrors must be set to #n $or this to %or.

    i. register4glo1als:set to #$$. Do not turn it on7 it is er dangerous and can openulnerabilities in poorl-%ritten scripts.

    ii. allow4url4fopen:set to #$$. I$ #n? this allo%s P8P scripts to open $iles on remoteserers ia $tp or http.

    iii. magic45uotes4gpc:set this to #$$. It is con$using i$ it&s turned on? as it automaticallescapes uotes in P#1; data.

    i:. file4uploa%s:turn on i$ ou %ant to globall allo% $ile uploads ia P8P scripts.

    :. ena1le4%l:turn this #$$ i$ #n? it allo%s users to load their o%n e:tensions $rom%ithin a P8P script.

    :i. sen%mail4path:set the path to the sendmail binar i$ it is in a non-standard location?

    4+

  • 8/12/2019 Apache and Php Course

    42/57

    or not on the apache user&s path

    :ii. session)sa*e4path:the path to the director into %hich session data is saed set it to2ar2%%%2sessions

    :iii. session)referer4chec":set to the domain name $or the Apache serer this ensuresthat session cooies are onl accepted i$ the client&s re$erer contains this string in ourcase? %e can set it to localhost.

    As P8P runs as the apache user? and %e hae tightened access to 2ar2log2apache? %e %ill setup aseparate log director $or P8P. ;his director %ill be %riteable b the apache user @2ar2log2apacheisn&t? $or securit reasons? and rather than mae 2ar2log2apache %riteable? it&s better to put P8P logsinto a di$$erent? less-secure director7

    mdir 2ar2log2php

    cho%n apache.apache 2ar2log2php

    chmod ,, 2ar2log2php

    @'e could also appl log rotation to these logs? as %e did $or the Apache logs.

    'e also need a separate director to sae session data7

    mdir 2ar2%%%2sessions

    cho%n apache.apache 2ar2%%%2sessions

    chmod ,, 2ar2%%%2sessions

    esting P)P . M$"/(@I&m assuming ou hae a M1= setup on our machine. I&m not going to e:plain ho% to do that

    7.

    First %e need a database? a table? and some data7

    +. 1tart the msl command line client in a terminal

    /. At the msl prompt7

    use test

    create table people @id IB; A;#KIBC*!M!B;? name 0A*C8A*@/55?P*IMA*R S!R@id

    insert into people alues@+? &!lliot 1mith&

    insert into people alues@/? &Mice Mouse&

    e:it

    3. 'rite a P8P script to access our M1= database @not secure - root has no pass%ord in me:ampleW7

    ,Zphp

    mysl'connect1QlocalhostQ8 QrootQ?

    mysl'select'db1QtestQ?

    Vresult C mysl'uery1Q)%)=> P 0*& peopleQ?

    4/

  • 8/12/2019 Apache and Php Course

    43/57

    while1Vrow C mysl'etch'assoc1Vresult L

    echo VrowEQnameQG . Q,br/KQ?

    M

    ZK

    And a short script using PD#&s M1= $unctionalit7

    ,Zphp

    Vdbh C new (6*1Qmysl:hostClocalhost?dbnameCtestQ8 QrootQ?

    oreach 1Vdbh-Kuery1Q)%)=> P 0*& peopleQ as Vrow L

    echo VrowEQnameQG . Q,br/KQ?

    M

    Vdbh C null?

    ZK

    esting P)P's %D e,tension'e can test the D P8P e:tension %ith a short script. It&s %orth doing this? as D relies on seeralother installed libraries? and it&s best to chec the are being re$erenced correctl.

    Create a ne% $ile in 2ar2%%%2htdocs2gdKtest.php %ith this content7

    ,Zphp

    Vim C imaecreatetruecolor14++8 ++?

    Vblac$ C imaecolorallocate1Vim8 +8 +8 +?

    Vwhite C imaecolorallocate1Vim8 2558 2558 255?

    Vont C Q/ar/lib/deoma/A-ttcidont-con.d/dirs/>rue>ype/rial'Dlac$.ttQ?

    imaeilledrectanle1Vim8 +8 +8 4++8 ++8 Vwhite?

    imaettteAt1Vim8 +8 +8 +8 4+ 8 Vblac$8 Vont8 Qello ForldRQ?

    header1Q=ontent->ype: imae/pnQ?

    imaepn1Vim?

    ZK

    Rou ma need a di$$erent $ont path7 use

    locate tt$

    or

    43

  • 8/12/2019 Apache and Php Course

    44/57

    $ind 2 -name T.tt$

    to $ind the ;rue;pe $onts on our sstem.

    #n Fedora? ou could use7

    2usr2share2$onts2bitstream-era20era.tt$

    $or e:ample.

    ;est b bro%sing to http722localhost2gdKtest.php

    44

  • 8/12/2019 Apache and Php Course

    45/57

    .htaccess files;hese $iles can be used to set local con$iguration $or a director @and its subdirectories. ;he arecommonl used to speci$ authentication and authorisation setup? but can also be used to set customhandlers? re%rite rules? P8P con$iguration? and so on @in $act? ou can set an directies enabled $or

    the director? as speci$ied b Allo%#erride.

    Bote that an con$iguration ou can do in a .htaccess $ile can also be done inside the main Apachecon$iguration $iles. I$ ou hae control oer the main con$ig. $iles? use them instead o$ doingcon$iguration inside .htaccess $iles? as it means our con$ig. %ill be centralised and easier tomanage.

    "etting up authentication b$ username and password+. 1%itch to the root user

    /. Allo% con$iguration $or the document root director to be oerridden in .htaccess $iles b

    modi$ing httpd.con$7

    ,6irectory /ar/www/htdocsK llow*erride ileno uth=oni %imit,/6irectoryK

    3. Create the director %e %ant to secure7

    mdir 2ar2%%%2htdocs2secure

    4. Create an inde:.php $ile inside the secure director.

    5. 'e need to load the modules reuired to do user and group authentication and authorisation7

    %oad&odule authn'ile'module modules/mod'authn'ile.so%oad&odule auth'basic'module modules/mod'auth'basic.so%oad&odule authz'user'module modules/mod'authz'user.so%oad&odule authz'roupile'module modules/mod'authz'roupile.so

    6. Create a data director %hich %ill contain the con$iguration $iles $or authentication7

    mdir 2opt2apache2datacho%n root7root 2opt2apache2data

    chmod ++ 2opt2apache2data

    . Create the $ile %ith the user data using the htpass%d program7

    2opt2apache2bin2htpass%d -c 2opt2apache2data2pass%ords elliot

    ;he -c s%itch tells the command %here to create the pass%ords $ile elliot is the user %e arecreating. Rou %ill be prompted to enter a pass%ord then con$irm it.

    ". Create a .htaccess $ile in 2ar2%%%2htdocs2secure2.htaccess to protect the secure director7

    uth>ype Dasic

    45

  • 8/12/2019 Apache and Php Course

    46/57

    uth3ame Hecure areaHuth;serile /opt/apache/data/passwords0euire alid-user

    ). ;est at http722localhost2secure2. Rou should be prompted $or a username and pass%ord.

    Authorisation b$ group;he aboe can be easil e:tended to do group authentication7

    +. Create a groups $ile in 2opt2apache2data2groups %ith this content7

    administrators: elliot

    /. Modi$ 2ar2%%%2htdocs2secure2.htaccess to authorise b group7

    uth>ype Dasic

    uth3ame H0estricted ilesHuth;serile /opt/apache/data/passwordsuth

  • 8/12/2019 Apache and Php Course

    47/57

    0irtual hostsN#nl about +,,, irtual hosts are possible per Apache instance using the approach detailed in thissection. eond this limit? it is better to use an optimised solution lie modKhostKalias instead.O

    0irtual hosting allo%s *unning multiple %ebsites on a single machine.

    ;%o methods7 IP-based or name-based

    +. Bame-based is simplest and reuires $e%er IP addresses @%hich are a scarce resource.

    /. IP-based is more comple: and needs one IP address $or each host. For 11 sites on di$$erenthosts? must use IP-based hosting @can&t hae multiple 11 sites on a single IP address.

    'e&re going to use name-based irtual hosts.

    #ur aim is to eep $iles related to an indiidual irtual host in one location resered $or that hostan core Apache log $iles etc. remain in a central location. ;his is the laout $or each host7

    2ar2%%%2>elica.com7 base path $or the irtual host

    2ar2%%%2>elica.com2data @priate %eb serer2application data - e.g. things lie pass%ords$or P8P applications? %eb serer pass%ord $iles generated using the htpass%d command? or1=ite database $iles

    2ar2%%%2>elica.com2htdocs @public $iles? P8P scripts? 8;M

    2ar2%%%2>elica.com2cgi-bin @publicl-accessible CI scripts

    2ar2%%%2>elica.com2log @logs $or this host

    2ar2%%%2>elica.com2tmp @temporar $iles? e.g. $iles uploaded using P8P

    In cases %here %e are using chrooting? %e might also hae the $ollo%ing7

    2ar2%%%2>elica.com2bin @priate binaries e:ecuted b this host allo%s us to isolatedi$$erent binaries $or di$$erent hosts? e.g. i$ one host reuires P8P 5 and another %ants P8P4

    'e&ll miss this last one out o$ our irtual host con$iguration? $or simplicit&s sae.

    'e are also going to store each irtual host con$iguration in its o%n con$iguration $ile? named a$terthe host. For e:ample? $or our >elica.com and oceanarea.com hosts? %e %ill put their con$igurationin these t%o $iles7

    +. 2opt2apache2con$2>elica.com.con$

    /. 2opt2apache2con$2oceanarea.com.con$

    I am not going to coer ho% to setup a machine to restrict a user to their o%n irtual hostdirectories? %ith no access to the rest o$ the $ilesstem. @1ee the earlier section on chroot.

    "etting up 1elica2com+. Create the user in charge o$ the domain7

    useradd --home 2ar2%%%2>elica.com >elicacom

    /. Mae the user&s home director accessible to Apache7

    chgrp apache 2ar2%%%2>elica.comchmod gelica.com

    4

  • 8/12/2019 Apache and Php Course

    48/57

    3. Create an htdocs director $or the user inside their home director7

    mdir 2ar2%%%2>elica.com2htdocscho%n >elicacom7apache 2ar2%%%2>elica.com2htdocschmod /5, 2ar2%%%2>elica.com2htdocs

    Bote that the last command also changes the stic bit on the director @the &/& at the start o$the argument to chmod? so that an $iles added to the director end up being o%ned b theapache group.

    4. Mae an inde: $ile $or the domain in 2ar2%%%2>elica.com2inde:.php

    5. Create the con$iguration $ile $or the domain in 2opt2apache2con$2>elica.com.con$

    ,Yirtualost P:"+K 6ocument0oot /ar/www/Welica.com/htdocs erer3ame Welica.com

    ,6irectory /ar/www/Welica.com/htdocsK *rder llow86eny llow rom all ,/6irectoryK,/YirtualostK

    6. 1et permissions7

    chmod 6,, 2opt2apache2con$2>elica.com.con$

    . Add the directie to mae Apache attach irtual host de$initions to all IP addresses o$ theserer7

    3ameYirtualost P:"+

    I$ ou had a machine %ith multiple IP addresses? ou could >ust set up one or t%o o$ these tosere irtual hosts $rom? e.g.

    Bame0irtual8ost ++.+/.+3.+47",

    ". Pull the >elica.com con$iguration $ile into httpd.con$7

    nclude /opt/apache/con/Welica.com.con

    ). Create a $ile in 2home2>elicacom2htdocs $or testing called inde:.php

    +,. Add an entr to 2etc2hosts to map the domain name >elica.com to the localhost IP address.;his enables to test our ne% irtual host %ithout haing to register the domain name etc..

    +/.,.,.+ >elica.com

    ++. ;est at http722>elica.com2

    +/. ;est user login b attempting to login ia ssh7

    ssh>elicacomYlocalhost

    Mae sure the logged in user ends up in the 2ar2%%%2>elica.com director.

    4"

    http://jelica.com/mailto:jelicacom@localhosthttp://jelica.com/mailto:jelicacom@localhost
  • 8/12/2019 Apache and Php Course

    49/57

    Setting up logging and CI for a *irtual host

    'e can setup the logs and CI $or the irtual host lie this7

    +. Mae directories $or the logs and CI scripts inside the irtual host&s director7

    mdir 2ar2%%%2>elica.com2logs

    mdir 2ar2%%%2>elica.com2cgi-bin

    /. 1et permissions on the directories7

    cho%n -* >elicacom7apache 2ar2%%%2>elica.comchmod /, 2ar2%%%2>elica.com2logschmod /5, 2ar2%%%2>elica.com2cgi-bin

    Bote the cgi-bin is set up the same as the htdocs director. 8o%eer? the logs director issetup to allo% the apache user to %rite into the director.

    3. Add these directies to >elica.com.con$? inside the 0irtual8ostJ directie7

    ,Yirtualost P:"+K 6ocument0oot /ar/www/Welica.com/htdocs erer3ame Welica.com

    ,6irectory /ar/www/Welica.com/htdocsK *rder llow86eny llow rom all ,/6irectoryK

    # error lo

    )rror%o /ar/www/Welica.com/los/error'lo

    # access lo

    ,&odule lo'coni'moduleK

    =ustom%o /ar/www/Welica.com/los/access'lo combined

    ,/&oduleK

    # ci-bin

    ,6irectory /ar/www/Welica.com/ci-binK

    *rder llow86eny

    llow rom all

    ,/6irectoryK

    criptlias /ci-bin/ /ar/www/Welica.com/ci-bin/

    ,/YirtualostK

    4)

  • 8/12/2019 Apache and Php Course

    50/57

  • 8/12/2019 Apache and Php Course

    51/57

    'e also hae to set the session.re$ererKchec to >elica.com. 8o%eer? i$ %e are allo%ingdomain paring? %e might %ant to remoe this constraint7 i$ a cooie is set under the pareddomain? the re$erer @%hen the cooie is passed to the ne:t page %ill re$erence the pareddomain? causing P8P to re>ect the cooie @as the re$erer is %rong.

    For the aboe to %or? %e %ill need a sessions director7

    mdir 2ar2%%%2>elica.com2sessionscho%n >elicacom.apache 2ar2%%%2>elica.com2sessionschmod /, 2ar2%%%2>elica.com2sessions

    4. php'admin'la ile'uploads onphp'admin'la upload'tmp'dir /ar/www/Welica.com/tmp

    ;hese settings allo% users to upload $iles using their P8P scripts.

    Again? ou %ill need a tmp director $or the irtual host7

    mdir 2ar2%%%2>elica.com2tmpcho%n >elicacom.apache 2ar2%%%2>elica.com2tmpchmod /, 2ar2%%%2>elica.com2tmp

    5. #ne more use$ul tric is to enable users to create $iles $rom inside their P8P scripts. Forno%? %e %ill enable P8P to %rite onl into the htdocs director.

    ;he $irst step is to allo% the apache user to %rite to the htdocs director7

    chmod gelica.com2htdocs

    ;he onl issue %ith allo%ing apache to create $iles inside htdocs is that the $iles created this%a %ill not be editable b the irtual host&s o%ner @in this case? >elicacom. #ne solution isto add the user to the apache group7

    usermod - >elicacom?apache >elicacom

    8o%eer? this could potentiall gie the user access to $iles in other irtual hosts @i.e. an$ile o%ned b the apache group.

    he final configuration file for our &irtual hostCombining these settings together inside the DirectorJ setting $or the irtual host @in2opt2apache2con$2>elica.com.con$ gies us7

    ,Yirtualost P:"+K

    6ocument0oot /ar/www/Welica.com/htdocs

    erer3ame Welica.com

    ,&odule php5'moduleK

    php'admin'alue open'basedir /ar/www/Welica.com

    5+

  • 8/12/2019 Apache and Php Course

    52/57

    php'admin'alue error'lo /ar/www/Welica.com/los/php'lo

    php'admin'alue session.sae'path /ar/www/Welica.com/sessions

    php'admin'alue session.reerer'chec$ Welica.com

    php'admin'la ile'uploads on

    php'admin'alue upload'tmp'dir /ar/www/Welica.com/tmp

    ,/&oduleK

    ,6irectory /ar/www/Welica.com/htdocsK

    *rder llow86eny

    llow rom all

    *ptions ym%in$s*wner&atch