apache and php: why httpd.conf is your new bff!

62
PHP&Apache PHP&Apache Why httpd.conf is your new BFF! Why httpd.conf is your new Why httpd.conf is your new BFF BFF ! ! & PHP & Apache Jeff Jones AtlantaPHP February 5 th , 2009 Jump by reebs*

Upload: jeff-jones

Post on 08-May-2015

9.938 views

Category:

Technology


4 download

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

Page 1: Apache and PHP: Why httpd.conf is your new BFF!

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*

Page 2: Apache and PHP: Why httpd.conf is your new BFF!

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“

Page 3: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 4: Apache and PHP: Why httpd.conf is your new BFF!

Apache Software FoundationApache Software FoundationFrom ApacheCon 2007, Atlanta, GA

“ASF by Ted Leung”

Page 5: Apache and PHP: Why httpd.conf is your new BFF!

Apache HTTP ServerApache HTTP Server

“Geronimo's Camp”

Page 6: Apache and PHP: Why httpd.conf is your new BFF!

““a patchy server”a patchy server”

Skydiving“Needs more duct tape”

Page 7: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 8: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 9: Apache and PHP: Why httpd.conf is your new BFF!

Apache ModulesApache Modules

“PCI Slot” by Ryan

Page 10: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 11: Apache and PHP: Why httpd.conf is your new BFF!

.htaccess.htaccess

“Apple I & Altair” by Shiny Things“Apple I & Altair” by Shiny Things

Page 12: Apache and PHP: Why httpd.conf is your new BFF!

Scope DirectivesScope DirectivesVirtualHostDirectory / DirectoryMatchFiles / FilesMatchLocation/LocationMatch

“Radiance” by jurvetson“Radiance” by jurvetson

Page 13: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 14: Apache and PHP: Why httpd.conf is your new BFF!

DirectoryDirectory

<Directory /></Directory>

<Directory /home/*></Directory>

“Dewey” by emdot“Dewey” by emdot

Page 15: Apache and PHP: Why httpd.conf is your new BFF!

DirectoryMatchDirectoryMatch

<DirectoryMatch "^/www/.*/[0-9]{3}">

</DirectoryMatch>

Page 16: Apache and PHP: Why httpd.conf is your new BFF!

FilesFiles

<Files admin.cgi><Files admin.cgi> Require group adminRequire group admin</Files></Files>

“Filed away..” by tpholland

Page 17: Apache and PHP: Why httpd.conf is your new BFF!

FilesMatchFilesMatch

<FilesMatch "\.(gif|jpe?g|png)$">

</FilesMatch>“Alphabetical”“Alphabetical”

Page 18: Apache and PHP: Why httpd.conf is your new BFF!

LocationLocation

“Lost” by w00kie

Page 19: Apache and PHP: Why httpd.conf is your new BFF!

LocationMatchLocationMatch

“Little Blue Pins”

Page 21: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 22: Apache and PHP: Why httpd.conf is your new BFF!

404 for pretty urls: 404 for pretty urls: Bad Idea!Bad Idea!

ErrorDocument 404 index.phpErrorDocument 404 index.php

(Hello mod_rewrite!)

“Irony”“Irony”

Page 23: Apache and PHP: Why httpd.conf is your new BFF!

KeepAliveKeepAlive

KeepAlive onKeepAliveTimeout 2MaxKeepAliveRequests 100

“Zombie Jeff”

Page 24: Apache and PHP: Why httpd.conf is your new BFF!

TimeOutTimeOut

TimeOut 300TimeOut 300

“Hang up.” by Robert Brook

Page 25: Apache and PHP: Why httpd.conf is your new BFF!

UseCanonicalNameUseCanonicalName

ServerName example.comUseCanonicalName On

Request: www.example.com/secureRedirects to: example.com/secure/

By Greyhorn

Page 26: Apache and PHP: Why httpd.conf is your new BFF!

● php_value / php_flag● php_admin_value / php_admin_flag● Contexts: All, Perdir, System.

