Apache HTTP Server: Difference between revisions

From ArchWiki
(→‎Using php-fpm and mod_proxy_fcgi: add DirectoryIndex to php-fpm.conf, like there is in php7_module.conf from the php-apache package)
(update interlanguage links)
 
(88 intermediate revisions by 34 users not shown)
Line 1: Line 1:
[[Category:Web server]]
[[Category:Web server]]
[[cs:Apache HTTP Server]]
[[Category:Apache]]
[[de:LAMP Installation]]
[[de:LAMP Installation]]
[[el:Apache HTTP Server]]
[[es:Apache HTTP Server]]
[[es:Apache HTTP Server]]
[[fa:LAMP]]
[[fr:Lamp]]
[[it:Apache HTTP Server]]
[[ja:Apache HTTP Server]]
[[ja:Apache HTTP Server]]
[[ko:Apache HTTP Server]]
[[pt:Apache HTTP Server]]
[[pl:Apache HTTP Server]]
[[ru:Apache HTTP Server]]
[[sr:Apache HTTP Server]]
[[tr:LAMP]]
[[zh-hans:Apache HTTP Server]]
[[zh-hans:Apache HTTP Server]]
{{Related articles start}}
{{Related articles start}}
{{Related|PHP}}
{{Related|MySQL}}
{{Related|PhpMyAdmin}}
{{Related|Adminer}}
{{Related|XAMPP}}
{{Related|XAMPP}}
{{Related|mod_perl}}
{{Related|/mod_perl}}
{{Related|nginx}}
{{Related|/mod_fcgid}}
{{Related|/mod_gnutls}}
{{Related|/mod_wsgi}}
{{Related articles end}}
{{Related articles end}}
The [[Wikipedia:Apache HTTP Server|Apache HTTP Server]], or Apache for short, is a very popular web server, developed by the Apache Software Foundation.
The [[Wikipedia:Apache HTTP Server|Apache HTTP Server]], or Apache for short, is a very popular [[web server]], developed by the Apache Software Foundation.


Apache is often used together with a scripting language such as PHP and database such as MySQL. This combination is often referred to as a [[Wikipedia:LAMP (software bundle)|LAMP]] stack ('''L'''inux, '''A'''pache, '''M'''ySQL, '''P'''HP). This article describes how to set up Apache and how to optionally integrate it with [[PHP]] and [[MySQL]].
This article describes how to set up Apache and how to optionally integrate it with [[PHP]].


== Installation ==
== Installation ==
[[Install]] the {{Pkg|apache}} package.
[[Install]] the {{Pkg|apache}} package.


== Configuration ==
== Configuration ==
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 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.


Apache should now be running. Test by visiting http://localhost/ in a web browser. It should display a simple index page.
To run Apache, [[start]] {{ic|httpd.service}}. If everything is working correctly, visiting http://localhost/ should display a simple index page.


For optional further configuration, see the following sections.
For optional further configuration, see the following sections.
Line 42: Line 31:
=== Advanced options ===
=== 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.htm directive quick reference].
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:
These options in {{ic|/etc/httpd/conf/httpd.conf}} might be interesting for you:
Line 63: Line 52:


  AllowOverride None
  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].
