&
                     PHP&Apache
             Why httpd.conf is your new BFF!

        Why httpd.conf is your new BFF!


...
Web “Solutions Stacks”
                    (Thanks Wikipedia!)

LAMP
 Linux Apache MySQL PHP

WAMP
 Windows Apache MySQL P...
Apache Background



Since April 1996 Apache has been the most
popular HTTP server on the World Wide Web.
 As of December ...
Apache Software Foundation
      From ApacheCon 2007, Atlanta, GA

                                         “ASF by Ted Le...
Apache HTTP Server




                 “Geronimo's Camp”
“a patchy server”




                Skydiving
          “Needs more duct tape”
Full-Featured Web Server
                     Some Features...
  Authentication, Authorization,        Environment Variabl...
Apache Configuration
                                                     By handjes




                       Contexts
S...
“PCI Slot” by Ryan




Apache Modules
httpd.conf
#httpd.conf
#Comment

#Directive
Include /usr/local/apache/conf/ssl.conf
Include /usr/local/apache/conf/vhosts/...
.htaccess




            “Apple I & Altair” by Shiny Things
Scope Directives
       VirtualHost
       Directory / DirectoryMatch
       Files / FilesMatch
       Location/LocationMa...
Virtual Host

<VirtualHost 10.1.2.3>
 ServerAdmin admin@example.com
 DocumentRoot /www/example.com
 ServerName example.com...
Directory


<Directory />
</Directory>

