Difference between revisions of "Apache HTTP Server"

From ArchWiki
Jump to: navigation, search
m (User directories: Requires root access)
(Create a key and (self-signed) certificate: link to talk from Template:Remove)
 
(253 intermediate revisions by 81 users not shown)
Line 1: Line 1:
[[Category:Web Server]]
+
[[Category:Web server]]
[[cs:LAMP]]
+
[[cs:Apache HTTP Server]]
 
[[de:LAMP Installation]]
 
[[de:LAMP Installation]]
[[el:LAMP]]
+
[[el:Apache HTTP Server]]
[[es:LAMP]]
+
[[es:Apache HTTP Server]]
 +
[[fa:LAMP]]
 
[[fr:Lamp]]
 
[[fr:Lamp]]
[[it:LAMP]]
+
[[it:Apache HTTP Server]]
[[pl:LAMP]]
+
[[ja:Apache HTTP Server]]
[[ru:LAMP]]
+
[[ko:Apache HTTP Server]]
[[sr:LAMP]]
+
[[pl:Apache HTTP Server]]
[[tr:LAMP]]
+
[[ru:Apache HTTP Server]]
[[zh-CN:LAMP]]
+
[[sr:Apache HTTP Server]]
{{Article summary start}}
+
[[zh-hans:Apache HTTP Server]]
{{Article summary text|This page explains the installation and configuration of a complete LAMP server.}}
+
{{Related articles start}}
{{Article summary heading|Related}}
+
{{Related|XAMPP}}
{{Article summary wiki|MySQL}}
+
{{Related|/mod_perl}}
{{Article summary wiki|PhpMyAdmin}}
+
{{Related articles end}}
{{Article summary wiki|Adminer}}
+
The [[Wikipedia:Apache HTTP Server|Apache HTTP Server]], or Apache for short, is a very popular web server, developed by the Apache Software Foundation.
{{Article summary wiki|Xampp}}
 
{{Article summary wiki|mod_perl}}
 
{{Article summary end}}
 
