Академический Документы
Профессиональный Документы
Культура Документы
ThisapproachhasanobviousadvantageoverWebserversthatuseasingleprocesstorespondtoallrequests:If theInternetInformationServer(IIS)processdiesonaWindowsWebserver,nofurtherrequestsareserveduntil theprocessisrestarted.IfasingleApacheprocessdies,onlytherequestbeingservedbythatprocessisaffected #httpdv Serverversion:Apache/2.0.40 Serverbuilt:Feb25200305:01:56 Isourserverastaticordynamicallybuiltone? Ifstatic,whichmodulesarecompiledinstatically? #httpdl core.c prefork.c<preforkMPMandoursisahardcoredynamic http_core.cserverwithDSOcapability mod_so.c<DSOcapabilityhastobestaticallybuiltinto thebinary
=================== #./configureenablemodules=all #make #makeinstall Allelsegivenbelowismerelydetail. BcoswecompileALLavailablemodulesasDSOsandlaterwecancomment outthedirectivesintheconfigfileforthemodules whichwedonotwant! Withastaticserverwecannotdothisandwillhavetorecompilethe servereverytimewemakeachange ./configureprefix=/usr/local/apache2b/enablemodsshared=all\ enableaccess=static #/usr/local/apache2b/bin/apachectll Compiledinmodules: core.c prefork.c<ThePreforkMPM[def] http_core.c mod_so.c<EnablesDSOcapabilityhenceyoucanaddmore moduleslaterasDSOs access.c<Thismodulenowinthebinary Download2.xApacheandcompile Apchecompiling #./configureprefix=/usr/local/apache2enablesoenablerewrite enablespellingenablesslenableuniqueidenableusertrack enabledeflatenableexpiresenableauthanonenableauthdbm enableauthdigestenablelogioenablemimemagic enablemodules=mostenableheadersenableinfo enablev4mappedenableproxybalancerenableproxyenabledbd enableproxyajp&&echodonecon canfilterthesemodulesasperreq --enable-auth-dbm -enable-auth-anon -enable-unique-id auth_anon_module --enable-usertrack enableauthdigestenableproxybalancerenableproxyajp configureoptions
http://httpd.apache.org/docs/2.0/programs/configure.html
http://httpd.apache.org/docs/1.3/mod/core.html
NameBasedVirtualHosing
http://www.uracad.kharkiv.edu/manual/vhosts/details.html http://www.uracad.kharkiv.edu/manual/vhosts/examples.html
Redirecting Redirect Redirect / http://altnix.com will redirect to default altnix.co m document root Redirect /old.html
http://altnix.com/new.html
document root and check can be done with different
http://altnix.com/old.html
the above will redirect sites.please try. to new.html.this
directory
Enter this line in your .htaccess file: Redirect permanent /oldfile.html http://www.domain.com/filename.html You can repeat that line for each file you need to redirect. Remember to include the directory name if the file is in a directory other than the root directory: Redirect permanent /olddirectory/oldfile.html http://www.domain.com/newdirectory/newfile.html If you have just renamed a directory you can use just the directory name: Redirect permanent /olddirectory http://www.domain.com/newdirectory (Note: The above commands should each be on a single line, they may be wrapping here but make sure they are on a single line when you copy them into your file.) This has the added advantage of preventing the increasing problem on the Internet, as people change their sites, of 'link rot'. Now people who have linked to pages on your site will still have functioning links, even if the pages have changed location.
ApacheDirectivesCheckinEssentials 020ApacheFastTrack133
checkforapachemodulelistinEssentials 02AApacheModulesList
htpasswd Appendtoyourvirtualhostcontainer <Directory/opt/altnix> AuthUserFile/opt/altnix/private AuthTypeBasic AuthName"MyFiles" Requirevaliduser </Directory> $htpasswdc/opt/altnix.comprivatesadhiq Alsotryvirtualusersandmanyuserswithgroups Forgroups Restrictingaccesstoresourcesonthewebservercanbeachievedafewdifferentways.Thepreferredmethodfor controllingaccessthroughoutthemainserverfilesystem,istoplaceindividualdirectivesintothehttpd.conf configurationfileforeachareathatneedsanyrestrictions. Thefollowingexampleprovidessecuritytothe/var/www/html/privatedirectory(http://localhost/private),and willonlyallowvalidusersfromtheauthusersfileiftheyarelistedintheprivategroupcontainedinthe authgroupsfile. Itisimportanttonotethattheauthorisationfilesarenotlocatedinsidethe"DocumentRoot"structure, otherwisetheycouldbedownloadedifnotproperlysecured. #Providessecurityfor"http://www.example.com/private" <Directory"/var/www/html/private">
AuthType Basic AuthName "Private Area - Authorisation Required" AuthUserFile /etc/httpd/conf/authusers AuthGroupFile /etc/httpd/conf/authgroups Require group private #Require valid-user OptionsIndexesFollowSymLinks AllowOverrideNone </Directory> Theauthgroupsfilecontainsalistingofusersthathavebeenplacedintologicalgroupsdependingontheareas ofaccesstheywillbegranted.Whenausersauthorisationischeck,theusernamemustcorrespondtothegroup nameintheauthgroupsfile,asspecifiedinthe"Requiregroupprivate"directive.Onlyusersalice,bobandjane areauthorisedtoaccesstheprivatearea. [bash]#vi/etc/httpd/conf/authgroups private:alicebobjane friends:marklindaandrew superusers:lindabob Theauthusersfilecontainsalistingofusernamesandhashedpasswordvalueswhicharecheckedfor authorisation.Forasmallofficeorhomeserver,thedirective"Requirevaliduser"wouldbemoresuitablethan managingalistofgroupsandusersasitwillmatchanyuserinthefile. [bash]#touch/etc/httpd/conf/authusers [bash]#htpasswd/etc/httpd/conf/authusers alice Youshouldalwaysusethetouchcommandtocreateausername/passwordfile,usingthewrongcommand lineoption(c)willoverwriteanexistingfile.
HTTP Basic Authentication. HTTP Basic Authentication, which is based on a username and password, is the authentication mechanism defined in the HTTP/1.0 specification. A web server requests a web client to authenticate the user. As part of the request, the web server passes the realm (a string) in which the user is to be authenticated. The realm string of Basic Authentication does not have to reflect any particular security policy domain (confusingly also referred to as a realm). The web client obtains the username and the password from the user and transmits them to the web server. The web server then authenticates the user in the specified realm. Basic Authentication is not a secure authentication protocol. User passwords are sent in simple base64 ENCODING (not ENCRYPTED !), and the target server is not authenticated. Additional protection can alleviate some of these concerns: a secure transport mechanism (HTTPS), or security at the network level (such as the IPSEC protocol or VPN strategies) is applied in some deployment scenarios.
HTTP Digest Authentication. Like HTTP Basic Authentication, HTTP Digest Authentication authenticates a user based on a username and a password. However the authentication is performed by transmitting the password in an ENCRYPTED form which is much MORE SECURE than the simple base64 encoding used by Basic Authentication, e.g. HTTPS Client Authentication. As Digest Authentication is not currently in widespread use, servlet containers are encouraged but NOT REQUIRED to support it. The advantage of this method is that the cleartext password is protected in transmission, it cannot be determined from the digest that is submitted by the client to the server. Digested password authentication supports the concept of digesting user passwords. This causes the stored version of the passwords to be encoded in a form that is not easily reversible, but that the Web server can still utilize for authentication. From a user perspective, digest authentication acts almost identically to basic authentication in that it triggers a login dialog. The difference between basic and digest authentication is that on the network connection between the browser and the server, the password is encrypted, even on a non-SSL connection. In the server, the password can be stored in clear text or encrypted text, which is true for all login methods and is independent of the choice that the application deployer makes.
http://www.scribd.com/doc/17599711/Authentication
OrderAllow&Deny(Essentials) /opt/Essentials/09APACHE/06BOrderAllowDenyExmples
OrderAllow,Deny
Allow From all </Directory>
Overview
http://www.brennan.id.au/13Apache_Web_Server.html http://www.yolinux.com/TUTORIALS/LinuxTutorialApacheAddingLoginSiteProtection.html
Proxycaching
CacheLastModifiedFactor0.1 CacheDefaultExpire1 Inorder,thesedirectivesconfigurethefollowing: 1. CacheRootspecifiesthelocationofthediskcache.ThisexampleusesadirectorywithintheApache installation,butyoumightwanttoplaceitonaseparatepartitionagoodfastdiskorsuitableRAID solutionaregoodchoices. 2. CacheSizedefinesthemaximumamountofspacethatwillbeusedforthecacheondisk.Becareful withthissetting;it'stemptingtospecifyasizeaslargeastheavailablepartition,butthiscanleadtoan inefficientcache,largelymadeupofinformationyouneveragainuse.Instead,considermakingsome assumptionsabouttheexpectedamountofinformationtobedownloadedbytheusersinatypicalday, andthenmultiplythatbythenumberthatwillusetheproxyservice.Forexample,5MBisareasonable figureforlighttomediumuse;for100clients,thattranslatesinto500MB. 3. CacheGcIntervalspecifiesthenumberofhourstowaitbeforeattemptingtocleanoutunusedobjects fromthecache.Setthistoolow,andyoucanforcesomeobjectstoconstantlybereloaded.Setittohigh, andyouriskfillingthecachewithstaledata. 4. CacheMaxExpirespecifiesthenumberofsecondsforanobjecttobecachedwithoutcheckingthe originoftheservertodetermineifthedocumenthasbeenupdated.Thishelpskeeptheobjectsinthe cache"fresh,"asitspecifiesthemaximumamountoftimeanobjectinthecachecanbeoutofdate. 5. CacheLastModifiedFactordefinesavaluethatwillbeusedtocalculatewhetheraniteminthecache shouldbeexpirediftheobjecthasn'texplicitlybeenmarkedwithanexpirationdate. 6. CacheDefaultExpirespecifiesthenumberofsecondsafterwhichanobjectwillbeexpiredifno specificdataissuppliedabouttheexpirationdateorperiodfromtheoriginalserver. TheCacheMaxFileSizeandCacheMinFileSizedirectivesarealsouseful,astheysetthemaximumand minimumfilesizeparametersforfilestoberetainedinthecache.Thedefaultvaluesare100,000bytesand1 byte,respectively.Usually,youwillwanttopreventverylargefiles(e.g.,moviesandapplicationsinstallers) frombeingretainedinacache.Thatsaid,ifacompanyregularlyviewsstaticmediafilesandhasareasonable amountofspaceavailabletodevotetothecache,itmakessensetosettheCacheMaxFileSizedirectivetoamore videofriendlylimit.Beaware,however,thatdoingsowillmakeotherlargeobjectscacheable.
Filtering
ProxyBlock
www.mcslp.com
Toblockthedomain,use: ProxyBlock
mcslp.com
Toblockanynameordomainwithagivenstring: ProxyBlockmcslp
http://modperlbook.org/html/12711ProxyPass.html
http://www.helicontech.com/ape/doc/mod_proxy.htm
http://httpd.apache.org/docs/2.2/mod/mod_proxy.html http://www.slideshare.net/jimjag/acus08advancedloadbalancingapache22presentation
apachemod_rewrite
Magic Trick No. 6: Prevent Linking to Your Images The greatest and most irritating bandwidth leech is having someone link to images on your site. You can foil such thieves very easily with .htaccess. Copy the following into your .htaccess file: RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain.com/.*$ [NC] RewriteRule \.(gif|jpg)$ - [F] You don't need to understand any of that! Just change 'domain.com' to the name of your domain. (Again each command should be on a single line. There are 4 lines above, each starting with 'Rewrite') If you want to really let them know they have been rumbled why not make an image like the one below (or take this one if you like)
call it stealing.gif, save it to your images file and add the following line after the code above: RewriteRule \.(gif|jpg)$ http://www.domainname.com/images/stealing.gif [R,L] (The above command should be on a single line)
AllowOverride
http://httpd.apache.org/docs/2.0/mod/core.html#allowoverride
http://www.devshed.com/c/a/Apache/SettingPermissionsinApache/2/ .htaccess
http://httpd.apache.org/docs/2.0/howto/htaccess.html http://www.bloghash.com/2006/11/beginnersguidetohtaccessfilewithexamples/
http://www.javascriptkit.com/howto/htaccess14.shtml
Magic Trick No. 3: Allow/Prevent Directory Browsing Most servers are configured so that directory browsing is not allowed, that is if people enter the URL to a directory that does not contain an index file they will not see the contents of the directory but will instead get an error message. If your site is not configured this way you can prevent directory browsing by adding this simple line to your .htaccess file: IndexIgnore */* But there may be times when you want to allow browsing, perhaps to allow access to files for downloading or for whatever reason, on a server configured not to allow it. You can override the servers settings with this line: Options +Indexes
Apacheandphpwithmysql
#cd/usr/src
# wget http://fedora.osuosl.org/linux/releases/9/Everything/source/SRPMS/php-5.2.57.fc9.src.rpm # rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-53.noarch.rpm # yum install httpd-devel libc-client-devel postgresql-devel \ unixODBC-devel net-snmp-devel gd-devel libmcrypt-devel \ mhash-devel libtidy-devel freetds-devel aspell-devel # yum install apr-devel # rpm -ihv php-5.2.5-7.fc9.src.rpm # cd /usr/src/redhat/SPECS # rpmbuild -bb php.spec # cd /usr/src/redhat/RPMS/x86_64 # rpm -ihv php-5.2.5-7.x86_64.rpm php-ldap-5.2.5-7.x86_64.rpm \ php-gd-5.2.5-7.x86_64.rpm php-cli-5.2.5-7.x86_64.rpm \ php-common-5.2.5-7.x86_64.rpm php-mbstring-5.2.5-7.x86_64.rpm \ php-pdo-5.2.5-7.x86_64.rpm php-mysql-5.2.5-7.x86_64.rpm
TodeterminetheconfigurationofPHPonasharedserver,runthefollowingcommandfromashellaccount(or byrunningthecommandinVirtualmin): phpiThiscommandwilltellyouthePHPconfiguration(storedin/usr/local/etc/php.ini)ofthesharedserver. TothecheckthecurrentconfigurationofPHPforavirtualserveronyouraccount,createanewPHPfile(e.g. phpinfo.php)somewhereinyourDocumentrootdirectoryorasubdirectorythereof,withthefollowingcontents: <?phpphpinfo();?>andaccessthatfilefromyourbrowserusingyourvirtualserver'shostname(e.g.navigating tohttp://domain.com/phpinfo.phpdependingonwhereyouputthefile). Everyvirtualserveryoucreate(seeDomains)willhaveitsownphp.inifile(whichisacopyofserverwide sharedonein/usr/local/etc/php.ini)andstoredunderthe~/etcdirectoryforeachvirtualserver. IfyouneedtochangesomecommonsettingsunderPHPforyouraccount(likeerrorreporting),youcandoso throughVirtualmin. TousePHPonthecommandlinewiththeconfigurationofoneofyourvirtualservers,insteadoftheshared configuration,usethecswitch: phpc/path/to/your/php.ini...CustomizingyourPHPconfiguration SignintoVirtualmin(seeAccountloginsandimportantURLs). PickavirtualserverthatyouwanttoconfigurePHPfor. ClickServicesinthelefthandnavigation,thenclickPHP5Configuration(orPHP4Configurationifthisisfor PHP4). YoushouldnowseeapagelistingalltheavailablesettingsyoucaneditsuchasPHPVariables,Directory Settings,andErrorLogging. Asanexample,ifyou'dlikeenableerrorreportingdothis: SignintoVirtualmin(seeAccountloginsandimportantURLs). PickavirtualserverthatyouwanttoconfigurePHPfor.
What is a Handler
A "handler" is an internal Apache representation of the action to be performed when a file is called. Generally, files have implicit handlers, based on the file type. Normally, all files are simply served by the server, but certain file typed are "handled" separately. For example, you may use a type of "application/x-httpd-cgi" to invoke CGI scripts.
AddHandler
Syntax:<AddHandlerhandlernameextension> Context:serverconfig,virtualhost,directory,.htaccess Status:Base Module:mod_mime AddHandler maps the filename extension extension to the handler handler-name. For example, to activate CGI scripts with the file extension ".cgi", you might use:
AddHandler cgi-script cgi
Once that has been put into your srm.conf or httpd.conf file, any file ending with ".cgi" will be treated as a CGI program.
MimeTypes https://developer.mozilla.org/en/Properly_Configuring_Server_MIME_Types
openssl sslrunsintransportlayer NormalwebtrafficissentunencryptedovertheInternet.Thatis,anyonewithaccesstotherighttoolscansnoop allofthattraffic.Obviously,thiscanleadtoproblems,especiallywheresecurityandprivacyisnecessary,such asincreditcarddataandbanktransactions.TheSecureSocketLayerisusedtoencryptthedatastreambetween thewebserverandthewebclient(thebrowser). SSLmakesuseofwhatisknownasasymmetriccryptography,commonlyreferredtoaspublickeycryptography (PKI).Withpublickeycryptography,twokeysarecreated,onepublic,oneprivate.Anythingencryptedwith eitherkeycanonlybedecryptedwithitscorrespondingkey. CAcertificatesigningAuthority Thecertificate,signedbyatrustedCertificateAuthority(CA),ensuresthatthecertificateholderisreallywhohe claimstobe.Withoutatrustedsignedcertificate,yourdatamaybeencrypted $opensslgenrsades3randfile1:file2:file3:file4:file5outserver.key1024 ThefirststepistocreateyourRSAPrivateKey.Thiskeyisa1024bitRSAkeywhichisencryptedusing TripleDESandstoredinaPEM Thekeyisgeneratedusingthefollowingcommand,wherefile1:file2:etcrepresentstherandomcompressed files.
DuringthegenerationoftheCSR,youwillbepromptedforseveralpiecesofinformation.ThesearetheX.509 attributesofthecertificate $ Usingconfigurationfrom/usr/local/ssl/openssl.cnf EnterPEMpassphrase:Enterpassphrasehere Youareabouttobeaskedtoenterinformationthatwillbeincorporatedintoyourcertificaterequest. US StateorProvinceName(fullname)[SomeState]:NewHampshire LocalityName(eg,city)[]:Nashua OrganizationName(eg,company)[InternetWidgitsPtyLtd]:Domain.com,Inc. OrganizationalUnitName(eg,section)[]:. CommonName(eg,YOURname)[]:www.domain.com EmailAddress[]:webmaster@domain.com Pleaseenterthefollowing'extra'attributestobesentwithyourcertificaterequest Achallengepassword[]: Anoptionalcompanyname[]:
searchfor.crtand.keyanduncommentthe2lines.. SSLCertificateFile"/usr/local/apache2/conf/server.crt" SSLCertificateKeyFile"/usr/local/apache2/conf/server.key" Forcustomisingtoyourpath #mkdir/usr/local/apache2/conf/sslandchangethepathtoanewdircreatedinsslconffileandrunthebelow cmd Forcertificatewithpassphraserunthefollowingcmd #opensslgenrsades3randfile1:file2:file3:file4:file5outserver.key1024 #opensslrsainserver.keyoutserver.pem #opensslreqnewkeyserver.keyoutserver.csr #opensslx509reqdays60inserver.csrsignkeyserver.keyoutserver.crt
Thefollowingcanalsobedonebuttrythedefaulthaswedoneinclass. #SSLVirtualHosts <IfDefineSSL> <VirtualHost_default_:443> ServerAdminwebmaster@domain.com DocumentRoot/usr/local/apache/share/htdocs ServerNamewww.domain.com ScriptAlias/cgibin//usr/local/apache/share/htdocs/cgibin/ SSLEngineon SSLCertificateFile/usr/local/apache/etc/ssl.crt/server.crt SSLCertificateKeyFile/usr/local/apache/etc/ssl.key/server.pem SetEnvIfUserAgent".*MSIE.*"nokeepalivessluncleanshutdown CustomLog/usr/local/apache/var/log/ssl_request_log\"%t%h%{SSL_PROTOCOL}x%
{SSL_CIPHER}x\"%r\"%b"</VirtualHost> </IfDefine> Refrences http://www.openssl.org/docs/ apache+ssldirectives http://www.covalent.net/resource/documentation/faststart/2.1.0/userguide/html/httpdconf.php http://www.techfaq.com/understandingssl.shtml http://heronforge.net/redhat/node10.html http://slacksite.com/apache/certificate.php http://gregsidberry.com/2007/08/31/howtogetapacheproxypassworkingwithssl/ http://heronforge.net/redhat/node10.html#SECTION000101000000000000000
$cd/usr/bin mvjavajavaorg $ cd/usr $ lns/home/test/setup/jdk(javadir) java $ source/etc/profile.d/alljava.sh $ echo$JAVA_HOME #Theabovecommandshouldshowthebelowpath /usr/java #ThisisconfirmedyourJAVA Pathwassetcorrect. ConfiguringTomcat #step1:Downloadfrombelowmentionsite
http://archive.apache.org/dist/jakarta/tomcat5/v5.0.28/bin/
Extracttarfile. tarzxvf<tomcat.tar.gz> #step3 cd<tomcatpath/jakartadir/bin/ ./catalina.shrun #Nowcheckthetomcatport telnetlocalhost8080 Nowyourequiredthetoolforjava 1.Eclipse 2.NetBeans Downloadpath
http://linux.softpedia.com/progSearch
pagedeliverymechanisms.IIS(InternetInformationServices)isMicrosoft'sWebserver. InformationofLanguages CGI EarlierCGIwasdevelopedtoprovidetheserversidecapabilitytowebapplication.AlthoughCGIplayeda majorroleintheexplosionofInternet,it'sperformance,scalabilityandusabilityissuesmakeitlessthanthe optimalsolution.CGIrunsinaseparateprocessseparatedfromthewebserveranditrequiresmorehardware andsoftwareresources.CGIprogramsareslowbecauseforeachanewcallistotheCGIprogram,which subsequentlyrunsinaseparateprocess.IfyourprogramneedstointeractwithWebServer,usingCGIprogram youcan'taccomplishitasCGI'sseparateprocesscan'tinteractwithWebServer. ScriptingLanguages Tosolvealltheseproblemsseveralcompanieshavedevelopedserversidescriptinglanguages.Thesescriptsare popularandallowsdeveloperstodevelopwebapplicationsthatgeneratesdynamicpages.Microsofthas developedASP(ActiveServerPages)forIISServerandColdFusionisproductofAllaire.WebServer interpretsthesescriptswhenthepagesareserved.Thesescriptinglanguagesprovidegoodperformancebut imposestheportabilityissuesastheyarelimitedtoparticulargroupofproductsoroperatingsystem. Serverplugintechnologies Serversideplugintechnologyprovideverygoodperformance.NSAPIisthepluginfromNetscapeandISAPI isfromMicrosoft.Programmingusingthesepluginaredifficultandalsolearningcurveisalsoveryhigh. JavaServlets JavaServletseliminatedalltheseproblems.Thefirsttrulyplatformindependentwebdevelopmenttechnique, JavaServletsbreaksdownalltraditionalbarriersgivingyouflexibilitytorunyourWebApplicationonanyWeb Server. BuiltfromthegroundupusingSun'swriteoncerunanywheretechnology,JavaServletsprovideexcellent frameworktodevelopserversideapplicationwithoutsacrificingfunctionalityorperformance. WithJavaServletsyoucanfinallydevelopyourwebapplicationthatcanrunonanyplatform.JavaServlets havenumberofadvantagesoverCGIandotherAPI's.Theyare: PlatformIndependence: ThisisveryimportantfeatureofServlets,whichmakesthemportableacrossplatformsandacrossdifferentWeb Servers,becausetheServletAPIdefinesastandardinterfacebetweenaServletandaWebServer. Persistent: JavaServletsareloadedoncebyaWebServerwhenitreceivesarequestfromtheclientandservingthe subsequentrequestisjustamatterofcreatingnewthread.Servletscanmaintainsystemresources(e.g..database connectivityetc.)betweenrequests,thusmakingiteasytoshareresourceslikedatabaseconnectivity. Familiarity: ServletsarewritteninJavaLanguage,soanyonehavingsomeprogrammingknowledgeinJavacanlearn Servletseasily.Thissavessavesthevaluabletimeoflearninganewprogramminglanguage. InthenextsectionwelearnaboutJDBCandseehowtouseJDBCtoconnectoursearchenginetodatabase. http://www.roseindia.net/softwaretutorials/detail/6299 JSP JSPisascriptinglanguageflexibleforwebdesignersto undersatndthetagswithjavalanguageandthisis espiciallyforpresentation,asinthisstrutsscenario, Servletisacomponentwhichisresponsiblefortakingthe contentsofincomminghttprequestsanddecodeandprocess
forfurthurforwardingratherthanpresenation...Sothisis genaralwayofthinkingtounderstandytheyhadchossen servletinsteadofjsp.ifwearehavingabeeter understaningofjspandservletsthen,weourselfcan decidewhichoneismorebetterifyourwayofthinking alsoconsideringtheloadbalancingissues. Contexts ThewebapplicationusedtoprocesseachHTTPrequestisselectedbyCatalinabasedonmatchingthelongest possibleprefixoftheRequestURIagainstthecontextpathofeachdefinedContext.Onceselected,thatContext willselectanappropriateservlettoprocesstheincomingrequest,accordingtotheservletmappingsdefinedin thewebapplicationdeploymentdescriptorfile(whichMUSTbelocatedat/WEB-INF/web.xmlwithinthe webapp'sdirectoryhierarchy). YoumaydefineasmanyContextelementsasyouwish.EachsuchContextMUSThaveauniquecontextpath. Inaddition,aContextmustbepresentwithacontextpathequaltoazerolengthstring.ThisContextbecomes thedefaultwebapplicationforthisvirtualhost,andisusedtoprocessallrequeststhatdonotmatchanyother Context'scontextp
Servelet AservletisaJavaprogramminglanguageclassusedtoextendthecapabilitiesofserversthathostapplications accessedviaarequestresponseprogrammingmodel.Althoughservletscanrespondtoanytypeofrequest,they arecommonlyusedtoextendtheapplicationshostedbyWebservers.Forsuchapplications,JavaServlet technologydefinesHTTPspecificservletclasses. Servletcontainer AServletcontainerisaspecializedwebserverthatsupportsServletexecution.Itcombinesthebasic functionalityofawebserverwithcertainJava/Servletspecificoptimizationsandextensionssuchasan integratedJavaruntimeenvironment,andtheabilitytoautomaticallytranslatespecificURLsintoServlet requests.IndividualServletsareregisteredwithaServletcontainer,providingthecontainerwithinformation aboutwhatfunctionalitytheyprovide,andwhatURLorotherresourcelocatortheywillusetoidentify themselves.TheServletcontaineristhenabletoinitializetheServletasnecessaryanddeliverrequeststothe Servletastheyarrive.ManycontainershavetheabilitytodynamicallyaddandremoveServletsfromthe system,allowingnewServletstoquicklybedeployedorremovedwithoutaffectingotherServletsrunningfrom thesamecontainer.Servletcontainersarealsoreferredtoas webcontainersorwebengines. LiketheotherJavaAPIs,differentvendorsprovidetheirownimplementationoftheServletcontainerstandard. Foralistofsomeofthefreeandcommercialwebcontainers,see thelistofServletcontainers.(Notethat'free' meansthatnoncommercialuseisfree.Someofthecommercialcontainers,e.g.ResinandOrion,arefreetouse inaserverenvironmentfornonprofitorganizations). HowareServletsUsed?
Servletsaretypicallyusedasfollows: 1.ClientsendsHTTPrequest
Dyanmiccontentsusingjavaservelets
http://www.roseindia.net/softwaretutorials/detail/6299
Serveletcontainers noncommercial 1.Apachetomcat 2.Apachegeronimo 3.jaminid commercial 1.Beaweblogicwebserver 2.jboss 3.webshere(IBM) Apachewithmod_jk http://confluence.atlassian.com/display/DOC/Using+Apache+with+mod_jk Worker http://tomcat.apache.org/connectorsdocarchive/jk2/jk/workershowto.html
renamethemoduletomod_jk.soandmovetothemodulesdirofapache /usr/local/apache2/modules Edityourhttpd.confandappendthefollowingbelowLoadModuledirective LoadModulejk_modulemodules/mod_jk.so(appendthistoloadmodulesdirectivesexists) Appendthefollowingattheendofthefile <IfModulemod_jk2.c> # #Locationoftheworkers2.propertiesfile # # JkSetconfig.fileAPACHE_HOME/conf/workers.properties JkWorkersFile"C:/ApacheSoftwareFoundation/Apache2.2/conf/workers.properties" #Wheretoputjklogs JkLogFilelogs/mod_jk.log #Setthejkloglevel[debug/error/info] JkLogLeveldebug #Selectthelogformat JkLogStampFormat"[%a%b%d%H:%M:%S%Y]" #JkOptionsindicatetosendSSLKEYSIZE, JkOptions+ForwardKeySize+ForwardURICompatForwardDirectories #JkRequestLogFormatsettherequestformat JkRequestLogFormat"%w%V%T" </IfModule> ORwithoutifmodule #mod_jkconfiguration JkWorkersFile"conf/workers.properties" JkLogFile"logs/jk.log" JkLogLevelerror JkLogStampFormat"[%a%b%d%H:%M:%S%Y]" JkOptions+ForwardKeySize+ForwardURICompatForwardDirectories JkRequestLogFormat"%w%V%T" #endmod_jkconfiguration
ServerAliaswww.dummyhost.example.com ErrorLog"logs/dummyhost.example.comerror_log" CustomLog"logs/dummyhost.example.comaccess_log"common JkMount/jspexamples/*worker1 </VirtualHost> Note:jkunmount/jspexamples/images(imagesarestaticcontentssoumountfor savere ****************************************************************************************** ******* Createworkers.propertiesunder/usr/local/apache2/conf/ Appendthefollowingtothatfile
Appendthefollowingattheendofthefile #Define1realworkerusingajp13 worker.list=worker1 #Setpropertiesforworker1(ajp13) worker.worker1.type=ajp13 worker.worker1.host=localhost worker.worker1.port=8009 worker.worker1.connection_pool_size=100 worker.worker1.connection_pool_timeout=10 SecondWayUsingProxyPassforwindows Edityourhttpd.confandappendthefollowing LoadModuleproxy_modulemodules/mod_proxy.so LoadModuleproxy_http_modulemodules/mod_proxy_http.so <VirtualHost*:80> ServerNamecheckin.altnix.com(noteyoushouldhavednspointerorentryin/etc//hostsof windows) ServerAdminb.sadhiq@gmail.com DocumentRoot"C:/mycompany/apps/checkin"(fortestingcreateanindex.htmlfileunderthis) ErrorLoglogs/checkin.altnix.com_error CustomLoglogs/checkin.altnix.comaccess_logcommon </VirtualHost> #createmytestdirectoryatunderDocumentRootofTomcat ProxyPass/checkin/ http://localhost:8080/mytest/ ProxyPassReverse/checkin/http://localhost:8080/mytest/
Nowourownpagewithjava createadirunder$CATALINA_HOME/webapps/test $vidate.jsp %@pageimport="java.util.Date"%> <html> <head> <title>JavaCurrenDateandTime</title> </head> <body> <h1>CurrentTimeIs:</h1> <%=newDate().toLocaleString()%> </body> </html> :wq createaxmlfileorcopyfrom$CATALINA_HOME/conf/Catalina/localhost/manager.xml andrenametotest.xmlorany. Andthefileshouldbeasfollowing vitest.xml <Contextpath="/test"docBase="${catalina.home}/webapps/test" debug="0"privileged="true"> </Context> :wq Nowtrylocalhost:8080/test/date.jsp andtrywithjkmountforrunningwithport80
Bandwidththrotlingwithcband
http://tikiwiki.org/HowToApacheModCbandRateLimiting http://www.lslnet.com/linux/edosc/07/linux07143856.htm
Locationhandler http://www.usenetforums.com/apachewebserver/42436helplocationdirectivewillwork.html LogFormat
http://www.analog.cx/docs/logfmt.html http://httpd.apache.org/docs/1.3/logs.html
http://httpd.apache.org/docs/2.0/logs.html Performancetunning TheApacheHTTPServerisamodularprogramwheretheadministratorcanchoosethefunctionstobeincluded intheserverbyselectingasetofmodules[2].Themodulescanbecompiledeitherstaticallyaspartofthe'httpd' binary,orasDynamicSharedObjects(DSOs).DSOmodulescaneitherbecompiledwhentheserverisbuilt,or addedlaterviatheapxsutility,whichallowscompilationatalaterdate.Themod_somodulemustbestatically compiledintotheApachecoretoenableDSOsupport. RunApachewithonlytherequiredmodules.Thisreducesthememoryfootprint,whichimprovestheserver performance.StaticallycompilingmoduleswillsaveRAMthat'susedforsupportingdynamicallyloaded modules,butyouwouldhavetorecompileApachetoaddorremoveamodule.ThisiswheretheDSO mechanismcomeshandy.Oncethemod_somoduleisstaticallycompiled,anyothermodulecanbeaddedor droppedusingthe'LoadModule'commandinthe'httpd.conf'file.Ofcourse,youwillhavetocompilethe modulesusing'apxs'iftheyweren'tcompiledwhentheserverwasbuilt.
2.2ChooseappropriateMPM:
TheApacheservershipswithaselectionofMultiProcessingModules(MPMs)whichareresponsible forbindingtonetworkportsonthemachine,acceptingrequests,anddispatchingchildrentohandlethe requests[3].OnlyoneMPMcanbeloadedintotheserveratanytime. ChoosinganMPMdependsonvariousfactors,suchaswhethertheOSsupportsthreads,howmuch memoryisavailable,scalabilityversusstability,whethernonthreadsafethirdpartymodulesareused, etc. LinuxsystemscanchoosetouseathreadedMPMlikeworkeroranonthreadedMPMlikeprefork: TheworkerMPMusesmultiplechildprocesses.It'smultithreadedwithineachchild,andeachthread handlesasingleconnection.Workerisfastandhighlyscalableandthememoryfootprintis comparativelylow.It'swellsuitedformultipleprocessors.Ontheotherhand,workerislesstolerantof faultymodules,andafaultythreadcanaffectallthethreadsinachildprocess.
ThepreforkMPMusesmultiplechildprocesses,eachchildhandlesoneconnectionatatime.Preforkiswell suitedforsingleordoubleCPUsystems,speediscomparabletothatofworker,andit'shighlytolerantoffaulty modulesandcrashingchildrenbutthememoryusageishigh,andmoretrafficleadstogreatermemoryusage.
Resources(memory,etc.)canbesharedbetweenthreads. Multiplethreadscanexecutesimultaneously.
f&sig=HocOBWL7lUwRrWjup1cp7sbf4eI&hl=en&sa=X&oi=book_result&resnum=5&ct=result#PPA186,M1
http://tldp.org/LDP/LGNET/123/vishnu.html#MPM
http://www.howtoforge.com/configuring_apache_for_maximum_performance
KeepAlive:This directive is taking "on"/"off" as parameter. In simple term - whether you want to use the feature or not. For example, once you visit a site (www.someting.com), there would be a number of connection from your machine to the remote machine (on port 80). Once the browse finished fetcing pages, the socket will be closed (if KeepAlive off). If you click on a link on that page, another connection will be initiated. Remember that opening/closing socket will require some overhead from OS, and Apache itself (same thing with closing the sockets).
The number of seconds Apache will wait for a subsequent request before closing the connection. Once a request has been received, the timeout value specified by the Timeout directive applies.Setting KeepAliveTimeout to a high value may cause performance problems in heavily loaded servers. The higher the timeout, the more server processes will be kept occupied waiting on connections with idle clients.
http://httpd.apache.org/docs/2.2/programs/apxs.html
Tomcatworker
http://tomcat.apache.org/connectorsdocarchive/jk2/jk/workershowto.html http://tomcat.apache.org/tomcat3.3doc/TomcatWorkersHowTo.html
Ajpconnector
http://tomcat.apache.org/tomcat4.0doc/config/ajp.html
MONITsearchforit Apachemonitoring wtopsearchforit Httpwatch
http://tomcat.apache.org/tomcat3.3doc/TomcatWorkersHowTo.html
ApacheErrorCodes
http://www.debianhelp.co.uk/errorcodes.htm http://bignosebird.com/apache/a5.shtml
Creatingcustomizeerrorpages http://www.webreference.com/programming/apache_errors/
ab is a tool for benchmarking your Apache HTTP server. apachectl is a front end to the Apache HTTP server which is designed to help the administrator control the functioning of the Apache httpd daemon. apxs is a tool for building and installing extension modules for the Apache HTTP server. dbmanage is used to create and update the DBM format files used to store usernames and passwords for basic authentication of HTTP users. htdigest is used to create and update the flat-files used to store usernames, realms and passwords for digest authentication of HTTP users. htpasswd is used to create and update the flat-files used to store usernames and passwords for basic authentication of HTTP users. httpd is the Apache HTTP server program. instdso.sh is a script which installs Apache DSO modules. logresolve is a post-processing program to resolve IP-addresses in Apache's access log files. rotatelogs is a simple program for use in conjunction with Apache's piped log file feature.