<Directory /home/*>
</Directory>



                        “Dewey” by emdot
DirectoryMatch

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

</DirectoryMatch>
Files




<Files admin.cgi>
  Require group admin
</Files>
                        “Filed away..” by tpholland
FilesMatch




<FilesMatch quot;.(gif|jpe?g|png)$quot;>

</FilesMatch>
                                    “Alphabetical”
Location




           “Lost” by w00kie
LocationMatch




                “Little Blue Pins”
mod_core




           “Earth Core”
ErrorDocument             “Coat Check Fail”




#Output a customized message.
ErrorDocument 403 quot;No Access”

#Redirect...
404 for pretty urls: Bad Idea!
           (Hello mod_rewrite!)




ErrorDocument 404 index.php       “Irony”
KeepAlive        “Zombie Jeff”




KeepAlive on
KeepAliveTimeout 2
MaxKeepAliveRequests 100
TimeOut




TimeOut 300
                    “Hang up.” by Robert Brook
UseCanonicalName




         ServerName example.com
         UseCanonicalName On

         Request: www.example.com/secur...
mod_php




    php_value / php_flag
●


    php_admin_value / php_admin_flag
●


    Contexts: All, Perdir, System.
●

  ...
PHP Config Contexts


    PHP_INI_ALL
●


    PHP_INI_PERDIR
●


    PHP_INI_SYSTEM
●
php_value




            “Gratuitous Bacon”




php_value name value
php_flag




php_flag name off|on      “Wave the flags”
php_admin_(flag|value)




php_admin_flag safe_mode on
                         “The Flag”
How is this useful?




                                         “Mixer Detail”



Set PHP Configuration per directory, ur...
Prepend & Append

auto_prepend_file header.php
auto_append_file footer.php

auto_prepend_file none




                   ...
include_path




          include_path=quot;.;/php/includesquot;

          include_path=quot;.;C:/php/includesquot;
“Gah...
Turn that crap off!




php_flag magic_quotes_gpc off

php_flag register_globals off   “Sausage King”
Output Buffering




php_flag output_buffering on
php_value output_handler ob_tidyhandler
php_flag implicit_flushoff
     ...
PHP Error Logging




log_errors stderr

php_value error_log /path/to/error.log
                                   “Telex ...
Display Errors




display_errors off
                     “Don't you feel secure?”
mod_env
                             “Capitol Reef National Park” by W. Staudt




    Access via $_ENV[] or getenv();
●
SetEnv




SetEnv webenv production
SetEnv webenv testing

SetEnv scriptdebug true
                           “Programmabl...
mod_mime




           “Mime Typing...”
AddType/Handler
AddType image/gif .gif

AddHandler php-script .php

#Not the best way:
AddType application/x-httpd-php .ht...
ForceType/SetHandler
ForceType application/x-httpd-php

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

<Location /images>
 ...
mod_negotiation
URI: foo

URI: foo.jpeg
Content-type: image/jpeg; qs=0.8

URI: foo.gif
Content-type: image/gif; qs=0.5

UR...
MultiViews
         Set as part of directory options
       MultiViews tracks down the best file.




<Directory /usr/loca...
mod_rewrite




http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

http://httpd.apache.org/docs/1.3/misc/rewriteguide....
Rewrite Rules

RewriteEngine On
RewriteBase /
RewriteCond /home/www/$1.php -f
RewriteRule ^(/?[^/.]+)/$ /$1.php




      ...
RewriteRule Flags
RewriteEngine On
RewriteCond %{HTTP_HOST} ^.*website2.com
RewriteRule ^/?$ /website2.php [QSA, E=thedoma...
Rewrites & Redirects



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

The Front Controller Pattern is a
software design pattern listed in
several pattern catalogs. The patter...
mod_auth
                   Other Auth & Related Modules

    mod_access
●


        Access control based on client hostna...
Basic Auth
      .htpasswd                  .htgroups
username:md5(password)     phpers: Tetraboy bdole
Tetraboy:crypt(pas...
PHP HTTP Auth
$_SERVER['PHP_AUTH_USER'] & $_SERVER['PHP_AUTH_PW']


<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
   head...
mod_headers

Header set|append|add header value
Header unset header

ErrorHeader
Setting Headers

<Files *.css>
SetHandler php-script
Header Set Content-type “text/css”
</Files>
PHP's Apache Extension
    apache_child_terminate — Terminate apache process after this request
●



    apache_get_module...
apache_child_terminate();




                       “Terminator
apache_lookup_uri
<?php
  info = apache_lookup_uri('index.php?var=value');
  var_dump($info);
?>                     stdCl...
Apache HTTP Headers

<?php


apache_request_headers();


apache_response_headers();


?>
Tip of Iceberg
     There are around 100 modules for Apache 1.3.x
●




     There are about 300 modules for Apache 2.x
●
...
“Books by Bowen”




         Apache is a Web Server.




    Don't rewrite a web server in PHP.
●



         Unless you ...
More info?
    http://httpd.apache.org/
●


    irc.freenode.net #apache
●


    http://planetapache.org/
●


    http://a...
Questions?

    Why is the sky blue?
●


    Why is the moon white?
●


    Why is the grass green?
●


    Where do babie...
Upcoming SlideShare
Loading in...5
×

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

10,050

Published on

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.

Published in: Technology
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
10,050
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
199
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

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

  1. 1. & PHP&Apache Why httpd.conf is your new BFF! Why httpd.conf is your new BFF! PHP & Apache Jeff Jones AtlantaPHP February 5th, 2009 Jump by reebs*
  2. 2. Web “Solutions Stacks” (Thanks Wikipedia!) 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. “yellow lamp“
  3. 3. Apache 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”
  4. 4. Apache Software Foundation From ApacheCon 2007, Atlanta, GA “ASF by Ted Leung”
  5. 5. Apache HTTP Server “Geronimo's Camp”
  6. 6. “a patchy server” Skydiving “Needs more duct tape”
  7. 7. Full-Featured Web Server Some Features... Authentication, Authorization, Environment Variables   & Access Control Log Files  CGI: Dynamic Content w/ CGI  Server Side Includes  Configuration Files  URL Mapping  Content negotiation  URL Rewriting “Server” by existentist
  8. 8. Apache Configuration By handjes Contexts Server config: Server wide httpd.conf and included files. VirtualHost: <VirtualHost></VirtualHost> Directory: Directory,DirectoryMatch,Files,FilesMatch .htaccess: Per directory config files.
  9. 9. “PCI Slot” by Ryan Apache Modules
  10. 10. httpd.conf #httpd.conf #Comment #Directive Include /usr/local/apache/conf/ssl.conf Include /usr/local/apache/conf/vhosts/ Include /usr/local/apache/conf/a/*.conf #Block Directive <IfModule mod_rewrite.c> RewriteEngine on </IfModule> “Floppy” by Marcin Wichary
  11. 11. .htaccess “Apple I & Altair” by Shiny Things
  12. 12. Scope Directives VirtualHost Directory / DirectoryMatch Files / FilesMatch Location/LocationMatch “Radiance” by jurvetson
  13. 13. Virtual Host <VirtualHost 10.1.2.3> ServerAdmin admin@example.com DocumentRoot /www/example.com ServerName example.com ErrorLog exlogs/error_log TransferLog exlogs/access_log </VirtualHost> “CNN Hologram” by Hard Seat Sleeper
  14. 14. Directory <Directory /> </Directory> <Directory /home/*> </Directory> “Dewey” by emdot
  15. 15. DirectoryMatch <DirectoryMatch quot;^/www/.*/[0-9]{3}quot;> </DirectoryMatch>
  16. 16. Files <Files admin.cgi> Require group admin </Files> “Filed away..” by tpholland
  17. 17. FilesMatch <FilesMatch quot;.(gif|jpe?g|png)$quot;> </FilesMatch> “Alphabetical”
  18. 18. Location “Lost” by w00kie
  19. 19. LocationMatch “Little Blue Pins”
  20. 20. mod_core “Earth Core”
  21. 21. ErrorDocument “Coat Check Fail” #Output a customized message. ErrorDocument 403 quot;No Access” #Redirect to a local URL-path. ErrorDocument 404 /errors/404.php #Redirect to an external URL. ErrorDocument 500 http://example.com/5.php
  22. 22. 404 for pretty urls: Bad Idea! (Hello mod_rewrite!) ErrorDocument 404 index.php “Irony”
  23. 23. KeepAlive “Zombie Jeff” KeepAlive on KeepAliveTimeout 2 MaxKeepAliveRequests 100
  24. 24. TimeOut TimeOut 300 “Hang up.” by Robert Brook
  25. 25. UseCanonicalName ServerName example.com UseCanonicalName On Request: www.example.com/secure Redirects to: example.com/secure/ By Greyhorn
  26. 26. mod_php php_value / php_flag ● php_admin_value / php_admin_flag ● Contexts: All, Perdir, System. ● “php is cool” by Sara Golemon
  27. 27. PHP Config Contexts PHP_INI_ALL ● PHP_INI_PERDIR ● PHP_INI_SYSTEM ●
  28. 28. php_value “Gratuitous Bacon” php_value name value
  29. 29. php_flag php_flag name off|on “Wave the flags”
  30. 30. php_admin_(flag|value) php_admin_flag safe_mode on “The Flag”
  31. 31. How is this useful? “Mixer Detail” Set PHP Configuration per directory, uri, or file.
  32. 32. Prepend & Append auto_prepend_file header.php auto_append_file footer.php auto_prepend_file none “My Stapler”
  33. 33. include_path include_path=quot;.;/php/includesquot; include_path=quot;.;C:/php/includesquot; “Gahuti Trail” by Jeff Jones
  34. 34. Turn that crap off! php_flag magic_quotes_gpc off php_flag register_globals off “Sausage King”
  35. 35. Output Buffering php_flag output_buffering on php_value output_handler ob_tidyhandler php_flag implicit_flushoff “AOL Coasters”
  36. 36. PHP Error Logging log_errors stderr php_value error_log /path/to/error.log “Telex Machine”
  37. 37. Display Errors display_errors off “Don't you feel secure?”
  38. 38. mod_env “Capitol Reef National Park” by W. Staudt Access via $_ENV[] or getenv(); ●
  39. 39. SetEnv SetEnv webenv production SetEnv webenv testing SetEnv scriptdebug true “Programmable Thermostat”
  40. 40. mod_mime “Mime Typing...”
  41. 41. AddType/Handler AddType image/gif .gif AddHandler php-script .php #Not the best way: AddType application/x-httpd-php .html #better AddHandler php-script .html “Juggling Practice”
  42. 42. ForceType/SetHandler ForceType application/x-httpd-php <Files *.php> SetHandler php-script </Files> <Location /images> ForceType image/jpeg </Location>
  43. 43. mod_negotiation URI: foo URI: foo.jpeg Content-type: image/jpeg; qs=0.8 URI: foo.gif Content-type: image/gif; qs=0.5 URI: foo.txt Content-type: text/plain; qs=0.01 “Tough Negotiations”
  44. 44. MultiViews Set as part of directory options MultiViews tracks down the best file. <Directory /usr/local/www> Options Indexes MultiViews </Directory> foo foo.html.es foo.html.en.gz “Sniffin'”
  45. 45. mod_rewrite http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html http://httpd.apache.org/docs/1.3/misc/rewriteguide.html The Definitive Guide to Apache mod_rewrite by Rich Bowen http://apress.com/book/view/9781590595619 “The Vortex”
  46. 46. Rewrite Rules RewriteEngine On RewriteBase / RewriteCond /home/www/$1.php -f RewriteRule ^(/?[^/.]+)/$ /$1.php “Tapping a pencil”
  47. 47. RewriteRule Flags RewriteEngine On RewriteCond %{HTTP_HOST} ^.*website2.com RewriteRule ^/?$ /website2.php [QSA, E=thedomain:website2,NC,L] QSA = Query String Append E = Set Environment Variables NC=No Case L=Last
  48. 48. Rewrites & Redirects RewriteCond %{HTTP_HOST} !=www.domain.com RewriteRule (.*) http://www.domain.com/$1 [R=301,L]
  49. 49. Front Controller The Front Controller Pattern is a software design pattern listed in several pattern catalogs. The pattern relates to the design of web applications. It quot;provides a centralized entry point for handling requests.quot; Source: Wikipedia
  50. 50. mod_auth Other 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 ●
  51. 51. Basic Auth .htpasswd .htgroups username:md5(password) phpers: Tetraboy bdole Tetraboy:crypt(password) bramsey:md5(WildGarlic) bdole:crypt(lbp) AuthType Basic AuthName quot;Apache Loginsquot; AuthUserFile /usr/apasswd/.htpasswd AuthGroupFile /usr/apasswd/.htgroups #Examples Require user Tetraboy bramsey bdole Require group phpers Require valid-user
  52. 52. PHP HTTP Auth $_SERVER['PHP_AUTH_USER'] & $_SERVER['PHP_AUTH_PW'] <?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm=quot;My Realmquot;'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit; } else { echo quot;<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>quot;; echo quot;<p>Your pass:{$_SERVER['PHP_AUTH_PW']}.</p>quot;; } ?>
  53. 53. mod_headers Header set|append|add header value Header unset header ErrorHeader
  54. 54. Setting Headers <Files *.css> SetHandler php-script Header Set Content-type “text/css” </Files>
  55. 55. PHP'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 ● “Trilions Served” virtual — Perform an Apache sub-request ●
  56. 56. apache_child_terminate(); “Terminator
  57. 57. apache_lookup_uri <?php info = apache_lookup_uri('index.php?var=value'); var_dump($info); ?> 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 )
  58. 58. Apache HTTP Headers <?php apache_request_headers(); apache_response_headers(); ?>
  59. 59. Tip of Iceberg There are around 100 modules for Apache 1.3.x ● There are about 300 modules for Apache 2.x ● mod_rewrite can do amazing stuff with URIs ● Apache can be expanded with custom modules! ● “Ice Breaker”
  60. 60. “Books by Bowen” Apache is a Web Server. Don't rewrite a web server in PHP. ● Unless you really have to. ●
  61. 61. More info? http://httpd.apache.org/ ● irc.freenode.net #apache ● http://planetapache.org/ ● http://apache-cookbook.com/ ● “Theo Thinks”
  62. 62. Questions? Why is the sky blue? ● Why is the moon white? ● Why is the grass green? ● Where do babies come from? ● “Downtown ATL”
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×