apache and php: why httpd.conf is your new bff!
DESCRIPTION
Apache's configuration files can be used to configure how Apache operates, but they can also be used to configure PHP and how Apache httpd interacts with PHP. In this talk, Jeff explains the different ways Apache can be configured, explains many of the useful config options available for Apache modules, including our own mod_php, and showcases example of how they can be used with, and instead of, your PHP code.TRANSCRIPT
PHP&ApachePHP&ApacheWhy httpd.conf is your new BFF!
Why httpd.conf is your new Why httpd.conf is your new BFFBFF!!&
PHP & ApacheJeff JonesAtlantaPHPFebruary 5th, 2009
Jump by reebs*
LAMP Linux Apache MySQL PHP WAMP Windows Apache MySQL PHP WIMP Windows IIS MySQL PHP LAPP Linux Apache PostgreSQL PHP FAPP FreeBSD Apache PostgreSQL PHP
Common denominator? Apache.
Web “Solutions Stacks”Web “Solutions Stacks”(Thanks Wikipedia!)
“yellow lamp“
Apache BackgroundApache Background
Since April 1996 Apache has been the most popular HTTP server on the World Wide Web.
As of December 2008 Apache served over 51% of all websites.
“Fort Apache by PhillipC”“Fort Apache by PhillipC”
Apache Software FoundationApache Software FoundationFrom ApacheCon 2007, Atlanta, GA
“ASF by Ted Leung”
Apache HTTP ServerApache HTTP Server
“Geronimo's Camp”
““a patchy server”a patchy server”
Skydiving“Needs more duct tape”
Full-Featured Web ServerFull-Featured Web Server
Authentication, Authorization,& Access Control
CGI: Dynamic Content w/ CGI Configuration Files Content negotiation
Environment VariablesLog Files
Server Side Includes URL Mapping URL Rewriting
Some Features...
“Server” by existentist
Apache ConfigurationApache Configuration
ContextsServer config: Server wide httpd.conf and included files.VirtualHost: <VirtualHost></VirtualHost>Directory: Directory,DirectoryMatch,Files,FilesMatch.htaccess: Per directory config files.
By handjesBy handjes
Apache ModulesApache Modules
“PCI Slot” by Ryan
httpd.confhttpd.conf#httpd.conf#httpd.conf#Comment#Comment
#Directive#DirectiveInclude /usr/local/apache/conf/ssl.confInclude /usr/local/apache/conf/ssl.confInclude /usr/local/apache/conf/vhosts/Include /usr/local/apache/conf/vhosts/Include /usr/local/apache/conf/a/*.conf
#Block Directive#Block Directive<IfModule mod_rewrite.c><IfModule mod_rewrite.c> RewriteEngine onRewriteEngine on</IfModule></IfModule> “Floppy” by Marcin Wichary
.htaccess.htaccess
“Apple I & Altair” by Shiny Things“Apple I & Altair” by Shiny Things
Scope DirectivesScope DirectivesVirtualHostDirectory / DirectoryMatchFiles / FilesMatchLocation/LocationMatch
“Radiance” by jurvetson“Radiance” by jurvetson
Virtual HostVirtual Host
<VirtualHost 10.1.2.3> ServerAdmin [email protected] DocumentRoot /www/example.com ServerName example.com ErrorLog exlogs/error_log TransferLog exlogs/access_log</VirtualHost>
“CNN Hologram” by Hard Seat Sleeper
DirectoryDirectory
<Directory /></Directory>
<Directory /home/*></Directory>
“Dewey” by emdot“Dewey” by emdot
DirectoryMatchDirectoryMatch
<DirectoryMatch "^/www/.*/[0-9]{3}">
</DirectoryMatch>
FilesFiles
<Files admin.cgi><Files admin.cgi> Require group adminRequire group admin</Files></Files>
“Filed away..” by tpholland
FilesMatchFilesMatch
<FilesMatch "\.(gif|jpe?g|png)$">
</FilesMatch>“Alphabetical”“Alphabetical”
ErrorDocumentErrorDocument
#Output a customized message.#Output a customized message.ErrorDocument 403 "No Access”ErrorDocument 403 "No Access”
#Redirect to a local URL-path.#Redirect to a local URL-path.ErrorDocument 404 /errors/404.phpErrorDocument 404 /errors/404.php
#Redirect to an external URL.#Redirect to an external URL.ErrorDocument 500 http://example.com/5.phpErrorDocument 500 http://example.com/5.php
“Coat Check Fail”
404 for pretty urls: 404 for pretty urls: Bad Idea!Bad Idea!
ErrorDocument 404 index.phpErrorDocument 404 index.php
(Hello mod_rewrite!)
“Irony”“Irony”
KeepAliveKeepAlive
KeepAlive onKeepAliveTimeout 2MaxKeepAliveRequests 100
“Zombie Jeff”
TimeOutTimeOut
TimeOut 300TimeOut 300
“Hang up.” by Robert Brook
UseCanonicalNameUseCanonicalName
ServerName example.comUseCanonicalName On
Request: www.example.com/secureRedirects to: example.com/secure/
By Greyhorn
● php_value / php_flag● php_admin_value / php_admin_flag● Contexts: All, Perdir, System.
mod_phpmod_php
“php is cool” by Sara Golemon
PHP Config ContextsPHP Config Contexts
● PHP_INI_ALL● PHP_INI_PERDIR● PHP_INI_SYSTEM
““GratuitousGratuitous Bacon” Bacon”
php_valuephp_value
php_value name valuephp_value name value
php_flagphp_flag
php_flag name off|onphp_flag name off|on “Wave the flags”“Wave the flags”
php_admin_(flag|value)php_admin_(flag|value)
php_admin_flag safe_mode on“The Flag”“The Flag”
How is this useful?How is this useful?
Set PHP Configuration per directory, uri, or file.Set PHP Configuration per directory, uri, or file.
“Mixer Detail”“Mixer Detail”
Prepend & AppendPrepend & Append
auto_prepend_file header.phpauto_append_file footer.php
auto_prepend_file none
“My Stapler”
include_pathinclude_path
include_path=".;/php/includes"include_path=".;/php/includes"
include_path=".;C:/php/includes"include_path=".;C:/php/includes"
“Gahuti Trail” by Jeff Jones“Gahuti Trail” by Jeff Jones
Turn that crap off!Turn that crap off!
php_flag magic_quotes_gpc offphp_flag magic_quotes_gpc off
php_flag register_globals offphp_flag register_globals off “Sausage King”“Sausage King”
Output BufferingOutput Buffering
php_flag output_buffering onphp_flag output_buffering onphp_value output_handler ob_tidyhandlerphp_value output_handler ob_tidyhandler
php_flag implicit_flushoffphp_flag implicit_flushoff
“AOL Coasters”“AOL Coasters”
PHP Error LoggingPHP Error Logging
log_errors stderrlog_errors stderr
php_value error_log /path/to/error.logphp_value error_log /path/to/error.log“Telex Machine”“Telex Machine”
Display ErrorsDisplay Errors
display_errors offdisplay_errors off
“Don't you feel secure?”“Don't you feel secure?”
mod_envmod_env● Access via $_ENV[] or getenv();Access via $_ENV[] or getenv();
“Capitol Reef National Park” by W. Staudt“Capitol Reef National Park” by W. Staudt
SetEnvSetEnv
SetEnv webenv productionSetEnv webenv testing
SetEnv scriptdebug true“Programmable Thermostat”“Programmable Thermostat”
AddType/HandlerAddType/Handler
AddType image/gif .gifAddType image/gif .gif
AddHandler php-script .phpAddHandler php-script .php
##Not the best way:Not the best way:AddType application/x-httpd-php .htmlAddType application/x-httpd-php .html
##betterbetterAddHandler php-script .htmlAddHandler php-script .html
“Juggling Practice”“Juggling Practice”
ForceType/SetHandlerForceType/SetHandler
ForceType application/x-httpd-php
<Files *.php>SetHandler php-script</Files>
<Location /images> ForceType image/jpeg</Location>
mod_negotiationmod_negotiation URI: fooURI: foo
URI: foo.jpegURI: foo.jpeg Content-type: image/jpeg; qs=0.8Content-type: image/jpeg; qs=0.8
URI: foo.gifURI: foo.gif Content-type: image/gif; qs=0.5Content-type: image/gif; qs=0.5
URI: foo.txtURI: foo.txt Content-type: text/plain; qs=0.01Content-type: text/plain; qs=0.01
“Tough Negotiations”“Tough Negotiations”
MultiViewsMultiViewsSet as part of directory options
MultiViews tracks down the best file.
<Directory /usr/local/www><Directory /usr/local/www> Options Indexes MultiViewsOptions Indexes MultiViews</Directory></Directory>
foofoofoo.html.esfoo.html.esfoo.html.en.gzfoo.html.en.gz
“Sniffin'”“Sniffin'”
mod_rewritemod_rewrite
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.htmlhttp://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
http://httpd.apache.org/docs/1.3/misc/rewriteguide.htmlhttp://httpd.apache.org/docs/1.3/misc/rewriteguide.html
The Definitive Guide to Apache mod_rewriteThe Definitive Guide to Apache mod_rewrite by Rich Bowenby Rich Bowen http://apress.com/book/view/9781590595619http://apress.com/book/view/9781590595619 “The Vortex”“The Vortex”
Rewrite RulesRewrite Rules
RewriteEngine OnRewriteBase /RewriteCond /home/www/$1.php -fRewriteRule ^(/?[^/\.]+)/$ /$1.php
“Tapping a pencil”“Tapping a pencil”
RewriteRule FlagsRewriteRule Flags
RewriteEngine OnRewriteCond %{HTTP_HOST} ^.*website2.comRewriteRule ^/?$ /website2.php [QSA, E=thedomain:website2,NC,L]
QSA = Query String Append
E = Set Environment Variables
NC=No Case
L=Last
Rewrites & RedirectsRewrites & Redirects
RewriteCond %{HTTP_HOST} !=www.domain.com RewriteRule (.*) http://www.domain.com/$1 [R=301,L]
Front ControllerFront Controller
The Front Controller Pattern is a The Front Controller Pattern is a software design pattern listed in software design pattern listed in several pattern catalogs. The pattern several pattern catalogs. The pattern relates to the design of web relates to the design of web applications. It "provides a applications. It "provides a centralized entry point for handling centralized entry point for handling requests."requests."
Source: WikipediaSource: Wikipedia
mod_authmod_authOther Auth & Related Modules
● mod_access● Access control based on client hostname or IP address
● mod_auth_dbm● User authentication using DBM files
● mod_auth_db● User authentication using Berkeley DB files
● mod_auth_anon Apache 1.1 and up● Anonymous user access to authenticated areas
● mod_digest● MD5 authentication
Basic AuthBasic Auth
AuthType BasicAuthName "Apache Logins"AuthUserFile /usr/apasswd/.htpasswdAuthGroupFile /usr/apasswd/.htgroups
#ExamplesRequire user Tetraboy bramsey bdoleRequire group phpersRequire valid-user
username:md5(password)Tetraboy:crypt(password)bramsey:md5(WildGarlic)bdole:crypt(lbp)
.htpasswdphpers: Tetraboy bdole
.htgroups
PHP HTTP AuthPHP HTTP Auth
<?phpif (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit;} else { echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>"; echo "<p>Your pass:{$_SERVER['PHP_AUTH_PW']}.</p>";}?>?>
$_SERVER['PHP_AUTH_USER'] & $_SERVER['PHP_AUTH_PW']$_SERVER['PHP_AUTH_USER'] & $_SERVER['PHP_AUTH_PW']
mod_headersmod_headers
Header set|append|add header value
Header unset header
ErrorHeader
Setting HeadersSetting Headers
<Files *.css>SetHandler php-scriptHeader Set Content-type “text/css”</Files>
PHP's Apache ExtensionPHP's Apache Extension● apache_child_terminate — Terminate apache process after this request● apache_get_modules — Get a list of loaded Apache modules● apache_get_version — Fetch Apache version● apache_getenv — Get an Apache subprocess_env variable● apache_lookup_uri — Perform a partial request on a URI, returns info.● apache_note — Get and set apache request notes● apache_request_headers — Fetch all HTTP request headers● apache_reset_timeout — Reset the Apache write timer● apache_response_headers — Fetch all HTTP response headers● apache_setenv — Set an Apache subprocess_env variable● ascii2ebcdic — Translate string from ASCII to EBCDIC● ebcdic2ascii — Translate string from EBCDIC to ASCII● getallheaders — Fetch all HTTP request headers● virtual — Perform an Apache sub-request “Trilions Served”“Trilions Served”
apache_child_terminate();apache_child_terminate();
“Terminator”“Terminator”
apache_lookup_uri apache_lookup_uri
stdClass Object( [status] => 200 [the_request] => GET /dir/file.php HTTP/1.1 [method] => GET [mtime] => 0 [clength] => 0 [chunked] => 0 [content_type] => application/x-httpd-php [no_cache] => 0 [no_local_copy] => 1 [unparsed_uri] => /dir/index.php?var=value [uri] => /dir/index.php [filename] => /home/htdocs/dir/index.php [args] => var=value [allowed] => 0 [sent_bodyct] => 0 [bytes_sent] => 0 [request_time] => 1074282764)
<?php info = apache_lookup_uri('index.php?var=value'); var_dump($info);?>
Apache HTTP HeadersApache HTTP Headers
<?php
apache_request_headers();
apache_response_headers();
?>
Tip of IcebergTip of Iceberg● There are around 100 modules for Apache 1.3.xThere are around 100 modules for Apache 1.3.x
● There are about 300 modules for Apache 2.xThere are about 300 modules for Apache 2.x
● mod_rewrite can do amazing stuff with URIsmod_rewrite can do amazing stuff with URIs
● Apache can be expanded with custom modules!Apache can be expanded with custom modules!
“Ice Breaker”“Ice Breaker”
Apache is a Web Server.Apache is a Web Server.
● Don't rewrite a web server in PHP.Don't rewrite a web server in PHP.● Unless you really have to.Unless you really have to.
“Books by Bowen”“Books by Bowen”
More info?More info?
● http://httpd.apache.org/● irc.freenode.net #apache● http://planetapache.org/● http://apache-cookbook.com/
“Theo Thinks”“Theo Thinks”
Questions?Questions?
● Why is the sky blue?● Why is the moon white?● Why is the grass green?● Where do babies come from?
“Downtown ATL”“Downtown ATL”