: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 [https://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}}}}
{{Tip|If you have issues with your configuration you can have Apache check the configuration with: {{ic|apachectl configtest}}}}
Line 83: Line 72:
  Include conf/extra/httpd-userdir.conf
  Include conf/extra/httpd-userdir.conf


{{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]]).}}
{{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#Execution permissions for private files]]).|section=User Directories}}


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"):
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"):
Line 91: Line 80:
  $ chmod -R o+r ~/public_html
  $ chmod -R o+r ~/public_html


Restart {{ic|httpd.service}} to apply any changes. See also [[Umask#Set the mask value]].
[[Restart]] {{ic|httpd.service}} to apply any changes. See also [[Umask#Set the mask value]].
 
=== TLS ===
 
{{Warning|If you deploy [[Wikipedia:Transport Layer Security|TLS]], be sure to follow [https://weakdh.org/sysadmin.html weakdh.org's guide] to prevent vulnerabilities. For more information see [[Server-side TLS]].}}


=== TLS/SSL ===
Firstly [[obtain a certificate]]. If you own a public domain, you can use [[Transport Layer Security#ACME clients]].
{{Warning|If you plan on implementing SSL/TLS, know that some variations and implementations are [https://weakdh.org/#affected still] [[wikipedia:Transport_Layer_Security#Attacks_against_TLS.2FSSL|vulnerable to attack]]. For details on these current vulnerabilities within SSL/TLS and how to apply appropriate changes to the web server, visit http://disablessl3.com/ and https://weakdh.org/sysadmin.html}}
[[OpenSSL]] provides TLS/SSL support and is installed by default on Arch installations.


In {{ic|/etc/httpd/conf/httpd.conf}}, uncomment the following three lines:
In {{ic|/etc/httpd/conf/httpd.conf}}, uncomment the following three lines:
Line 102: Line 93:
  Include conf/extra/httpd-ssl.conf
  Include conf/extra/httpd-ssl.conf


For TLS/SSL, 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]].
If using [[Certbot]] ({{ic|certbot --apache}}), the following line needs to be uncommented as well:
LoadModule rewrite_module modules/mod_rewrite.so


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}}.
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}}.


Finally, restart {{ic|httpd.service}} to apply any changes.
Finally, [[restart]] {{ic|httpd.service}} to apply any changes.
 
{{Tip|Mozilla has a useful [https://wiki.mozilla.org/Security/Server_Side_TLS SSL/TLS article] which includes [https://wiki.mozilla.org/Security/Server_Side_TLS#Apache Apache specific] configuration guidelines as well as an [https://mozilla.github.io/server-side-tls/ssl-config-generator/ automated tool] to help create a more secure configuration.}}


==== Create a key and (self-signed) certificate ====
{{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.}}
 
Create a private key and self-signed certificate. This is adequate for most installations that do not require a [[wikipedia:Certificate signing request|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 [[wikipedia:Certificate signing request|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 [https://www.openssl.org/docs/apps/openssl.html man page] or peruse openssl's [https://www.openssl.org/docs/ extensive documentation].}}


=== Virtual hosts ===
=== Virtual hosts ===
Line 140: Line 112:
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.
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.


To test the virtual hosts on you local machine, add the virtual names to your {{ic|/etc/hosts}} file:
To test the virtual hosts on your local machine, add the virtual names to your {{ic|/etc/hosts}} file:
  127.0.0.1 domainname1.dom  
  127.0.0.1 domainname1.dom  
  127.0.0.1 domainname2.dom
  127.0.0.1 domainname2.dom


Restart {{ic|httpd.service}} to apply any changes.
[[Restart]] {{ic|httpd.service}} to apply any changes.


==== Managing many virtual hosts ====
==== Managing many virtual hosts ====
{{Note|Having your virtual servers separated into individual files is mandatory if you plan on using {{pkg|certbot}} to deploy TLS certificates. Having all your virtual servers listed in a single file (as it is by default) will result in certbot failing to deploy the certificates correctly}}


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}}.
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}}.
Line 200: Line 174:


=== PHP ===
=== 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]]).
First [[PHP#Installation|install PHP]], then follow one of the next three subsections below.  Finally, test the installation as described in the final subsection.


==== Using libphp ====
==== Using libphp ====
[[Install]] the {{Pkg|php-apache}} package.
 
This method is probably the easiest, but is also the least scalable: it is suitable for a light request load. It also requires you to change the mpm module, which may cause problems with other extensions (e.g. it is not compatible with [[#HTTP/2]]).
 
[[Install]] {{Pkg|php-apache}}.


In {{ic|/etc/httpd/conf/httpd.conf}}, comment the line:
In {{ic|/etc/httpd/conf/httpd.conf}}, comment the line:
  #LoadModule mpm_event_module modules/mod_mpm_event.so
  #LoadModule mpm_event_module modules/mod_mpm_event.so
and uncomment the line:
and uncomment the line:
  LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
  LoadModule mpm_prefork_module modules/mod_mpm_prefork.so


{{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}})
{{Note|1=The above is required, because {{ic|libphp.so}} included with the package does not work with {{ic|mod_mpm_event}}, but will only work {{ic|mod_mpm_prefork}} instead. ({{Bug|39218}})


Otherwise you will get the following error:
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.
 
{{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
AH00013: Pre-configuration failed
httpd.service: control process exited, code=exited status=1}}
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).
As an alternative, you can use {{ic|mod_proxy_fcgi}} (see [[#Using php-fpm and mod_proxy_fcgi]] below).
Line 223: Line 205:


To enable PHP, add these lines to {{ic|/etc/httpd/conf/httpd.conf}}:
To enable PHP, add these lines to {{ic|/etc/httpd/conf/httpd.conf}}:
*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


Restart {{ic|httpd.service}} using [[systemd#Using units|systemd]].
* Place this at the end of the {{ic|LoadModule}} list:
LoadModule php_module modules/libphp.so
AddHandler php-script .php
* Place this at the end of the {{ic|Include}} list:
Include conf/extra/php_module.conf


==== Using php-fpm and mod_proxy_fcgi ====
then [[restart]] {{ic|httpd.service}}.


{{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.
==== Using apache2-mpm-worker and mod_fcgid ====
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}}}}


[[Install]] the {{pkg|php-fpm}} package.
This method provides improved performance and memory usage when serving multiple requests.


Enable proxy modules:
[[Install]] {{AUR|mod_fcgid}} and {{Pkg|php-cgi}}.
{{hc|/etc/httpd/conf/httpd.conf|<nowiki>
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
</nowiki>}}
 
Create {{ic|/etc/httpd/conf/extra/php-fpm.conf}} with the following content:
{{hc|/etc/httpd/conf/extra/php-fpm.conf|<nowiki>
DirectoryIndex index.php index.html
<FilesMatch \.php$>
    SetHandler "proxy:unix:/run/php-fpm/php-fpm.sock|fcgi://localhost/"
</FilesMatch>
</nowiki>}}
 
And include it at the bottom of {{ic|/etc/httpd/conf/httpd.conf}}:
Include conf/extra/php-fpm.conf
 
{{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]}}
 
You can configure PHP-FPM in {{ic|/etc/php/php-fpm.d/www.conf}}, but the default setup should work fine.
 
[[Restart]] {{ic|httpd.service}} and {{ic|php-fpm.service}}.
 
==== Using apache2-mpm-worker and mod_fcgid ====
[[Install]] the {{pkg|mod_fcgid}} and {{Pkg|php-cgi}} packages.


Create the needed directory and symlink it for the PHP wrapper:
Create the needed directory and symlink it for the PHP wrapper:
Line 294: Line 250:
</nowiki>}}
</nowiki>}}


Edit {{ic|/etc/httpd/conf/httpd.conf}}, enabling the actions module:
Edit {{ic|/etc/httpd/conf/httpd.conf}}:
  LoadModule actions_module modules/mod_actions.so
* Uncomment the loading of the actions module: {{bc|LoadModule actions_module modules/mod_actions.so}}
* Load the FCGID module ''after'' the loading of the unixd module (on which it is dependent) - you may wish to place this within the {{ic|<IfModule unixd_module>}} block: {{bc|LoadModule fcgid_module modules/mod_fcgid.so}}
* Ensure that the inclusion of the MPM configuration is uncommented (it is uncommented in the default installed version of this file): {{bc|Include conf/extra/httpd-mpm.conf}}
* Add an inclusion of your new FCGID configuration: {{bc|Include conf/extra/php-fcgid.conf}}
 
[[Restart]] {{ic|httpd.service}}.
 
==== Using php-fpm and mod_proxy_fcgi ====
 
This method provides "an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites" [https://www.php.net/manual/en/install.fpm.php].  
 
{{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 libphp, mod_fastcgi and mod_fcgid.
If you still want to try ProxyPass, experiment with a line like this: {{bc|ProxyPassMatch ^/(.*\.php(/.*)?)$ unix:/run/php-fpm/php-fpm.sock{{!}}fcgi://localhost/srv/http/$1}}}}
 
[[Install]] {{pkg|php-fpm}}.
 
Enable proxy modules:
{{hc|/etc/httpd/conf/httpd.conf|<nowiki>
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
</nowiki>}}
 
Create {{ic|/etc/httpd/conf/extra/php-fpm.conf}} with the following content:
{{bc|<nowiki>
DirectoryIndex index.php index.html
<FilesMatch \.php$>
    SetHandler "proxy:unix:/run/php-fpm/php-fpm.sock|fcgi://localhost/"
</FilesMatch>
</nowiki>}}


And add the following lines:
And include it at the bottom of {{ic|/etc/httpd/conf/httpd.conf}}:
LoadModule fcgid_module modules/mod_fcgid.so
  Include conf/extra/php-fpm.conf
Include conf/extra/httpd-mpm.conf
  Include conf/extra/php-fcgid.conf


[[Restart]] {{ic|httpd.service}}.
{{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]}}
 
You can configure PHP-FPM in {{ic|/etc/php/php-fpm.d/www.conf}}, but the default setup should work fine.
 
[[Start]] and [[enable]] {{ic|php-fpm.service}}, then [[restart]] {{ic|httpd.service}}.
 
==== Test whether PHP works ====


==== 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|~<username>/public_html/}}) with the following contents:
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(); ?>
  <?php phpinfo(); ?>
To see if it works go to: http://localhost/test.php or http://localhost/~myname/test.php
Then go to http://localhost/test.php or <nowiki>http://localhost/~<username>/test.php</nowiki> as appropriate.


=== HTTP2 ===
=== HTTP/2 ===


To enable HTTP/2 support, uncomment the following line in {{ic|httpd.conf}}:
{{Note|
* While Apache supports unencrypted HTTP/2 over TCP ({{ic|h2c}}), common browsers [https://stackoverflow.com/a/46789195 do not]. Thus for use with the latter, [[#TLS]] must be enabled first.
* If supporting clients do not use HTTP/2 instead of HTTP/1.1 and Mozilla's configuration generator (which already includes the {{ic|Protocols}} line below) was used to setup [[#TLS]], try {{ic|Include}}ing {{ic|httpd-ssl.conf}} ''after'' the latter's output.
* Ways to test include {{ic|curl -sI <nowiki>https://your.website</nowiki>}} or use [https://github.com/pd4d10/http-indicator http indicator] (supports both chromium based browsers and firefox based browsers).}}
 
To enable HTTP/2 over TLS support, uncomment the following line in {{ic|httpd.conf}}:
  LoadModule http2_module modules/mod_http2.so
  LoadModule http2_module modules/mod_http2.so


Line 318: Line 309:
  Protocols h2 http/1.1
  Protocols h2 http/1.1


For more information, see the [https://httpd.apache.org/docs/2.4/mod/mod_http2.html mod_http2] documentation.
To debug, you can set only the module rather than the entire server to {{ic|debug}} or {{ic|info}}:
<IfModule http2_module>
    LogLevel http2:info
</IfModule>
 
For more information – including extra HTTP/2 feature settings – see the [https://httpd.apache.org/docs/2.4/mod/mod_http2.html mod_http2] documentation.
 
{{Warning|The {{ic|http2_module}} is incompatible with the {{ic|mpm_prefork_module}} that old configurations widely use to setup PHP. Consider using [[#Using php-fpm and mod_proxy_fcgi|php-fpm]] instead.}}


== Troubleshooting ==
== Troubleshooting ==
Line 331: Line 329:


Comment out the {{ic|unique_id_module}} line in {{ic|httpd.conf}}: {{ic|#LoadModule unique_id_module modules/mod_unique_id.so}}
Comment out the {{ic|unique_id_module}} line in {{ic|httpd.conf}}: {{ic|#LoadModule unique_id_module modules/mod_unique_id.so}}
=== /run/httpd not being created at boot ===
If {{ic|systemd-tmpfiles --create}} as the root user complains about "unsafe path transition", check ownership of your root directory.
ls -la /
chown root:root /


=== Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe. ===
=== 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:
If when loading {{ic|php_module}} the {{ic|httpd.service}} fails, you may 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.
  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}}:
This is because PHP includes support for a module that is not threadsafe, and you are trying to use a threaded MPM. One solution to fix this is to use a non-threaded MPM. Try replacing {{ic|mpm_event_module}} with {{ic|mpm_prefork_module}}:


{{hc|/etc/httpd/conf/httpd.conf|
{{hc|/etc/httpd/conf/httpd.conf|
Line 345: Line 350:
}}
}}


and restart {{ic|httpd.service}}.
and [[restart]] {{ic|httpd.service}}.
 
{{Warning|Some other modules, like the {{ic|http2_module}}, will disable themselves when {{ic|mpm_prefork}} is active.}}


=== AH00534: httpd: Configuration error: No MPM loaded. ===
=== 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.
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:
To fix it, uncomment the following line.


{{hc|/etc/httpd/conf/httpd.conf|
{{hc|/etc/httpd/conf/httpd.conf|
Line 356: Line 362:
}}
}}


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.
and [[restart]] {{ic|httpd.service}}.


=== AH00072: make_sock: could not bind to address ===
=== 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:
This can be caused by multiple things. Most common issue being that something is already listening on a given port, check via [[ss]] that this is not happening:


  # netstat -lnp | grep -e :80 -e :443
  # ss -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.
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.
Line 370: Line 376:
  # httpd -k start
  # 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:
Finally, you can also have an error with your configuration and you are listening twice on the given port. Following is an example of a bad configuration that will trigger this issue:


  Listen 0.0.0.0:80
  Listen 0.0.0.0:80
  Listen [::]:80
  Listen [::]:80
=== AH01071: Got error 'Primary script unknown' ===
This can be caused by {{ic|1=ProtectHome=true}} in the php-fpm systemd unit file if you are serving files in {{ic|/home}} such as in a virtual host environment. You can disable this feature by [[systemd#Drop-in files|editing the php-fpm unit file]] and [[restart]]ing {{ic|php-fpm.service}}. Alternatively, move your document root.


=== Changing the max_execution_time in php.ini has no effect ===
=== Changing the max_execution_time in php.ini has no effect ===
Line 383: Line 393:
}}
}}


and restart {{ic|httpd.service}}.
and [[restart]] {{ic|httpd.service}}.
 
=== PHP-FPM: errors are not being logged separately per virtual host ===
 
If you have multiple virtual hosts, it may be desirable to have each of them output their error logs to separate files (using the ErrorLog Apache directive). If this is not working for you, confirm that PHP-FPM is configured to log errors to syslog:
 
{{hc|/etc/php/php-fpm.conf|
output=error_log = syslog
}}
 
It is also possible that the pool configuration is overriding it. Ensure the following line is commented out:
 
{{hc|/etc/php/php-fpm.d/www.conf|
output=;php_admin_value[error_log] = /var/log/fpm-php.www.log
}}


== See also ==
== See also ==

Latest revision as of 17:58, 1 February 2024

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 run Apache, start httpd.service. If everything is working correctly, visiting http://localhost/ 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

The factual accuracy of this article or section is disputed.

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

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.

Firstly obtain a certificate. If you own a public domain, you can use Transport Layer Security#ACME clients.

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 (certbot --apache), the following line needs to be uncommented as well:

LoadModule rewrite_module modules/mod_rewrite.so

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.

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

Note: Having your virtual servers separated into individual files is mandatory if you plan on using certbot to deploy TLS certificates. Having all your virtual servers listed in a single file (as it is by default) will result in certbot failing to deploy the certificates correctly

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, then follow one of the next three subsections below. Finally, test the installation as described in the final subsection.

Using libphp

This method is probably the easiest, but is also the least scalable: it is suitable for a light request load. It also requires you to change the mpm module, which may cause problems with other extensions (e.g. it is not compatible with #HTTP/2).

Install php-apache.

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 libphp.so included with the package 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 php_module modules/libphp.so
AddHandler php-script .php
  • Place this at the end of the Include list:
Include conf/extra/php_module.conf

then restart httpd.service.

Using apache2-mpm-worker and mod_fcgid

This method provides improved performance and memory usage when serving multiple requests.

Install mod_fcgidAUR and php-cgi.

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:

  • Uncomment the loading of the actions module:
    LoadModule actions_module modules/mod_actions.so
  • Load the FCGID module after the loading of the unixd module (on which it is dependent) - you may wish to place this within the <IfModule unixd_module> block:
    LoadModule fcgid_module modules/mod_fcgid.so
  • Ensure that the inclusion of the MPM configuration is uncommented (it is uncommented in the default installed version of this file):
    Include conf/extra/httpd-mpm.conf
  • Add an inclusion of your new FCGID configuration:
    Include conf/extra/php-fcgid.conf

Restart httpd.service.

Using php-fpm and mod_proxy_fcgi

This method provides "an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites" [1].

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 libphp, 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 php-fpm.

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:

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, then restart httpd.service.

Test whether 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 ~<username>/public_html/) with the following contents:

<?php phpinfo(); ?>

Then go to http://localhost/test.php or http://localhost/~<username>/test.php as appropriate.

HTTP/2

Note:
  • While Apache supports unencrypted HTTP/2 over TCP (h2c), common browsers do not. Thus for use with the latter, #TLS must be enabled first.
  • If supporting clients do not use HTTP/2 instead of HTTP/1.1 and Mozilla's configuration generator (which already includes the Protocols line below) was used to setup #TLS, try Includeing httpd-ssl.conf after the latter's output.
  • Ways to test include curl -sI https://your.website or use http indicator (supports both chromium based browsers and firefox based browsers).

To enable HTTP/2 over TLS 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

To debug, you can set only the module rather than the entire server to debug or info:

<IfModule http2_module>
    LogLevel http2:info
</IfModule>

For more information – including extra HTTP/2 feature settings – see the mod_http2 documentation.

Warning: The http2_module is incompatible with the mpm_prefork_module that old configurations widely use to setup PHP. Consider using php-fpm instead.

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

/run/httpd not being created at boot

If systemd-tmpfiles --create as the root user complains about "unsafe path transition", check ownership of your root directory.

ls -la /
chown root:root /

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

If when loading php_module the httpd.service fails, you may 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.

This is because PHP includes support for a module that is not threadsafe, and you are trying to use a threaded MPM. One solution to fix this is to use a non-threaded MPM. Try replacing 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.

Warning: Some other modules, like the http2_module, will disable themselves when mpm_prefork is active.

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

and restart httpd.service.

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 ss that this is not happening:

# ss -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 configuration and you are listening twice on the given port. Following is an example of a bad configuration that will trigger this issue:

Listen 0.0.0.0:80
Listen [::]:80

AH01071: Got error 'Primary script unknown'

This can be caused by ProtectHome=true in the php-fpm systemd unit file if you are serving files in /home such as in a virtual host environment. You can disable this feature by editing the php-fpm unit file and restarting php-fpm.service. Alternatively, move your document root.

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.

PHP-FPM: errors are not being logged separately per virtual host

If you have multiple virtual hosts, it may be desirable to have each of them output their error logs to separate files (using the ErrorLog Apache directive). If this is not working for you, confirm that PHP-FPM is configured to log errors to syslog:

/etc/php/php-fpm.conf
error_log = syslog

It is also possible that the pool configuration is overriding it. Ensure the following line is commented out:

/etc/php/php-fpm.d/www.conf
;php_admin_value[error_log] = /var/log/fpm-php.www.log

See also