mod_phpmod_php

“php is cool” by Sara Golemon

Page 27: Apache and PHP: Why httpd.conf is your new BFF!

PHP Config ContextsPHP Config Contexts

● PHP_INI_ALL● PHP_INI_PERDIR● PHP_INI_SYSTEM

Page 28: Apache and PHP: Why httpd.conf is your new BFF!

““GratuitousGratuitous Bacon” Bacon”

php_valuephp_value

php_value name valuephp_value name value

Page 29: Apache and PHP: Why httpd.conf is your new BFF!

php_flagphp_flag

php_flag name off|onphp_flag name off|on “Wave the flags”“Wave the flags”

Page 30: Apache and PHP: Why httpd.conf is your new BFF!

php_admin_(flag|value)php_admin_(flag|value)

php_admin_flag safe_mode on“The Flag”“The Flag”

Page 31: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 32: Apache and PHP: Why httpd.conf is your new BFF!

Prepend & AppendPrepend & Append

auto_prepend_file header.phpauto_append_file footer.php

auto_prepend_file none

“My Stapler”

Page 33: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 34: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 35: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 36: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 37: Apache and PHP: Why httpd.conf is your new BFF!

Display ErrorsDisplay Errors

display_errors offdisplay_errors off

“Don't you feel secure?”“Don't you feel secure?”

Page 38: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 39: Apache and PHP: Why httpd.conf is your new BFF!

SetEnvSetEnv

SetEnv webenv productionSetEnv webenv testing

SetEnv scriptdebug true“Programmable Thermostat”“Programmable Thermostat”

Page 40: Apache and PHP: Why httpd.conf is your new BFF!

mod_mimemod_mime

“Mime Typing...”

Page 41: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 42: Apache and PHP: Why httpd.conf is your new BFF!

ForceType/SetHandlerForceType/SetHandler

ForceType application/x-httpd-php

<Files *.php>SetHandler php-script</Files>

<Location /images> ForceType image/jpeg</Location>

Page 43: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 44: Apache and PHP: Why httpd.conf is your new BFF!

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'”

Page 45: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 46: Apache and PHP: Why httpd.conf is your new BFF!

Rewrite RulesRewrite Rules

RewriteEngine OnRewriteBase /RewriteCond /home/www/$1.php -fRewriteRule ^(/?[^/\.]+)/$ /$1.php

“Tapping a pencil”“Tapping a pencil”

Page 47: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 48: Apache and PHP: Why httpd.conf is your new BFF!

Rewrites & RedirectsRewrites & Redirects

RewriteCond %{HTTP_HOST} !=www.domain.com RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

Page 49: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 50: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 51: Apache and PHP: Why httpd.conf is your new BFF!

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

Page 52: Apache and PHP: Why httpd.conf is your new BFF!

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']

Page 53: Apache and PHP: Why httpd.conf is your new BFF!

mod_headersmod_headers

Header set|append|add header value

Header unset header

ErrorHeader

Page 54: Apache and PHP: Why httpd.conf is your new BFF!

Setting HeadersSetting Headers

<Files *.css>SetHandler php-scriptHeader Set Content-type “text/css”</Files>

Page 55: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 56: Apache and PHP: Why httpd.conf is your new BFF!

apache_child_terminate();apache_child_terminate();

“Terminator”“Terminator”

Page 57: Apache and PHP: Why httpd.conf is your new BFF!

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);?>

Page 58: Apache and PHP: Why httpd.conf is your new BFF!

Apache HTTP HeadersApache HTTP Headers

<?php

apache_request_headers();

apache_response_headers();

?>

Page 59: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 60: Apache and PHP: Why httpd.conf is your new BFF!

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”

Page 61: Apache and PHP: Why httpd.conf is your new BFF!

More info?More info?

● http://httpd.apache.org/● irc.freenode.net #apache● http://planetapache.org/● http://apache-cookbook.com/

“Theo Thinks”“Theo Thinks”

Page 62: Apache and PHP: Why httpd.conf is your new BFF!

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”