Apache 2.x sobre sistemas Unix

Esta sección contiene notas y consejos específicos a las instalaciones de Apache 2.x de PHP sobre sistemas Unix.

Advertencia

No se recomienda utilizar un MPM threaded en producción con Apache 2. Use MPM prefork, que es el MPM por defecto en Apache 2.0 y 2.2. Para información sobre cómo, lea la correspondiente entrada de la FAQ sobre utilizar Apache2 con un MPM threaded

La » Documentación de Apache es la fuente de información más autorizada acerca del servidor Apache 2.x. Ahí se puede encontrar más información acerca de las opciones de instalación.

La versión más reciente de Apache HTTP Server puede obtenerse del » Sitio de descargas de Apache, y una versión apropiada de PHP de los lugares anteriormente mencionados. Esta guía rápida solamente cubre lo básico para comenzar con Apache 2.x y PHP. Para obtener más información lea la » Documentación de Apache. Los números de versión han sido omitidos aquí, para asegurar que las instrucciones no sean incorrectas. En los ejemplos siguientes, 'NN' deberá ser reemplazado con la versión específica de Apache que se está utilizando.

Existen actualmente dos versiones de Apache 2.x - está la 2.0 y la 2.2. Mientras que existen varias razones para elegir cada una, la 2.2 es actualmente la versión más reciente, y la que se recomienda, si es que esa opción está disponible. Sin embargo, las instrucciones aquí funcionarán ya sea para 2.0 ó 2.2.

  1. Obténgase el servidor HTTP Apache de la ubicación listada con anterioridad, y desempáquese:

    gzip -d httpd-2_x_NN.tar.gz
    tar -xf httpd-2_x_NN.tar
    
  2. De la misma manera, obtener y desempacar las fuentes de PHP:

    gunzip php-NN.tar.gz
    tar -xf php-NN.tar
    
  3. Compilar e instalar Apache. Consúltese la documentación de instalación de Apache para mayores detalles sobre la compilación de Apache.

    cd httpd-2_x_NN
    ./configure --enable-so
    make
    make install
    
  4. Ahora se tiene Apache 2.x.NN disponible debajo de /usr/local/apache2, configurado con soporte para módulos cargables y con el MPM (Módulo de multiproceso) prefork estándar. Para probar la instalación úsese el procedimiento para iniciar el servidor Apache, por ej.:

    /usr/local/apache2/bin/apachectl start
    
    y deténgase el servidor para proceder con la configuración para PHP:
    /usr/local/apache2/bin/apachectl stop
    

  5. Ahora, configure y compile PHP. Aquí es donde se personaliza PHP con varias opciones, como qué extensiones se han de habilitar. Ejecute ./configure --help para obtener una lista de opciones disponibles. En el ejemplo se realiza un simple configure con soporte para Apache 2 y MySQL.

    Si se compila Apache a partir de los fuentes, tal como se describe anteriormente, el siguiente ejemplo coincidirá con la trayectoria para apxs, pero si se ha instalado Apache de alguna otra manera, será necesario ajustar la trayectoria a apxs apropiadamente. Nótese que algunas distribuciones pueden renombrar apxs cómo apxs2.

    cd ../php-NN
    ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql
    make
    make install
    

    Si se decide a cambiar las opciones de configuración después de la instalación, se deben volver a ejecutar los pasos configure, make, y make install. Solamente se necesita reiniciar apache para que el nuevo módulo tenga efecto. Una recompilación de Apache no es necesaria.

    Nótese que a menos que se indique lo contrario, 'make install' también instalará PEAR, varias herramientas de PHP tales como phpize, instalará la interfaz de línea de comando (CLI) de PHP, y más.

  6. Configurar php.ini

    cp php.ini-development /usr/local/lib/php.ini
    

    Se puede editar el fichero .ini para fijar las opciones de PHP. Si se prefiere tener php.ini en otra ubicación, utilice --with-config-file-path=/alguna/trayectoria en el paso 5.

    Si en vez de eso se elige php.ini-production, asegúrese de leer la lista de cambios al interior, ya que afectan como se comporta PHP.

  7. Edítese httpd.conf para cargar el módulo PHP. La trayectoria a la derecha de la sentencia LoadModule debe apuntar a la trayectoria del módulo PHP en el sistema. El make install anterior podría ya haber agregado esto automáticamente, pero asegúrese de revisar.

    LoadModule php5_module modules/libphp5.so
  8. Indicar a Apache que procese ciertas extensiones como PHP. Por ejemplo, hágase que Apache procese ficheros .php como PHP. En vez de solamente utilizar la directiva de Apache AddType, se desea evitar subidas de ficheros potencialmente peligrosas y que ficheros creados tal como exploit.php.jpg sean ejecutados como PHP. Utilizando este ejemplo, se puede hacer que cualquier extensión o extensiones sean procesadas como PHP simplemente añadiéndolas. Se agregará .php para demostrarlo.

    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

    O, si se deseara permitir que ficheros .php, .php2, .php3, .php4, .php5, .php6, y .phtml fuesen ejecutados como PHP, pero nada más, se utilizaría esto:

    <FilesMatch "\.ph(p[2-6]?|tml)$">
        SetHandler application/x-httpd-php
    </FilesMatch>

    Y para permitir que ficheros .phps sean manejados por el filtro de fuentes de php, y desplegado como código fuente con sintaxis resaltada, se utiliza esto:

    <FilesMatch "\.phps$">
        SetHandler application/x-httpd-php-source
    </FilesMatch>

    mod_rewrite puede ser utilizado para permitir que cualquier fichero .php arbitrario sea desplegado como código fuente con sintaxis resaltada, sin tener que renombrarlo o copiarlo a un fichero .phps:

    RewriteEngine On
    RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source]

    El filtro de código fuente php no debe habilitarse en sistemas de producción, donde podría exponer información confidencial o de alguna otra manera sensible incluida en código fuente.

  9. Utilícese el procedimiento normal para iniciar el servidor Apache, por ej.:

    /usr/local/apache2/bin/apachectl start
    

    O

    service httpd restart
    