[[Wikipedia:LAMP (software bundle)|LAMP]] refers to a common combination of software used in many web servers: '''L'''inux, '''A'''pache, '''M'''ySQL, and '''P'''HP. This article describes how to set up the [http://httpd.apache.org Apache HTTP Server] on an Arch Linux system. It also tells you how to optionally install [[PHP]] and [[MySQL]] and integrate these in the Apache server.
 
  
If you only need a web server for development and testing, [[Xampp]] might be a better and easier option.
+
This article describes how to set up Apache and how to optionally integrate it with [[PHP]].
  
 
== Installation ==
 
== Installation ==
This document assumes you will install Apache, PHP and MySQL together. If desired however, you may install Apache, PHP, and MySQL separately and simply refer to the relevant sections below.
+
[[Install]] the {{Pkg|apache}} package.
  
You can [[pacman|install]] {{Pkg|apache}}, {{Pkg|php}}, {{Pkg|php-apache}} and {{Pkg|mysql}} from the [[official repositories]]. Alternatively, run:
+
== Configuration ==
  $ pacman -S apache php php-apache mysql
+
Apache configuration files are located in {{ic|/etc/httpd/conf}}. The main configuration file is {{ic|/etc/httpd/conf/httpd.conf}}, which includes various other configuration files.
 +
The default configuration file should be fine for a simple setup. By default, it will serve the directory {{ic|/srv/http}} to anyone who visits your website.
 +
 
 +
To start Apache, start {{ic|httpd.service}} using [[systemd#Using units|systemd]].
 +
 
 +
Apache should now be running. Test by visiting http://localhost/ in a web browser. It should display a simple index page.
 +
 
 +
For optional further configuration, see the following sections.
 +
 
 +
=== Advanced options ===
 +
 
 +
See the [https://httpd.apache.org/docs/trunk/mod/directives.html full list of Apache configuration directives] and the [https://httpd.apache.org/docs/trunk/mod/quickreference.html directive quick reference].
 +
 
 +
These options in {{ic|/etc/httpd/conf/httpd.conf}} might be interesting for you:
 +
 
 +
User http
 +
:For security reasons, as soon as Apache is started by the root user (directly or via startup scripts) it switches to this UID. The default user is ''http'', which is created automatically during installation.
 +
 
 +
Listen 80
 +
:This is the port Apache will listen to. For Internet-access with router, you have to forward the port.
 +
 
 +
:If you want to setup Apache for local development you may want it to be only accessible from your computer. Then change this line to {{ic|Listen 127.0.0.1:80}}.
 +
 
 +
ServerAdmin you@example.com
 +
:This is the admin's email address which can be found on e.g. error pages.
 +
 
 +
DocumentRoot "/srv/http"
 +
:This is the directory where you should put your web pages.
 +
 
 +
:Change it, if you want to, but do not forget to also change {{ic|<Directory "/srv/http">}} to whatever you changed your {{ic|DocumentRoot}} to, or you will likely get a '''403 Error''' (lack of privileges) when you try to access the new document root. Do not forget to change the {{ic|Require all denied}} line to {{ic|Require all granted}}, otherwise you will get a '''403 Error'''. Remember that the DocumentRoot directory and its parent folders must allow execution permission to others (can be set with {{ic|chmod o+x /path/to/DocumentRoot}}), otherwise you will get a '''403 Error'''.
 +
 
 +
AllowOverride None
 +
:This directive in {{ic|<Directory>}} sections causes Apache to completely ignore {{ic|.htaccess}} files. Note that this is now the default for Apache 2.4, so you need to explicitly allow overrides if you plan to use {{ic|.htaccess}} files. If you intend to use {{ic|mod_rewrite}} or other settings in {{ic|.htaccess}} files, you can allow which directives declared in that file can override server configuration. For more info refer to the [http://httpd.apache.org/docs/current/mod/core.html#allowoverride Apache documentation].
 +
 
 +
{{Tip|If you have issues with your configuration you can have Apache check the configuration with: {{ic|apachectl configtest}}}}
 +
 
 +
More settings can be found in {{ic|/etc/httpd/conf/extra/httpd-default.conf}}:
 +
 
 +
To turn off your server's signature:
 +
ServerSignature Off
  
{{Note|New default user and group: Instead of group '''nobody''', {{ic|apache}} now runs as user/group '''http''' by default. You might want to adjust your {{ic|httpd.conf}} according to this change, although it is still possible to run {{ic|httpd}} as '''nobody'''.}}
+
To hide server information like Apache and PHP versions:
 +
ServerTokens Prod
  
== Configuration ==
+
=== User directories ===
  
=== Apache ===
+
User directories are available by default through http://localhost/~yourusername/ and show the contents of {{ic|~/public_html}} (this can be changed in {{ic|/etc/httpd/conf/extra/httpd-userdir.conf}}).
For security reasons, as soon as Apache is started by the root user (directly or via startup scripts) it switches to the UID/GID specified in {{ic|/etc/httpd/conf/httpd.conf}}. The default is user '''http''' and it is created automatically during installation.
 
  
After installation, you can:
+
If you do not want user directories to be available on the web, comment out the following line in {{ic|/etc/httpd/conf/httpd.conf}}:
* Change {{ic|httpd.conf}} and optionally {{ic|extra/httpd-default.conf}} to your liking and
 
* [[Daemons|Start]] the '''httpd''' daemon.
 
  $ httpd
 
  
:Apache should now be running. Test by visiting http://localhost/ in a web browser. It should display a simple Apache test page. If you receive a '''403 Error''', comment out the following line in {{ic|/etc/httpd/conf/httpd.conf}}:
 
 
  Include conf/extra/httpd-userdir.conf
 
  Include conf/extra/httpd-userdir.conf
  
==== User directories ====
+
{{Accuracy|It is not necessary to set {{ic|+x}} for every users, setting it only for the webserver via ACLs suffices (see [[Access Control Lists#Granting execution permissions for private files to a Web Server]]).}}
* User directories are available by default through http://localhost/~user/ and show the contents of {{ic|~/public_html}} (this can be changed in {{ic|/etc/httpd/conf/extra/httpd-userdir.conf}}).
+
 
 +
You must make sure that your home directory permissions are set properly so that Apache can get there. Your home directory and {{ic|~/public_html}} must be executable for others ("rest of the world"):
 +
 
 +
$ chmod o+x ~
 +
$ chmod o+x ~/public_html
 +
$ chmod -R o+r ~/public_html
  
* If you do not want user directories to be available on the web, comment the following line in {{ic|/etc/httpd/conf/httpd.conf}}:
+
Restart {{ic|httpd.service}} to apply any changes. See also [[Umask#Set the mask value]].
  Include conf/extra/httpd-userdir.conf
 
  
* You must make sure that your home directory permissions are set properly so that Apache can get there. Your home directory and {{ic|~/public_html/}} must be executable for others ("rest of the world"). This seems to be enough:
+
=== TLS ===
  $ chmod o+x ~
+
{{Warning|If you deploy [[Wikipedia:TLS|TLS]], be sure to follow [https://weakdh.org/sysadmin.html weakdh.org's guide] to prevent vulnerabilities. For more information see [[Server-side TLS]].}}
  $ chmod o+x ~/public_html
 
  
* A more secure way to share your home folder with Apache is to add the '''http''' user to the group that owns your home folder. For example, if your home folder and other sub-folders in your home folder belong to group '''piter''', all you have to do is following:
+
To obtain a certificate, see [[OpenSSL#Certificates]].
  # usermod -aG http piter
 
  
* Of course, you have to give ''read'' and ''execute'' permissions on {{ic|~/}},  {{ic|~/public_html}}, and all other sub-folders in {{ic|~/public_html}} to the group members (group '''piter''' in our case). Do something like the following ('''modify the commands for your specific case'''):
+
In {{ic|/etc/httpd/conf/httpd.conf}}, uncomment the following three lines:
  $ chmod g+xr-w /home/''yourusername''
+
LoadModule ssl_module modules/mod_ssl.so
  $ chmod -R g+xr-w /home/''yourusername''/public_html
+
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
 +
Include conf/extra/httpd-ssl.conf
  
{{Note|This way you do not have to give access to your folder to every single user in order to give access to '''http''' user. Only the '''http''' user and other potential users that are in the '''piter''' group will have access to your home folder.}}
+
If using {{ic|certbot --apache}}, the following line needs to be uncommented as well:
 +
LoadModule rewrite_module modules/mod_rewrite.so
  
and [[Daemons|restart]] '''httpd'''.
+
For TLS, you will need a key and certificate. If you own a public domain, you can use [[Let's Encrypt]] to obtain a certificate for free, otherwise follow [[#Create a key and (self-signed) certificate]].
  
==== SSL ====
+
After obtaining a key and certificate, make sure the {{ic|SSLCertificateFile}} and {{ic|SSLCertificateKeyFile}} lines in {{ic|/etc/httpd/conf/extra/httpd-ssl.conf}} point to the key and certificate. If a concatenated chain of CA certificates was also generated, add that filename against {{ic|SSLCertificateChainFile}}.
* Create a self-signed certificate (you can change the key size and the number of days of validity):
 
  # cd /etc/httpd/conf
 
  # openssl genrsa -des3 -out server.key 1024
 
  # openssl req -new -key server.key -out server.csr
 
  # cp server.key server.key.org
 
  # openssl rsa -in server.key.org -out server.key
 
  # openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
 
  
* Then, in {{ic|/etc/httpd/conf/httpd.conf}}, uncomment the line containing:
+
Finally, restart {{ic|httpd.service}} to apply any changes.
  Include conf/extra/httpd-ssl.conf
 
and [[Daemons|restart]] '''httpd'''.
 
  
==== Virtual Hosts ====
+
{{Tip|Mozilla has a useful [[MozillaWiki:Security/Server_Side_TLS|SSL/TLS article]] as well as an [https://mozilla.github.io/server-side-tls/ssl-config-generator/ automated tool] to help create a more secure configuration.}}
* If you want to have more than one host, make sure you have
 
{{bc|
 
# Virtual hosts
 
Include conf/extra/httpd-vhosts.conf
 
}}
 
in {{ic|/etc/httpd/conf/httpd.conf}}.
 
  
* In {{ic|/etc/httpd/conf/extra/httpd-vhosts.conf}} set your virtual hosts according the example, e.g.:
+
==== Create a key and (self-signed) certificate ====
{{hc|/etc/httpd/conf/extra/httpd-vhosts.conf|
 
NameVirtualHost *:80
 
  
#this first virtualhost enables: http://127.0.0.1, or: http://localhost,
+
{{Remove|Duplicates [[OpenSSL#Certificates]]|section=Removal of Create a key and (self-signed) certificate section}}
#to still go to /srv/http/*index.html(otherwise it will 404_error).
 
#the reason for this: once you tell httpd.conf to include extra/httpd-vhosts.conf,
 
#ALL vhosts are handled in httpd-vhosts.conf(including the default one),
 
# E.G. the default virtualhost in httpd.conf is not used and must be included here,
 
#otherwise, only domainname1.dom & domainname2.dom will be accessible
 
#from your web browser and NOT http://127.0.0.1, or: http://localhost, etc.
 
#
 
  
<VirtualHost *:80>
+
Create a private key and self-signed certificate. This is adequate for most installations that do not require a [[wikipedia:Certificate signing request|CSR]]:
    DocumentRoot "/srv/http"
 
    ServerAdmin root@localhost
 
    ErrorLog "/var/log/httpd/127.0.0.1-error_log"
 
    CustomLog "/var/log/httpd/127.0.0.1-access_log" common
 
    <Directory /srv/http/>
 
      DirectoryIndex index.htm index.html
 
      AddHandler cgi-script .cgi .pl
 
      Options ExecCGI Indexes FollowSymLinks MultiViews +Includes
 
      AllowOverride None
 
      Order allow,deny
 
      Allow from all
 
    </Directory>
 
</VirtualHost>
 
  
<VirtualHost *:80>
+
# cd /etc/httpd/conf
    ServerAdmin your@domainname1.dom
+
# openssl req -new -x509 -nodes -newkey rsa:4096 -keyout server.key -out server.crt -days 1095
    DocumentRoot "/home/username/yoursites/domainname1.dom/www"
+
# chmod 400 server.key
    ServerName domainname1.dom
 
    ServerAlias domainname1.dom
 
    <Directory /home/username/yoursites/domainname1.dom/www/>
 
      DirectoryIndex index.htm index.html
 
      AddHandler cgi-script .cgi .pl
 
      Options ExecCGI Indexes FollowSymLinks MultiViews +Includes
 
      AllowOverride None
 
      Order allow,deny
 
      Allow from all
 
</Directory>
 
</VirtualHost>
 
  
<VirtualHost *:80>
+
{{Note|The -days switch is optional and RSA keysize can be as low as 2048 (default).}}
    ServerAdmin your@domainname2.dom
 
    DocumentRoot "/home/username/yoursites/domainname2.dom/www"
 
    ServerName domainname2.dom
 
    ServerAlias domainname2.dom
 
    <Directory /home/username/yoursites/domainname2.dom/www/>
 
      DirectoryIndex index.htm index.html
 
      AddHandler cgi-script .cgi .pl
 
      Options ExecCGI Indexes FollowSymLinks MultiViews +Includes
 
      AllowOverride None
 
      Order allow,deny
 
      Allow from all
 
</Directory>
 
</VirtualHost>
 
}}
 
  
* Add your virtual host names to your {{ic|/etc/hosts}} file (not necessary if [[BIND]] is serving these domains already, but will not hurt to do it anyway):
+
If you need to create a [[wikipedia:Certificate signing request|CSR]], follow these keygen instructions instead of the above:
{{bc|127.0.0.1 domainname1.dom
 
127.0.0.1 domainname2.dom}}
 
  
and [[Daemons|restart]] '''httpd'''.
+
# cd /etc/httpd/conf
 +
# openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out server.key
 +
# chmod 400 server.key
 +
# openssl req -new -sha256 -key server.key -out server.csr
 +
# openssl x509 -req -days 1095 -in server.csr -signkey server.key -out server.crt
  
* If you setup your virtual hosts to be in your user directory, sometimes it interferes with Apache's {{ic|Userdir}} settings. To avoid problems disable {{ic|Userdir}} by commenting it out:
+
{{Note|For more openssl options, read the [https://www.openssl.org/docs/apps/openssl.html man page] or peruse openssl's [https://www.openssl.org/docs/ extensive documentation].}}
{{bc|
 
# User home directories
 
#Include conf/extra/httpd-userdir.conf}}
 
  
* As said above, ensure that you have the proper permissions:
+
=== Virtual hosts ===
# chmod 0775 /home/''yourusername''/
 
  
* If you have a huge amount of virtual hosts, you may want to easily disable and enable them. It is recommended to create one configuration file per virtual host and store them all in one folder, eg: {{ic|/etc/httpd/conf/vhosts}}.
+
{{Note|You will need to add a separate {{ic|<VirtualHost *:443>}} section for virtual host SSL support.
 +
See [[#Managing many virtual hosts]] for an example file.}}
  
* First create the folder:
+
If you want to have more than one host, uncomment the following line in {{ic|/etc/httpd/conf/httpd.conf}}:
# mkdir /etc/httpd/conf/vhosts
+
Include conf/extra/httpd-vhosts.conf
  
* Then place the single configuration files in it:
+
In {{ic|/etc/httpd/conf/extra/httpd-vhosts.conf}} set your virtual hosts. The default file contains an elaborate example that should help you get started.
# nano /etc/httpd/conf/vhosts/domainname1.dom
 
# nano /etc/httpd/conf/vhosts/domainname2.dom
 
...
 
  
* In the last step, {{ic|Include}} the single configurations in your {{ic|/etc/httpd/conf/httpd.conf}}:
+
To test the virtual hosts on your local machine, add the virtual names to your {{ic|/etc/hosts}} file:
{{bc|
+
127.0.0.1 domainname1.dom  
#Enabled Vhosts:
+
127.0.0.1 domainname2.dom
Include conf/vhosts/domainname1.dom
 
#Include conf/vhosts/domainname1.dom
 
}}
 
  
* You can enable and disable single virtual hosts by commenting or uncommenting them.
+
Restart {{ic|httpd.service}} to apply any changes.
  
==== Advanced Options ====
+
==== Managing many virtual hosts ====
These options in {{ic|/etc/httpd/conf/httpd.conf}} might be interesting for you.
 
  
# Listen 80
+
If you have a huge amount of virtual hosts, you may want to easily disable and enable them. It is recommended to create one configuration file per virtual host and store them all in one folder, eg: {{ic|/etc/httpd/conf/vhosts}}.
* This is the port Apache will listen to. For Internet-access with router, you have to forward the port.
 
  
If you setup Apache for local development you may want it to be only accessible from your computer. Then change this line to:
+
First create the folder:
  # Listen 127.0.0.1:80
+
  # mkdir /etc/httpd/conf/vhosts
  
* This is the admin's email address which can be found on e.g. error pages:
+
Then place the single configuration files in it:
  # ServerAdmin you@example.com
+
# nano /etc/httpd/conf/vhosts/domainname1.dom
 +
# nano /etc/httpd/conf/vhosts/domainname2.dom
 +
  ...
  
* This is the directory where you should put your web pages:
+
In the last step, {{ic|Include}} the single configurations in your {{ic|/etc/httpd/conf/httpd.conf}}:
  # DocumentRoot "/srv/http"
+
  #Enabled Vhosts:
 +
Include conf/vhosts/domainname1.dom
 +
Include conf/vhosts/domainname2.dom
  
Change it, if you want to, but do not forget to also change
+
You can enable and disable single virtual hosts by commenting or uncommenting them.
<Directory "/srv/http">
 
to whatever you changed your {{ic|DocumentRoot}} too, or you will likely get a '''403 Error''' (lack of privileges) when you try to access the new document root. Do not forget to change the {{ic|Deny from all}} line, otherwise you will get a '''403 Error'''.
 
  
# AllowOverride None
+
A very basic vhost file will look like this:
* This directive in {{ic|<Directory>}} sections causes Apache to completely ignore {{ic|.htaccess}} files. If you intend to use {{ic|mod_rewrite}} or other settings in {{ic|.htaccess}} files, you can allow which directives declared in that file can override server configuration. For more info refer to the [http://httpd.apache.org/docs/current/mod/core.html#allowoverride Apache documentation].
 
  
{{Note|If you have issues with your configuration you can have Apache check the configuration with: {{ic|apachectl configtest}}}}
+
{{hc|/etc/httpd/conf/vhosts/domainname1.dom|<nowiki>
 +
<VirtualHost *:80>
 +
    ServerAdmin webmaster@domainname1.dom
 +
    DocumentRoot "/home/user/http/domainname1.dom"
 +
    ServerName domainname1.dom
 +
    ServerAlias domainname1.dom
 +
    ErrorLog "/var/log/httpd/domainname1.dom-error_log"
 +
    CustomLog "/var/log/httpd/domainname1.dom-access_log" common
  
* More settings in {{ic|/etc/httpd/conf/httpd.conf}}:
+
    <Directory "/home/user/http/domainname1.dom">
 +
        Require all granted
 +
    </Directory>
 +
</VirtualHost>
  
* To turn off your server's signature:
+
<VirtualHost *:443>
ServerSignature Off
+
    ServerAdmin webmaster@domainname1.dom
 +
    DocumentRoot "/home/user/http/domainname1.dom"
 +
    ServerName domainname1.dom:443
 +
    ServerAlias domainname1.dom:443
 +
    SSLEngine on
 +
    SSLCertificateFile "/etc/httpd/conf/server.crt"
 +
    SSLCertificateKeyFile "/etc/httpd/conf/server.key"
 +
    ErrorLog "/var/log/httpd/domainname1.dom-error_log"
 +
    CustomLog "/var/log/httpd/domainname1.dom-access_log" common
 +
 
 +
    <Directory "/home/user/http/domainname1.dom">
 +
        Require all granted
 +
    </Directory>
 +
</VirtualHost></nowiki>}}
  
* To hide server information like Apache and PHP versions:
+
== Extensions ==
ServerTokens Prod
 
  
 
=== PHP ===
 
=== PHP ===
* To enable PHP, add these lines to {{ic|/etc/httpd/conf/httpd.conf}}:
+
First install PHP as explained in on the [[PHP]] page.
:Place this in the {{ic|LoadModule}} list anywhere after {{ic|LoadModule dir_module modules/mod_dir.so}}:
 
  LoadModule php5_module modules/libphp5.so
 
  
:Place this at the end of the {{ic|Include}} list:
+
There are multiple methods to use PHP with Apache. [[#Using libphp]] is probably the easiest, but also the least scalable. libphp also requires you to change the mpm module, which may cause problems with other extensions (e.g. it is not compatible with [[#HTTP2]]).
  Include conf/extra/php5_module.conf
 
  
:Make sure that the following line is uncommented in the {{ic|<IfModule mime_module>}} section:
+
==== Using libphp ====
  TypesConfig conf/mime.types
+
[[Install]] the {{Pkg|php-apache}} package.
  
:Uncomment the following line (optional):
+
In {{ic|/etc/httpd/conf/httpd.conf}}, comment the line:
  MIMEMagicFile conf/magic
+
#LoadModule mpm_event_module modules/mod_mpm_event.so
 +
and uncomment the line:
 +
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
  
* Add this line in {{ic|/etc/httpd/conf/mime.types}}:
+
{{Note|1=The above is required, because {{ic|libphp7.so}} included with {{pkg|php-apache}} does not work with {{ic|mod_mpm_event}}, but will only work {{ic|mod_mpm_prefork}} instead. ({{bug|39218}})
  application/x-httpd-php      php    php5
 
  
{{Note|If you do not see {{ic|libphp5.so}} in the Apache modules directory ({{ic|/etc/httpd/modules}}), you may have forgotten to install {{Pkg|php-apache}}.}}
+
Otherwise you will get the following error:
 +
{{bc|1=Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.  You need to recompile PHP.
 +
AH00013: Pre-configuration failed
 +
httpd.service: control process exited, code=exited status=1}}
 +
 
 +
As an alternative, you can use {{ic|mod_proxy_fcgi}} (see [[#Using php-fpm and mod_proxy_fcgi]] below).
 +
}}
  
* If your {{ic|DocumentRoot}} is not {{ic|/srv/http}}, add it to {{ic|open_basedir}} in {{ic|/etc/php/php.ini}} as such:
+
To enable PHP, add these lines to {{ic|/etc/httpd/conf/httpd.conf}}:
  open_basedir=/srv/http/:/home/:/tmp/:/usr/share/pear/:/path/to/documentroot
+
*Place this at the end of the {{ic|LoadModule}} list:
 +
LoadModule php7_module modules/libphp7.so
 +
AddHandler php7-script .php
 +
*Place this at the end of the {{ic|Include}} list:
 +
Include conf/extra/php7_module.conf
  
* [[Daemons|Restart]] the '''httpd''' daemon.
+
Restart {{ic|httpd.service}} using [[systemd#Using units|systemd]].
  
* To test whether PHP was correctly configured: create a file called {{ic|test.php}} in your Apache {{ic|DocumentRoot}} directory (e.g. {{ic|/srv/http/}} or {{ic|~/public_html}}) and inside it put:
+
==== Using php-fpm and mod_proxy_fcgi ====
<?php phpinfo(); ?>
 
:To see if it works go to: http://localhost/test.php or http://localhost/~myname/test.php
 
  
:If the PHP code is not executed (you see plain text in {{ic|test.php}}), check that you have added {{ic|Includes}} to the {{ic|Options}} line for your root directory in {{ic|/etc/httpd/conf/httpd.conf}}. Moreover, check that {{ic|TypesConfig conf/mime.types}} is uncommented in the <IfModule mime_module> section, you may also try adding the following to the {{ic|<IfModule mime_module>}} in {{ic|httpd.conf}}:
+
{{Note|Unlike the widespread setup with ProxyPass, the proxy configuration with SetHandler respects other Apache directives like DirectoryIndex. This ensures a better compatibility with software designed for libphp7, mod_fastcgi and mod_fcgid.
AddHandler application/x-httpd-php .php
+
If you still want to try ProxyPass, experiment with a line like this: {{bc|ProxyPassMatch ^/(.*\.php(/.*)?)$ unix:/run/php-fpm/php-fpm.sock&#124;fcgi://localhost/srv/http/$1}}}}
  
==== Advanced options ====
+
[[Install]] the {{pkg|php-fpm}} package.
* It is recommended to set your timezone ([http://www.php.net/manual/en/timezones.php list of timezones]) in {{ic|/etc/php/php.ini}} like so:
 
{{bc|1=date.timezone = Europe/Berlin}}
 
  
* If you want to display errors to debug your PHP code, change {{ic|display_errors}} to {{ic|On}} in {{ic|/etc/php/php.ini}}:
+
Enable proxy modules:
display_errors=On
+
{{hc|/etc/httpd/conf/httpd.conf|<nowiki>
 +
LoadModule proxy_module modules/mod_proxy.so
 +
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
 +
</nowiki>}}
  
* If you want the {{ic|libGD}} module, install {{Pkg|php-gd}} and uncomment {{ic|1=extension=gd.so}} in {{ic|/etc/php/php.ini}}:
+
Create {{ic|/etc/httpd/conf/extra/php-fpm.conf}} with the following content:
{{Note|{{Pkg|php-gd}} requires {{Pkg|libpng}}, {{Pkg|libjpeg-turbo}}, and {{Pkg|freetype2}}.}}
+
{{hc|/etc/httpd/conf/extra/php-fpm.conf|<nowiki>
extension=gd.so
+
DirectoryIndex index.php index.html
 +
<FilesMatch \.php$>
 +
    SetHandler "proxy:unix:/run/php-fpm/php-fpm.sock|fcgi://localhost/"
 +
</FilesMatch>
 +
</nowiki>}}
  
{{Note|Pay attention to which extension you uncomment, as this extension is sometimes mentioned in an explanatory comment before the actual line you want to uncomment.}}
+
And include it at the bottom of {{ic|/etc/httpd/conf/httpd.conf}}:
 +
Include conf/extra/php-fpm.conf
  
* If you want the {{ic|mcrypt}} module, install {{Pkg|php-mcrypt}} and uncomment {{ic|1=extension=mcrypt.so}} in {{ic|/etc/php/php.ini}}:
+
{{Note|The pipe between {{ic|sock}} and {{ic|fcgi}} is not allowed to be surrounded by a space! {{ic|localhost}} can be replaced by any string. More [https://httpd.apache.org/docs/2.4/mod/mod_proxy_fcgi.html here]}}
extension=mcrypt.so
 
  
* Remember to add a file handler for {{ic|.phtml}}, if you need it, in {{ic|/etc/httpd/conf/extra/php5_module.conf}}:
+
You can configure PHP-FPM in {{ic|/etc/php/php-fpm.d/www.conf}}, but the default setup should work fine.
DirectoryIndex index.php index.phtml index.html
 
  
==== Using php5 with apache2-mpm-worker and mod_fcgid ====
+
Start and enable {{ic|php-fpm.service}}. [[Restart]] {{ic|httpd.service}}.
* Uncomment following in {{ic|/etc/conf.d/apache}}:
 
HTTPD=/usr/sbin/httpd.worker
 
  
* Uncomment following in {{ic|/etc/httpd/conf/httpd.conf}}:
+
==== Using apache2-mpm-worker and mod_fcgid ====
Include conf/extra/httpd-mpm.conf
+
[[Install]] the {{pkg|mod_fcgid}} and {{Pkg|php-cgi}} packages.
  
* [[Pacman|Install]] the {{pkg|mod_fcgid}} and {{Pkg|php-cgi}} packages from the [[official repositories]].
+
Create the needed directory and symlink it for the PHP wrapper:
 +
# mkdir /srv/http/fcgid-bin
 +
# ln -s /usr/bin/php-cgi /srv/http/fcgid-bin/php-fcgid-wrapper
  
* Create {{ic|/etc/httpd/conf/extra/php5_fcgid.conf}} with following content:
+
Create {{ic|/etc/httpd/conf/extra/php-fcgid.conf}} with the following content:
{{hc|/etc/httpd/conf/extra/php5_fcgid.conf|<nowiki>
+
{{hc|/etc/httpd/conf/extra/php-fcgid.conf|<nowiki>
 
# Required modules: fcgid_module
 
# Required modules: fcgid_module
  
 
<IfModule fcgid_module>
 
<IfModule fcgid_module>
AddHandler php-fcgid .php
+
    AddHandler php-fcgid .php
AddType application/x-httpd-php .php
+
    AddType application/x-httpd-php .php
Action php-fcgid /fcgid-bin/php-fcgid-wrapper
+
    Action php-fcgid /fcgid-bin/php-fcgid-wrapper
ScriptAlias /fcgid-bin/ /srv/http/fcgid-bin/
+
    ScriptAlias /fcgid-bin/ /srv/http/fcgid-bin/
SocketPath /var/run/httpd/fcgidsock
+
    SocketPath /var/run/httpd/fcgidsock
SharememPath /var/run/httpd/fcgid_shm
+
    SharememPath /var/run/httpd/fcgid_shm
 
         # If you don't allow bigger requests many applications may fail (such as WordPress login)
 
         # If you don't allow bigger requests many applications may fail (such as WordPress login)
 
         FcgidMaxRequestLen 536870912
 
         FcgidMaxRequestLen 536870912
        PHP_Fix_Pathinfo_Enable 1
 
 
         # Path to php.ini – defaults to /etc/phpX/cgi
 
         # Path to php.ini – defaults to /etc/phpX/cgi
 
         DefaultInitEnv PHPRC=/etc/php/
 
         DefaultInitEnv PHPRC=/etc/php/
Line 290: Line 287:
 
         # Maximum requests before a process is stopped and a new one is launched
 
         # Maximum requests before a process is stopped and a new one is launched
 
         #DefaultInitEnv PHP_FCGI_MAX_REQUESTS 5000
 
         #DefaultInitEnv PHP_FCGI_MAX_REQUESTS 5000
        <Location /fcgid-bin/>
+
    <Location /fcgid-bin/>
SetHandler fcgid-script
+
        SetHandler fcgid-script
Options +ExecCGI
+
        Options +ExecCGI
</Location>
+
    </Location>
</IfModule></nowiki>
+
</IfModule>
 +
</nowiki>}}
 +
 
 +
Edit {{ic|/etc/httpd/conf/httpd.conf}}, enabling the actions module:
 +
LoadModule actions_module modules/mod_actions.so
 +
 
 +
And add the following lines:
 +
LoadModule fcgid_module modules/mod_fcgid.so
 +
Include conf/extra/httpd-mpm.conf
 +
Include conf/extra/php-fcgid.conf
 +
 
 +
[[Restart]] {{ic|httpd.service}}.
 +
 
 +
==== Test if PHP works ====
 +
 +
To test whether PHP was correctly configured: create a file called {{ic|test.php}} in your Apache {{ic|DocumentRoot}} directory (e.g. {{ic|/srv/http/}} or {{ic|~/public_html}}) with the following contents:
 +
<?php phpinfo(); ?>
 +
To see if it works go to: http://localhost/test.php or http://localhost/~myname/test.php
 +
 
 +
=== HTTP2 ===
 +
 
 +
To enable HTTP/2 support, uncomment the following line in {{ic|httpd.conf}}:
 +
LoadModule http2_module modules/mod_http2.so
 +
 
 +
And add the following line:
 +
Protocols h2 http/1.1
 +
 
 +
For more information, see the [https://httpd.apache.org/docs/2.4/mod/mod_http2.html mod_http2] documentation.
 +
 
 +
== Troubleshooting ==
 +
 
 +
=== Apache Status and Logs ===
 +
 
 +
See the status of the Apache daemon with [[systemctl]].
 +
 
 +
Apache logs can be found in  {{ic|/var/log/httpd/}}
 +
 
 +
=== Error: PID file /run/httpd/httpd.pid not readable (yet?) after start ===
 +
 
 +
Comment out the {{ic|unique_id_module}} line in {{ic|httpd.conf}}: {{ic|#LoadModule unique_id_module modules/mod_unique_id.so}}
 +
 
 +
=== Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe. ===
 +
 
 +
If when loading {{ic|php7_module}} the {{ic|httpd.service}} fails, and you get an error like this in the journal:
 +
 
 +
Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.  You need to recompile PHP.
 +
 
 +
you need to replace {{ic|mpm_event_module}} with {{ic|mpm_prefork_module}}:
 +
 
 +
{{hc|/etc/httpd/conf/httpd.conf|
 +
<s>LoadModule mpm_event_module modules/mod_mpm_event.so</s>
 +
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
 
}}
 
}}
  
* Create the needed directory and symlink it for the PHP wrapper:
+
and restart {{ic|httpd.service}}.
# mkdir /srv/http/fcgid-bin
+
 
  # ln -s /usr/bin/php-cgi /srv/http/fcgid-bin/php-fcgid-wrapper
+
=== AH00534: httpd: Configuration error: No MPM loaded. ===
 +
 
 +
You might encounter this error after a recent upgrade. This is only the result of a recent change in {{ic|httpd.conf}} that you might not have reproduced in your local configuration.
 +
To fix it, uncomment the following line.
 +
 
 +
{{hc|/etc/httpd/conf/httpd.conf|
 +
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
 +
}}
 +
 
 +
Also check [[#Apache_is_running_a_threaded_MPM.2C_but_your_PHP_Module_is_not_compiled_to_be_threadsafe.|the above]] if more errors occur afterwards.
 +
 
 +
=== AH00072: make_sock: could not bind to address ===
 +
 
 +
This can be caused by multiple things. Most common issue being that something is already listening on a given port, check via netstat that this is not happening:
 +
 
 +
  # netstat -lnp | grep -e :80 -e :443
 +
 
 +
If you get any output, stop the given service that's taking up the port or kill the runaway process that is causing the port to be bound, and try again.
 +
 
 +
Another issue could be that Apache is not starting as root for some reason - try starting it manually and see if you still get the AH0072 error.
  
* Edit {{ic|/etc/httpd/conf/httpd.conf}}:
+
  # httpd -k start
  #LoadModule php5_module modules/libphp5.so
 
LoadModule fcgid_module modules/mod_fcgid.so
 
Include conf/extra/php5_fcgid.conf
 
  
* Make sure {{ic|/etc/php/php.ini}} has the directive enabled:
+
Finally, you can also have an error with your config and you are listening twice on the given port. Following is an example of a bad config that will trigger this issue:
cgi.fix_pathinfo=1
 
and [[Daemons|restart]] '''httpd'''.
 
  
{{Note|1=As of Apache 2.4 (the {{AUR|apache24}} package is available in the [[AUR]]) you can now use [http://httpd.apache.org/docs/2.4/mod/mod_proxy_fcgi.html mod_proxy_fcgi] (part of the official distribution) with PHP-FPM (and the new event MPM). See this [http://wiki.apache.org/httpd/PHP-FPM configuration example].}}
+
Listen 0.0.0.0:80
 +
Listen [::]:80
  
=== MySQL ===
+
=== Changing the max_execution_time in php.ini has no effect ===
* Configure MySQL as described in [[MySQL]].
 
  
* Uncomment at least one of the following lines in {{ic|/etc/php/php.ini}}:
+
If you changed the {{ic|max_execution_time}} in {{ic|php.ini}} to a value greater than 30 (seconds), you may still get a {{ic|503 Service Unavailable}} response from Apache after 30 seconds. To solve this, add a {{ic|ProxyTimeout}} directive to your http configuration right before the {{ic|<FilesMatch \.php$>}} block:
extension=pdo_mysql.so
 
extension=mysqli.so
 
extension=mysql.so
 
  
* You can add minor privileged MySQL users for your web scripts. You might also want to edit {{ic|/etc/mysql/my.cnf}} and uncomment the {{ic|skip-networking}} line so the MySQL server is only accessible by the localhost. You have to restart MySQL for changes to take effect.
+
{{hc|/etc/httpd/conf/httpd.conf|
 +
ProxyTimeout 300
 +
}}
  
* [[Daemons|Restart]] the '''httpd''' daemon.
+
and restart {{ic|httpd.service}}.
  
{{Tip|You may want to install a tool like [[phpMyAdmin]], [[Adminer]] or {{AUR|mysql-workbench}} to work with your databases.}}
+
== See also ==
  
== External links ==
+
* [https://www.apache.org/ Apache Official Website]
* [http://www.apache.org/ Apache Official Website]
+
* [https://httpd.apache.org/docs/2.4/ Apache documentation]
* [http://www.php.net/ PHP Official Website]
+
* [https://wiki.apache.org/httpd/ Apache wiki]
* [http://www.mysql.com/ MySQL Official Website]
+
* [https://httpd.apache.org/docs/current/misc/security_tips.html Apache documentation - Security Tips]
* [http://www.akadia.com/services/ssh_test_certificate.html Tutorial for creating self-signed certificates]
+
* [https://wiki.apache.org/httpd/CommonMisconfigurations Apache Wiki - Troubleshooting]
* [http://wiki.apache.org/httpd/CommonMisconfigurations Apache Wiki Troubleshooting]
+
* [[debian:Apache|Apache]] on wiki.debian.org

Latest revision as of 05:49, 25 September 2018

The Apache HTTP Server, or Apache for short, is a very popular web server, developed by the Apache Software Foundation.

This article describes how to set up Apache and how to optionally integrate it with PHP.

Installation

Install the apache package.

Configuration

Apache configuration files are located in /etc/httpd/conf. The main configuration file is /etc/httpd/conf/httpd.conf, which includes various other configuration files. The default configuration file should be fine for a simple setup. By default, it will serve the directory /srv/http to anyone who visits your website.

To start Apache, start httpd.service using systemd.

Apache should now be running. Test by visiting http://localhost/ in a web browser. It should display a simple index page.

For optional further configuration, see the following sections.

Advanced options

See the full list of Apache configuration directives and the directive quick reference.

These options in /etc/httpd/conf/httpd.conf might be interesting for you:

User http
For security reasons, as soon as Apache is started by the root user (directly or via startup scripts) it switches to this UID. The default user is http, which is created automatically during installation.
Listen 80
This is the port Apache will listen to. For Internet-access with router, you have to forward the port.
If you want to setup Apache for local development you may want it to be only accessible from your computer. Then change this line to Listen 127.0.0.1:80.
ServerAdmin you@example.com
This is the admin's email address which can be found on e.g. error pages.
DocumentRoot "/srv/http"
This is the directory where you should put your web pages.
Change it, if you want to, but do not forget to also change <Directory "/srv/http"> to whatever you changed your DocumentRoot to, or you will likely get a 403 Error (lack of privileges) when you try to access the new document root. Do not forget to change the Require all denied line to Require all granted, otherwise you will get a 403 Error. Remember that the DocumentRoot directory and its parent folders must allow execution permission to others (can be set with chmod o+x /path/to/DocumentRoot), otherwise you will get a 403 Error.
AllowOverride None
This directive in <Directory> sections causes Apache to completely ignore .htaccess files. Note that this is now the default for Apache 2.4, so you need to explicitly allow overrides if you plan to use .htaccess files. If you intend to use mod_rewrite or other settings in .htaccess files, you can allow which directives declared in that file can override server configuration. For more info refer to the Apache documentation.
Tip: If you have issues with your configuration you can have Apache check the configuration with: apachectl configtest

More settings can be found in /etc/httpd/conf/extra/httpd-default.conf:

To turn off your server's signature:

ServerSignature Off

To hide server information like Apache and PHP versions:

ServerTokens Prod

User directories

User directories are available by default through http://localhost/~yourusername/ and show the contents of ~/public_html (this can be changed in /etc/httpd/conf/extra/httpd-userdir.conf).

If you do not want user directories to be available on the web, comment out the following line in /etc/httpd/conf/httpd.conf:

Include conf/extra/httpd-userdir.conf

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

Reason: It is not necessary to set +x for every users, setting it only for the webserver via ACLs suffices (see Access Control Lists#Granting execution permissions for private files to a Web Server). (Discuss in Talk:Apache HTTP Server#)

You must make sure that your home directory permissions are set properly so that Apache can get there. Your home directory and ~/public_html must be executable for others ("rest of the world"):

$ chmod o+x ~
$ chmod o+x ~/public_html
$ chmod -R o+r ~/public_html

Restart httpd.service to apply any changes. See also Umask#Set the mask value.

TLS

Warning: If you deploy TLS, be sure to follow weakdh.org's guide to prevent vulnerabilities. For more information see Server-side TLS.

To obtain a certificate, see OpenSSL#Certificates.

In /etc/httpd/conf/httpd.conf, uncomment the following three lines:

LoadModule ssl_module modules/mod_ssl.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
Include conf/extra/httpd-ssl.conf

If using certbot --apache, the following line needs to be uncommented as well:

LoadModule rewrite_module modules/mod_rewrite.so

For TLS, you will need a key and certificate. If you own a public domain, you can use Let's Encrypt to obtain a certificate for free, otherwise follow #Create a key and (self-signed) certificate.

After obtaining a key and certificate, make sure the SSLCertificateFile and SSLCertificateKeyFile lines in /etc/httpd/conf/extra/httpd-ssl.conf point to the key and certificate. If a concatenated chain of CA certificates was also generated, add that filename against SSLCertificateChainFile.

Finally, restart httpd.service to apply any changes.

Tip: Mozilla has a useful SSL/TLS article as well as an automated tool to help create a more secure configuration.

Create a key and (self-signed) certificate

Tango-edit-cut.pngThis section is being considered for removal.Tango-edit-cut.png

Create a private key and self-signed certificate. This is adequate for most installations that do not require a CSR:

# cd /etc/httpd/conf
# openssl req -new -x509 -nodes -newkey rsa:4096 -keyout server.key -out server.crt -days 1095
# chmod 400 server.key
Note: The -days switch is optional and RSA keysize can be as low as 2048 (default).

If you need to create a CSR, follow these keygen instructions instead of the above:

# cd /etc/httpd/conf
# openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out server.key
# chmod 400 server.key
# openssl req -new -sha256 -key server.key -out server.csr
# openssl x509 -req -days 1095 -in server.csr -signkey server.key -out server.crt
Note: For more openssl options, read the man page or peruse openssl's extensive documentation.

Virtual hosts

Note: You will need to add a separate <VirtualHost *:443> section for virtual host SSL support. See #Managing many virtual hosts for an example file.

If you want to have more than one host, uncomment the following line in /etc/httpd/conf/httpd.conf:

Include conf/extra/httpd-vhosts.conf

In /etc/httpd/conf/extra/httpd-vhosts.conf set your virtual hosts. The default file contains an elaborate example that should help you get started.

To test the virtual hosts on your local machine, add the virtual names to your /etc/hosts file:

127.0.0.1 domainname1.dom 
127.0.0.1 domainname2.dom

Restart httpd.service to apply any changes.

Managing many virtual hosts

If you have a huge amount of virtual hosts, you may want to easily disable and enable them. It is recommended to create one configuration file per virtual host and store them all in one folder, eg: /etc/httpd/conf/vhosts.

First create the folder:

# mkdir /etc/httpd/conf/vhosts

Then place the single configuration files in it:

# nano /etc/httpd/conf/vhosts/domainname1.dom
# nano /etc/httpd/conf/vhosts/domainname2.dom
...

In the last step, Include the single configurations in your /etc/httpd/conf/httpd.conf:

#Enabled Vhosts:
Include conf/vhosts/domainname1.dom
Include conf/vhosts/domainname2.dom

You can enable and disable single virtual hosts by commenting or uncommenting them.

A very basic vhost file will look like this:

/etc/httpd/conf/vhosts/domainname1.dom
<VirtualHost *:80>
    ServerAdmin webmaster@domainname1.dom
    DocumentRoot "/home/user/http/domainname1.dom"
    ServerName domainname1.dom
    ServerAlias domainname1.dom
    ErrorLog "/var/log/httpd/domainname1.dom-error_log"
    CustomLog "/var/log/httpd/domainname1.dom-access_log" common

    <Directory "/home/user/http/domainname1.dom">
        Require all granted
    </Directory>
</VirtualHost>

<VirtualHost *:443>
    ServerAdmin webmaster@domainname1.dom
    DocumentRoot "/home/user/http/domainname1.dom"
    ServerName domainname1.dom:443
    ServerAlias domainname1.dom:443
    SSLEngine on
    SSLCertificateFile "/etc/httpd/conf/server.crt"
    SSLCertificateKeyFile "/etc/httpd/conf/server.key"
    ErrorLog "/var/log/httpd/domainname1.dom-error_log"
    CustomLog "/var/log/httpd/domainname1.dom-access_log" common

    <Directory "/home/user/http/domainname1.dom">
        Require all granted
    </Directory>
</VirtualHost>

Extensions

PHP

First install PHP as explained in on the PHP page.

There are multiple methods to use PHP with Apache. #Using libphp is probably the easiest, but also the least scalable. libphp also requires you to change the mpm module, which may cause problems with other extensions (e.g. it is not compatible with #HTTP2).

Using libphp

Install the php-apache package.

In /etc/httpd/conf/httpd.conf, comment the line:

#LoadModule mpm_event_module modules/mod_mpm_event.so

and uncomment the line:

LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
Note: The above is required, because libphp7.so included with php-apache does not work with mod_mpm_event, but will only work mod_mpm_prefork instead. (FS#39218)

Otherwise you will get the following error:

Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.  You need to recompile PHP.
AH00013: Pre-configuration failed
httpd.service: control process exited, code=exited status=1
As an alternative, you can use mod_proxy_fcgi (see #Using php-fpm and mod_proxy_fcgi below).

To enable PHP, add these lines to /etc/httpd/conf/httpd.conf:

  • Place this at the end of the LoadModule list:
LoadModule php7_module modules/libphp7.so
AddHandler php7-script .php
  • Place this at the end of the Include list:
Include conf/extra/php7_module.conf

Restart httpd.service using systemd.

Using php-fpm and mod_proxy_fcgi

Note: Unlike the widespread setup with ProxyPass, the proxy configuration with SetHandler respects other Apache directives like DirectoryIndex. This ensures a better compatibility with software designed for libphp7, mod_fastcgi and mod_fcgid. If you still want to try ProxyPass, experiment with a line like this:
ProxyPassMatch ^/(.*\.php(/.*)?)$ unix:/run/php-fpm/php-fpm.sock|fcgi://localhost/srv/http/$1

Install the php-fpm package.

Enable proxy modules:

/etc/httpd/conf/httpd.conf
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so

Create /etc/httpd/conf/extra/php-fpm.conf with the following content:

/etc/httpd/conf/extra/php-fpm.conf
DirectoryIndex index.php index.html
<FilesMatch \.php$>
    SetHandler "proxy:unix:/run/php-fpm/php-fpm.sock|fcgi://localhost/"
</FilesMatch>

And include it at the bottom of /etc/httpd/conf/httpd.conf:

Include conf/extra/php-fpm.conf
Note: The pipe between sock and fcgi is not allowed to be surrounded by a space! localhost can be replaced by any string. More here

You can configure PHP-FPM in /etc/php/php-fpm.d/www.conf, but the default setup should work fine.

Start and enable php-fpm.service. Restart httpd.service.

Using apache2-mpm-worker and mod_fcgid

Install the mod_fcgid and php-cgi packages.

Create the needed directory and symlink it for the PHP wrapper:

# mkdir /srv/http/fcgid-bin
# ln -s /usr/bin/php-cgi /srv/http/fcgid-bin/php-fcgid-wrapper

Create /etc/httpd/conf/extra/php-fcgid.conf with the following content:

/etc/httpd/conf/extra/php-fcgid.conf
# Required modules: fcgid_module

<IfModule fcgid_module>
    AddHandler php-fcgid .php
    AddType application/x-httpd-php .php
    Action php-fcgid /fcgid-bin/php-fcgid-wrapper
    ScriptAlias /fcgid-bin/ /srv/http/fcgid-bin/
    SocketPath /var/run/httpd/fcgidsock
    SharememPath /var/run/httpd/fcgid_shm
        # If you don't allow bigger requests many applications may fail (such as WordPress login)
        FcgidMaxRequestLen 536870912
        # Path to php.ini – defaults to /etc/phpX/cgi
        DefaultInitEnv PHPRC=/etc/php/
        # Number of PHP childs that will be launched. Leave undefined to let PHP decide.
        #DefaultInitEnv PHP_FCGI_CHILDREN 3
        # Maximum requests before a process is stopped and a new one is launched
        #DefaultInitEnv PHP_FCGI_MAX_REQUESTS 5000
    <Location /fcgid-bin/>
        SetHandler fcgid-script
        Options +ExecCGI
    </Location>
</IfModule>

Edit /etc/httpd/conf/httpd.conf, enabling the actions module:

LoadModule actions_module modules/mod_actions.so

And add the following lines:

LoadModule fcgid_module modules/mod_fcgid.so
Include conf/extra/httpd-mpm.conf
Include conf/extra/php-fcgid.conf

Restart httpd.service.

Test if PHP works

To test whether PHP was correctly configured: create a file called test.php in your Apache DocumentRoot directory (e.g. /srv/http/ or ~/public_html) with the following contents:

<?php phpinfo(); ?>

To see if it works go to: http://localhost/test.php or http://localhost/~myname/test.php

HTTP2

To enable HTTP/2 support, uncomment the following line in httpd.conf:

LoadModule http2_module modules/mod_http2.so

And add the following line:

Protocols h2 http/1.1

For more information, see the mod_http2 documentation.

Troubleshooting

Apache Status and Logs

See the status of the Apache daemon with systemctl.

Apache logs can be found in /var/log/httpd/

Error: PID file /run/httpd/httpd.pid not readable (yet?) after start

Comment out the unique_id_module line in httpd.conf: #LoadModule unique_id_module modules/mod_unique_id.so

Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.

If when loading php7_module the httpd.service fails, and you get an error like this in the journal:

Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.  You need to recompile PHP.

you need to replace mpm_event_module with mpm_prefork_module:

/etc/httpd/conf/httpd.conf
LoadModule mpm_event_module modules/mod_mpm_event.so
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

and restart httpd.service.

AH00534: httpd: Configuration error: No MPM loaded.

You might encounter this error after a recent upgrade. This is only the result of a recent change in httpd.conf that you might not have reproduced in your local configuration. To fix it, uncomment the following line.

/etc/httpd/conf/httpd.conf
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

Also check the above if more errors occur afterwards.

AH00072: make_sock: could not bind to address

This can be caused by multiple things. Most common issue being that something is already listening on a given port, check via netstat that this is not happening:

# netstat -lnp | grep -e :80 -e :443

If you get any output, stop the given service that's taking up the port or kill the runaway process that is causing the port to be bound, and try again.

Another issue could be that Apache is not starting as root for some reason - try starting it manually and see if you still get the AH0072 error.

# httpd -k start

Finally, you can also have an error with your config and you are listening twice on the given port. Following is an example of a bad config that will trigger this issue:

Listen 0.0.0.0:80
Listen [::]:80

Changing the max_execution_time in php.ini has no effect

If you changed the max_execution_time in php.ini to a value greater than 30 (seconds), you may still get a 503 Service Unavailable response from Apache after 30 seconds. To solve this, add a ProxyTimeout directive to your http configuration right before the <FilesMatch \.php$> block:

/etc/httpd/conf/httpd.conf
ProxyTimeout 300

and restart httpd.service.

See also