Siguiendo los pasos anteriores se tendrá corriendo un servidor web Apache2 con soporte para PHP como un módulo SAPI. Por supuesto existen muchas opciones más de configuración disponibles para Apache y PHP. Para más información teclee ./configure --help en el árbol de fuentes correspondiente.

Apache se puede compilar con soporte multihilos seleccionando el worker MPM, en vez del prefork MPM standard, cuando Apache se compila. Esto se realiza agregando la siguiente opción al argumento pasado a ./configure, en el paso 3 anterior:


--with-mpm=worker

Esto no debe llevarse a cabo sin ser consciente de las consecuencias de esta decisión, y tener al menos un ligero entendimiento acerca de las implicaciones. La documentación de Apache al respecto de » MPM-Modules discute los MPM en forma mucho más detallada.

Nota:

Las Preguntas frecuentes de Apache MultiViews discute acerca del uso de multiviews con PHP.

Nota:

Para compilar una versión multihilo de Apache, el sistema destino debe soportar hilos. En este caso, PHP también debe compilarse con la opción Zend Thread Safety (ZTS) experimental. Bajo esta configuración, no todas las extensiones se encontrarán disponibles. La configuración recomendada es compilar Apache con el MPM-module prefork por omisión.

add a note add a note

User Contributed Notes 15 notes

up
2
chris@gerlt -dot- net
7 years ago
Install issues on Redhat, specifically RHEL4 with php4 already installed: 

I discovered that there was an issue caused by redhat loading php4 in another file seperate from the httpd.conf file!  This took me hours to discover.  Make sure you know if the apache config file (httpd.conf) is loading configurations from a directory (or another file(s)) as well.  If so, look in there for any php module loading which could conflict with the new module you are compiling/installing.
up
2
nmmm at nmmm dot nu
4 years ago
When I upgrade to apache 2.2, this:

AddType application/x-httpd-php .php5
AddType application/x-httpd-php .php42
AddType application/x-httpd-php .php4
AddType application/x-httpd-php .php3
AddType application/x-httpd-php .php
AddType application/x-httpd-php .phtm
AddType application/x-httpd-php .phtml
AddType application/x-httpd-php .asp

...does not worked for me, so I did this:

<FilesMatch "\.(php*|phtm|phtml|asp|aspx)$">
SetHandler application/x-httpd-php
</FilesMatch>

Another interesting point with Apache 2.2 is following.
Let suppose we installed PHP as module. But for some directory, we need to use PHP as CGI (probably because of custom configuration). This can be done using:

<FilesMatch "\.(php*|phtm|phtml|asp|aspx)$">
SetHandler none
</FilesMatch>

AddType application/x-httpd-php-custom .php
Action  application/x-httpd-php-custom  /cgi-bin/php-huge

Note type must be different than "application/x-httpd-php" and also you need to deactivate the handler on sertain extention. You can do mixed configuration:

<FilesMatch "\.(php)$">
SetHandler none
</FilesMatch>

AddType application/x-httpd-php-custom .php
Action  application/x-httpd-php-custom  /cgi-bin/php-huge

in such case files like *.php5 and so on will be parsed via module, but *.php will go to php-huge executable.
up
1
Tom420.Duhamel
5 years ago
I have successfully installed Apache 2.2.11 and PHP 5.2.8 under Red Hat 9.0 on a Pentium 166 with 32 MB of RAM.

While I used RH9, the worst possible case, these notes are probably good for RH-based distributions too (Red Hat Enterprise, Fedora, CentOS...)

If you want to install MySQL, it needs to be installed before PHP because PHP requires some libraries be available.

One think important when picking up a binary distribution of MySQL is to download all four packages: MySQL-server, MySQL-devel, MySQL-client and MySQL-shared. Note: The MySQL was bundled with PHP 4 but is not anymore in PHP 5.

Then you need to install Apache before PHP, because again PHP needs some libraries be available. I installed Apache 2 from source, using the very last version available, which is 2.2.11.

I installed PHP 5.2.8 from source. Here, I had a number of problems, but none which I could not resolve easily, some of them with a little help from different forums I found through Google.

Rembember: When it says you need a package named xyz and you notice there is also one named xyz-devel, grab it.

Most of the packages I got from:
http://legacy.redhat.com/pub/redhat/linux/9/en/os/i386/RedHat/RPMS/
A similar page exists for other versions of Red Hat
and:
http://rpmfind.net/
This site has an updated version of some of the packages. Make sure to use only the one labeled for you version (in my case, Red Hat 9.0) or it will not likely work.

You already have glibc and glibc-common installed, but you need to get glibc-devel and glibc-kernheaders. Make sure to match glibc's version (rpm -q glibc). Note: When it says kernel-header is a required dependency, that's glibc-kernheader (not kernel-source). You will also need binutils (no need to match the version), and gcc and cpp (version must match).

You need zlib-devel (zlib is probably already installed, match the version you have).

If you install the GD extension, the actual library is already bundled with PHP 5 (use that one, they have done some changes in there, so don't upgrade), but you will need to install libpng and libpng-devel (match version, or disable in configure if you don't want) and libjpeg (no -devel with that one).

You will also need libxml2. Now there were a problem, because PHP requires libxml2 be 2.6 or greater, but Red Hat only supplied 2.5.4-1 for RH9 (if you have a more recent distro, you might be more lucky). After looking for a while, I decided to grab the source code for the most recent distribution at the official website (http://xmlsoft.org/) and compiled.

Hope my post is useful to someone. Please, share your experience when compiling/installing for your particular platform and setup. Remember how hard it's been for you the very first time. I confess, my very first server installation took me nearly a week and I was glad others helped me.
up
1
svepa at milestone42 dot com
2 years ago
On 64-bit Fedora systems (I'm using Fedora 14), configuring PHP to use the MySQL libraries installed as part of the distribution gives the following error if you follow the default instructions in this manual.

Cannot find libmysqlclient under /usr

Modifying he following invocation of configure as follows:

./configure --with-apxs2=/path/to/apxs --with-libdir=lib64 --with-mysql

should work.

Note the addition of --with-libdir=lib64
This points the configure script to look for 64-bit mysqlclient libraries.
up
1
happyboy at php dot org
8 years ago
FILE TRUNCATED!!

during the make process should u receive an error declaring ext/ctype/ctype.lo (or another file) is truncated then you need to 'make clean' prior to a healthy 'make' and 'make install.'

looking into your ext/ directory you may find the offensive file to be 1 byte long.
up
0
Sami Fouad
3 months ago
If you're using Ubuntu, all that's really required is two terminal commands. Please see the Installation notes link on the left for Debian/Ubuntu.
up
0
susie91
7 years ago
for slackware 10.2 users with apache2, mysql5, and trying to install php5:

when following the directions above, after this step:

./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql

i kept getting this error:
"Unable to find MySql header files...."

the only way i could get php5 with mysql support was to compile MySql5 from source, and not use the binary as the mysql site recommends.

then i was able to ./configure successfully, but for some reason php was configured to compile the CGI version.

so, had to use this ./configure line:

./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql=/usr/local/mysql  --disable-cgi

alternatively, you could install php4 which does bundle the MySql client files.
up
0
felixcca at yahoo dot ca
8 years ago
I've (painfully) discovered that installing PHP5 with "make install" under SuSe 9.2 is NOT a good idea.
http://www.aditus.nu/jpgraph/apache2suse.php
This page explains how to install it without breaking everything that's php-related in the Apache2 configuration. Its first purpose, though, is to show how to have php 4 and 5 to cohabit properly.
up
0
frank@ethisoft
8 years ago
Using Apache2 & PHP5 work perfectly fine & safe together.
- all core modules are safe in Zend Engine 2
- third-party-libraries should be avoided
- semaphores and shared memory enables you to ensure yourself that your application/website is thread-safe also with non-thread-safe PHP modules!
up
0
mihai dot sandu at gtstelecom dot ro
9 years ago
For the SuSE9.2 install of PHP5.
First:
If building on a x64 platform, please set LDFLAGS="-L/usr/lib64" before configure.
As for install, it suffices to go to /etc/apache2 and:
ln -s sysconfig.d/loadmodule.conf httpd2-prefork.conf
and then make install
up
0
neil
9 years ago
To install mysql and mysqli with PHP5 do the following:

after doing:

./configure --with-mysql=/path/to/mysql_config --with-mysqli=/path/to/mysql_config

do this:

"
    if you want to use both the old mysql and the new mysqli interface, load the Makefile into your editor and search for the line beginning with EXTRA_LIBS; it includes -lmysqlclient twice; remove the second instance
"

then you can:

make
make install

.....
Pleasse note: you must have mysql-dev installed (RPM or source) or you will not have the mysql_config file at all.  The standard, server, and client installations of MySQL do not include it.  I read somewhere that the mysql and mysqli paths must be identical.

Quoted from Michael Kofler at the following link:
http://www.kofler.cc/forum/forumthread.php?rootID=3571
up
0
Dan Scott (dan dot scott at acm dot org)
9 years ago
Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

SuSE uses a rather fragmented set of Apache configuration files stored in /etc/apache2/. When you configure PHP 5.x with:

$ ./configure --with-apxs2=/usr/sbin/apxs2
$ make

everything builds just fine; but when you issue:
$ su -c "make install"

the unconventional Apache conf file layout confuses the install-sapi section of the Makefile and the process halts with the following error:

apxs:Error: Config file /etc/apache2/httpd2-prefork.conf not found.
make: *** [install-sapi] Error 1

At this point only the PHP SAPI library has been copied into place; the rest of the files (like PEAR scripts, PHP-CLI, etc) have not been installed. But never fear! You can overcome this problem with the following steps:

1. Edit Makefile and change the following line to remove "install-sapi":
install_targets = install-sapi install-cli install-pear install-build install-headers install-programs

2. Issue the make install command again:
$ su -c "make install"

3. Add the PHP module & type instructions to the Apache configuration. As root, create a new file, /etc/apache2/conf.d/php5.conf that contains the following lines:

LoadModule php5_module /usr/lib/apache2/libphp5.so
AddType application/x-httpd-php php

--- And that's it. Everything else is just as the documentation suggests it should be.
up
0
praveen dot k at masconit dot com
9 years ago
Hi too had same problem with multiview like when i execute http://huey/admin/test.php it used to compile but when i use http://huey/admin/test it wouldnt recognise it as php file... i worked it out with the addhandler method and AddType in different line and setting multiview for directive

"multiviews Options Indexes FollowSymLinks MultiViews"

the directives u can set it to root directory so now when u type pn test it will search in precendence for test.php, test.html if any .....

its working for me with apache2.0.47 and php 4.3.9 on solaris

praveen
up
-1
Anonymous
4 years ago
Solution for fedora is yum install mysql-devel. Then set --with-mysql=/usr/include/mysql/
monguesto
up
-2
jaya
7 years ago
PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Solaris9 Packages Installed:

Verify required package installation:
root# pkginfo SUNWbtool SUNWsprot SUNWtoo SUNWhea SUNWarc \
SUNWlibm SUNWlibms SUNWdfbh SUNWxglh SUNWcg6h

Uninstall Default Apache Packages:
root# /etc/init.d/apache stop
root# pkginfo |grep Apache
root# pkgrm SUNWaclg SUNWapchd SUNWapchr SUNWapchu

Create installation Directory:
root# mkdir /phpdata/

Download Required Packages from Sunfreeware:

Install libiconv-1.8 and gcc3.3.2 packages
root# pkgadd -d ./libiconv-1.8-sol9-sparc-local
root# pkgadd -d ./gcc-3.3.2-sol9-sparc-local

set LD_LIBRARY_PATH, CC and PATH variables
root# LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib/sparcv9/:\
/usr/lib:/usr/openwin/lib:/opt/local/lib:/usr/local/ssl/lib:\
/usr/local/apr/lib:/opt/mysql/mysql/lib
root# CC=gcc
root# PATH=$PATH:/usr/ucb:/usr/local/bin/
root# export LD_LIBRARY_PATH CC PATH
 
Install apr-1.2.2 and aprutil-1.2.2 packages

root# gzcat apr-1.2.2.tar.gz |tar xvf -
root# cd apr-1.2.2
root# ./configure
root# make
root# make install
root# cd ..

root# gzcat aprutil-1.2.2.tar.gz |tar xvf -
root# cd apr-util-1.2.2/
root# ./configure --with-apr=/usr/local/apr/
root# make
root# make install

Install gawk-3.1.4, expat-1.95.5, db-4.2.52.NC,
gdbm-1.8.3, libgcc-3.3 and libxml2-2.6.16 packages
root# cd ..
root# pkgadd -d ./gawk-3.1.4-sol9-sparc-local
root# pkgadd -d ./expat-1.95.5-sol9-sparc-local
root# pkgadd -d ./db-4.2.52.NC-sol9-sparc-local
root# pkgadd -d ./gdbm-1.8.3-sol9-sparc-local
root# pkgadd -d ./libgcc-3.3-sol9-sparc-local
root# pkgadd -d ./libxml2-2.6.16-sol9-sparc-local

Install GNU make package
root# gzcat make-3.81.tar.gz |tar xvf -
root# cd make-3.81
root# ./configure
root# make
root# make install
root# cd ..

Install mysql-standard-5.0.22 package
Search for user mysql
root# grep mysql /etc/passwd
root# grep mysql /etc/group

If not found create user and group mysql
root# groupadd mysql
root# useradd -G mysql mysql
root# pkgadd -d ./mysql-standard-5.0.22-solaris9-sparc.pkg.gz

Install openssl-0.9.7g package
root# gzcat openssl-0.9.7g.tar.gz |tar xvf -
root# cd openssl-0.9.7g
root# ./config shared
root# make
root# make install
root# cd ..

Install Apache2 package
root# gzcat httpd-2.2.0.tar.gz |tar xvf -
root# cd httpd-2.2.0
root# ./configure --enable-so
root# /usr/local/bin/make
root# /usr/local/bin/make install
root# cd ..

Install php-5.1.4 package
root# gzcat php-5.1.4.tar.gz |tar xvf -
root# cd php-5.1.4
root# ./configure --with-apxs2=/usr/local/apache2/bin/apxs\
--with-ldap --with-mysql=/opt/mysql/mysql/
root# /usr/local/bin/make
root# /usr/local/bin/make install
root# cp php.ini-dist /usr/local/lib/php.ini

Edit httpd.conf to load the PHP module
and to parse certain extensions as PHP
root# vi /usr/local/apache2/conf/httpd.conf
LoadModule php5_module modules/libphp5.so
AddType application/x-httpd-php .php .phtml

Start Apache
root# /usr/local/apache2/bin/apachectl start
 
Add environmental variables below HTTPD
root# vi /usr/local/apache2/bin/apachectl
LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib/sparcv9/:
/usr/lib:/usr/openwin/lib:/opt/local/lib:/usr/local/ssl/lib:
/usr/local/apr/lib:/opt/mysql/mysql/lib
PATH=/bin:/sbin:/usr/ccs/bin:/usr/sbin:/usr/openwin/bin:\
/usr/ucb:/usr/local/bin/
export LD_LIBRARY_PATH PATH

Create Apache Startup Script
To Top