Apache cheat sheet

This cheat sheet brings together the common settings in Apache configuration files, from testing and reloading the configuration, through VirtualHost, HTTPS, and redirects, to PHP-FPM, reverse proxy, caching, and security. You can search for a setting, filter by topic, and copy it with one click.

Commands and configuration testing

  • apachectl configtest

    Checks the syntax of the configuration files and returns Syntax OK, or the file and line of the error. It's the same as apachectl -t. On Debian and Ubuntu, the command is also available as apache2ctl.

  • apachectl -S

    Shows the configured websites as Apache read them: each address and port, the default website, and the ServerName and ServerAlias names, including the file and line of each website. Useful when a request reaches the wrong website.

  • apachectl -M

    Lists all loaded modules, static and dynamic. This lets you make sure that a module such as rewrite_module, ssl_module, or proxy_module is actually active.

    Example: apachectl -M | grep -i rewrite

  • apachectl -V

    Shows the version and the build parameters, including the active MPM and the main configuration file. The apachectl -v command shows the version only.

  • apachectl graceful

    A graceful reload: open connections aren't dropped, and requests in progress finish as usual. The command checks the configuration before reloading, and if it has an error, the server isn't reloaded.

  • apachectl configtest && systemctl reload apache2

    Tests the configuration and reloads it only if the test passes. On Debian and Ubuntu, the service is called apache2, and on RHEL-family distributions, such as AlmaLinux and Rocky Linux, it's called httpd.

    Example: apachectl configtest && systemctl reload httpd

  • systemctl restart apache2

    A full restart that drops open connections. It's needed, for example, after switching the MPM or loading a new module. For regular changes, a reload is enough.

  • systemctl status apache2

    Shows whether the service is running and the last lines of its log. When the service doesn't start, journalctl -u apache2 shows the full error message.

    Example: journalctl -u httpd -n 50 --no-pager

File layout by distribution

  • /etc/apache2/apache2.conf

    The main configuration file on Debian and Ubuntu. Ports are set in ports.conf, and websites, modules, and configuration snippets are kept in the sites-, mods-, and conf- directories, each as an available and enabled pair. It's best not to edit the main file and to add settings in the conf-available directory instead.

  • a2ensite example.com.conf

    Enables a website from the sites-available directory by creating a link in sites-enabled. The file name must end in .conf, otherwise the configuration doesn't load it. After enabling the website, reload Apache.

    Example: a2ensite example.com.conf && systemctl reload apache2

  • a2dissite 000-default.conf

    Disables a website and removes its link from sites-enabled, without deleting the file. In the example, the default website that comes with the installation is disabled.

  • a2enmod rewrite headers ssl

    Enables modules on Debian and Ubuntu. You can enable several modules in one command. After enabling a module, restart Apache.

    Example: a2enmod rewrite && systemctl restart apache2

  • a2dismod status

    Disables a module that isn't in use. Every loaded module uses memory in every process, so keep only the modules you need enabled.

  • a2enconf security

    Enables a configuration snippet from conf-available, for example a file with general security settings. Here too, the file name must end in .conf. The a2disconf command disables it.

  • /etc/httpd/conf/httpd.conf

    The main configuration file on RHEL-family distributions. Website settings are kept in .conf files in the /etc/httpd/conf.d directory, and modules are loaded from /etc/httpd/conf.modules.d. These distributions don't have the a2ensite commands, so you disable a website by changing the file extension or moving the file.

  • /var/www/html

    The default directory for website files in both distribution families. Logs are usually kept in /var/log/apache2 on Debian and Ubuntu, and in /var/log/httpd on RHEL-family distributions.

VirtualHost

  • <VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public <Directory /var/www/example.com/public> Require all granted AllowOverride None Options -Indexes +FollowSymLinks </Directory> ErrorLog /var/log/apache2/example.com-error.log CustomLog /var/log/apache2/example.com-access.log combined </VirtualHost>

    A basic name-based website. Apache picks the website by the Host header of the request, and when nothing matches, the first website configured for that address and port is used. On RHEL-family distributions, the logs are kept in /var/log/httpd.

  • ServerName example.com

    The main name of the website. It's used to pick the website and to build URLs in redirects the server creates. A ServerName at the server level also prevents the AH00558 warning at startup.

  • ServerAlias www.example.com *.example.com

    Additional names for the same website, including wildcards. The first match found wins, with no priority for the main name over the aliases.

  • DocumentRoot /var/www/example.com/public

    The website's file directory. For a directory outside /var/www, add a Directory block with Require all granted, otherwise visitors get a 403 error.

  • Require all granted

    Allows access to the directory. The opposite setting is Require all denied. In the default settings, access to the whole file system is blocked and is opened only for directories that are explicitly configured.

  • AllowOverride None

    The server doesn't look for .htaccess files, and this is the default. With AllowOverride All, the server checks on every request whether there's a .htaccess file in every directory along the path, so on a server where you have access to the configuration files, it's better to write the rules in the VirtualHost.

    Example: AllowOverride All

  • Options -Indexes +FollowSymLinks

    Turns off the automatic file listing in a directory without an index file, and allows following symbolic links. Don't mix options with + or - and options without a sign on the same line, or the configuration test fails.

  • DirectoryIndex index.php index.html

    The files the server looks for, in order, when the request is for a directory.

  • FallbackResource /index.php

    Passes every request for a file or directory that doesn't exist to index.php. This is the simple way to get friendly URLs in systems such as WordPress and Laravel, without mod_rewrite rules.

HTTPS and HTTP/2

  • <VirtualHost *:443> ServerName example.com DocumentRoot /var/www/example.com/public SSLEngine on SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem Protocols h2 http/1.1 </VirtualHost>

    A website over HTTPS. It requires mod_ssl, which you enable on Debian and Ubuntu with a2enmod ssl. The paths in the example are those of a Let's Encrypt certificate issued with Certbot.

  • SSLCertificateFile /etc/ssl/example.com/fullchain.pem

    The certificate file. In current versions, the file contains the website's certificate followed by the intermediate certificates, in order. The SSLCertificateChainFile directive is obsolete and no longer needed.

  • SSLCertificateKeyFile /etc/ssl/example.com/privkey.pem

    The certificate's private key. Restrict the file permissions so that only root can read it.

    Example: chmod 600 /etc/ssl/example.com/privkey.pem

  • <VirtualHost *:80> ServerName example.com ServerAlias www.example.com Redirect permanent "/" "https://example.com/" </VirtualHost>

    A permanent redirect from HTTP to HTTPS. This is the method the Apache documentation recommends: Redirect keeps the rest of the path, so /about is redirected to https://example.com/about, with no need for mod_rewrite.

  • Header always set Strict-Transport-Security "max-age=31536000"

    The HSTS header, which tells the browser to access the website only over HTTPS. It requires mod_headers and goes only in the VirtualHost for port 443. Add it only when the whole website works over HTTPS, because the browser remembers it for the entire period you set. Adding includeSubDomains applies it to all subdomains too.

  • Protocols h2 http/1.1

    Enables HTTP/2 on the website. It requires mod_http2, which you enable on Debian and Ubuntu with a2enmod http2. Browsers use HTTP/2 only over HTTPS. With MPM prefork, only one request at a time is possible on each connection, so MPM event is recommended.

  • SSLProtocol -all +TLSv1.2 +TLSv1.3

    Allows only the modern TLS versions. TLSv1.3 requires a recent enough OpenSSL library.

Redirects and mod_rewrite

  • Redirect permanent "/old-page" "https://example.com/new-page"

    A permanent 301 redirect from one path to another, with mod_alias. The redirect also applies to everything under the path. For simple redirects, the Apache documentation recommends Redirect over mod_rewrite.

  • RedirectMatch 301 "^/blog/(.*)$" "https://example.com/articles/$1"

    A redirect based on a regular expression, when you need to carry part of the path over to the new URL.

  • RewriteEngine On

    Turns on mod_rewrite in a VirtualHost or a directory. Without it, RewriteRule rules don't work. On Debian and Ubuntu, enable the module with a2enmod rewrite.

  • RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    A redirect to HTTPS with mod_rewrite. Suited to cases where you have no access to the VirtualHost for port 80, for example in a .htaccess file. When you do have access, Redirect in the VirtualHost for port 80 is simpler.

  • RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

    A redirect from the address with www to the address without www. The %1 value is the part captured in the RewriteCond condition, meaning the domain name without www.

  • RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    A redirect from the address without www to the address with www. Choose one preferred address and redirect everything else to it.

  • RewriteRule ^/?product/([0-9]+)$ /product.php?id=$1 [L,QSA]

    An internal rewrite of a friendly URL to a file, without changing the URL in the browser. The QSA flag appends the original query string; without it, the query string is dropped when the new URL contains a question mark.

  • [L] [R=301] [NC] [QSA] [END]

    The common flags: L stops processing rules in the current round, R redirects (302 by default, and R=301 for a permanent redirect), NC ignores case, QSA keeps the query string, and END stops processing completely, even in a .htaccess file.

  • RewriteCond %{HTTP_HOST} ^example\.net$ [NC,OR] RewriteCond %{HTTP_HOST} ^example\.org$ [NC]

    By default, all conditions in a sequence must be met. With the OR flag, it's enough for this condition or the next one to be met.

Reverse proxy and WebSocket

  • a2enmod proxy proxy_http headers

    The modules required for a reverse proxy on Debian and Ubuntu. On RHEL-family distributions, they're usually already loaded after installation.

  • <VirtualHost *:443> ServerName app.example.com # SSLEngine and certificate lines as in the HTTPS section ProxyPreserveHost On ProxyPass "/" "http://127.0.0.1:3000/" ProxyPassReverse "/" "http://127.0.0.1:3000/" RequestHeader set X-Forwarded-Proto "https" </VirtualHost>

    Passes requests to an application listening on a local port, for example Node.js. ProxyPassReverse fixes the URLs in redirects the application sends, and X-Forwarded-Proto tells the application that the visitor came over HTTPS.

  • ProxyPreserveHost On

    Passes the original domain name in the Host header to the application, instead of the address in ProxyPass. The default is Off, and applications that build URLs from the domain need it turned on. Apache adds the X-Forwarded-For header with the visitor's address on its own.

  • ProxyPass "/ws/" "http://127.0.0.1:3000/ws/" upgrade=websocket

    Passes WebSocket connections to the application. Write this line before the general ProxyPass for "/", because the first match wins. Older versions of Apache need mod_proxy_wstunnel for this.

  • ProxyPass "/" "http://127.0.0.1:3000/" timeout=120

    How long to wait, in seconds, for a response from the application. The ProxyTimeout directive sets a general value for every proxy, and by default it equals the Timeout value. When the time runs out, the visitor usually gets a 504 error.

    Example: ProxyTimeout 120

  • ProxyPass "/static/" "!"

    Excludes a path from the proxy, so Apache serves it directly from disk. The exclusion line goes before the general line.

  • ProxyRequests Off

    Turns off forward proxy mode, in which the server passes users' requests on to outside websites, and this is the default. A reverse proxy doesn't need this mode, and turning it on without access restrictions makes the server an open proxy for the whole world.

PHP-FPM and MPM

  • <FilesMatch "\.php$"> SetHandler "proxy:unix:/run/php/php-fpm.sock|fcgi://localhost/" </FilesMatch>

    Passes PHP files to PHP-FPM through mod_proxy_fcgi. The socket path differs between distributions: on Debian and Ubuntu, the file name in /run/php includes the PHP version, and on RHEL-family distributions, the common path is /run/php-fpm/www.sock. The listen setting in the PHP-FPM pool file shows the exact path.

  • SetHandler "proxy:fcgi://127.0.0.1:9000"

    Connects to PHP-FPM listening on a TCP port instead of a socket, for example when PHP-FPM runs in a separate container.

  • a2enmod proxy_fcgi setenvif

    The modules required for PHP-FPM on Debian and Ubuntu. The PHP-FPM package usually adds a file in conf-available, which you enable with a2enconf.

  • a2query -M

    Shows the active MPM on Debian and Ubuntu. On any distribution, you can also see it in the output of apachectl -V. With MPM event, one process handles many requests using threads, and with prefork, each request takes up a whole process.

  • a2dismod mpm_prefork && a2enmod mpm_event

    Switches from prefork to event on Debian and Ubuntu. Apache's built-in PHP module (mod_php) usually requires prefork, so first disable it with a2dismod and move to PHP-FPM. When you're done, run systemctl restart apache2. This is a major change: make it during low-traffic hours and check the website right afterward.

  • /etc/httpd/conf.modules.d/00-mpm.conf

    On RHEL-family distributions, you choose the MPM in this file: only one LoadModule line is active, and the default is event.

  • <IfModule mpm_event_module> ServerLimit 16 ThreadsPerChild 25 MaxRequestWorkers 400 MaxConnectionsPerChild 0 </IfModule>

    The main MPM event settings, with their default values. MaxRequestWorkers is the maximum number of requests handled at the same time, and it should be a multiple of ThreadsPerChild and no more than ServerLimit times ThreadsPerChild. Increase it carefully and according to the free memory, because a value that's too high can exhaust the server's memory.

Caching, compression, and connections

  • AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json

    gzip compression for text files with mod_deflate. There's no need to compress images, video, and files that are already compressed.

  • AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/css text/javascript application/javascript application/json

    Brotli compression with mod_brotli. The compressed response is sent only to browsers that state in the request that they support it.

  • ExpiresActive On ExpiresByType image/webp "access plus 1 month" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month"

    Browser caching with mod_expires. The module adds the Expires header and also max-age in the Cache-Control header.

  • <FilesMatch "\.(css|js|woff2)$"> Header set Cache-Control "public, max-age=31536000, immutable" </FilesMatch>

    Caching for one year for static files with mod_headers, as an alternative to mod_expires for the same file types. Suited to files whose name changes with every update, for example with a version number in the file name, otherwise visitors keep seeing the old version.

  • KeepAlive On KeepAliveTimeout 5 MaxKeepAliveRequests 100

    Persistent connections, which let the browser send several requests over the same connection. These are the default values. A high KeepAliveTimeout value can slow down a busy server.

Security and limits

  • ServerTokens Prod ServerSignature Off

    Hides the version and the operating system: the Server header shows only Apache, and error pages don't show a signature line. ServerTokens applies to the whole server and can't be set for each website separately.

  • <FilesMatch "^\."> Require all denied </FilesMatch>

    Blocks access to hidden files, such as .env and .htaccess. The default settings already block files that start with .ht.

  • RedirectMatch 404 "/\.git"

    Returns 404 for any request to a .git directory that was uploaded by mistake with the website files.

  • <Location "/admin"> Require ip 203.0.113.10 </Location>

    Limits a path to specific IP addresses. You can list several addresses and ranges on one line.

    Example: Require ip 203.0.113.0/24 198.51.100.7

  • <Location "/admin"> AuthType Basic AuthName "Restricted" AuthUserFile /etc/apache2/.htpasswd Require valid-user </Location>

    Password protection for a path. Use it only over HTTPS, because the password is sent with every request.

  • htpasswd -c /etc/apache2/.htpasswd admin

    Creates a password file and a first user. Note: the -c flag creates a new file and overwrites an existing one, so add more users without -c.

    Example: htpasswd /etc/apache2/.htpasswd editor

  • LimitRequestBody 104857600

    The maximum request size in bytes, here 100 MB. In recent versions, the default is 1 GB, and a larger request is blocked with a 413 error. On PHP websites, the upload size is also set by upload_max_filesize and post_max_size.

  • Header always set X-Content-Type-Options "nosniff" Header always set X-Frame-Options "SAMEORIGIN" Header always set Referrer-Policy "strict-origin-when-cross-origin"

    Common security headers with mod_headers. The always keyword adds the header to error pages and redirects too, not only to successful responses.

The visitor's IP behind a proxy and Cloudflare

  • RemoteIPHeader X-Forwarded-For RemoteIPTrustedProxy 192.0.2.10

    Restores the visitor's real IP address when Apache is behind a proxy or a load balancer, with mod_remoteip. Always list the trusted proxy addresses, otherwise any visitor can fake their address.

  • RemoteIPHeader CF-Connecting-IP RemoteIPTrustedProxy 192.0.2.0/24

    A website behind Cloudflare: Cloudflare sends the visitor's address in the CF-Connecting-IP header. Instead of the range in the example, list all the address ranges Cloudflare publishes, and update them from time to time.

  • RemoteIPTrustedProxyList conf/trusted-proxies.lst

    Reads the list of trusted addresses from a file, one address or range per line. Useful when the list is long, such as the Cloudflare ranges.

  • LogFormat "%a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

    In the access log, use %a instead of %h, so the visitor's real address is logged and not the proxy's address.

Logs and common errors

  • ErrorLog /var/log/apache2/example.com-error.log CustomLog /var/log/apache2/example.com-access.log combined

    A separate error log and access log for each website. A separate log makes it easier to check the traffic and problems of a specific website.

  • LogLevel warn ssl:info

    The general logging level, with a different level for a specific module. The default is warn.

  • LogLevel alert rewrite:trace3

    Detailed logging of every step in processing mod_rewrite rules, to find a rule that doesn't work. This logging fills the log quickly, so restore the previous setting as soon as you finish testing.

  • tail -f /var/log/apache2/error.log

    Follows the error log in real time while you try to reproduce the problem in the browser. On RHEL-family distributions, the log is /var/log/httpd/error_log.

    Example: tail -f /var/log/httpd/error_log

  • AH00558: Could not reliably determine the server's fully qualified domain name

    A startup warning: no ServerName is set at the server level. Apache keeps running; add a ServerName with the server's name in the main configuration file or in a general configuration snippet.

  • AH01630: client denied by server configuration

    The visitor got a 403 error because of the access settings. Usually Require all granted is missing from the Directory block of the website directory, or the path is explicitly blocked.

  • AH00072: make_sock: could not bind to address [::]:80

    Apache doesn't start because the port is in use, usually by another web server or a duplicate Listen directive. The command in the example shows which process is listening on the port.

    Example: ss -ltnp | grep ':80 '

  • Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

    The directive belongs to a module that isn't loaded, here mod_rewrite. Enable the module, on Debian and Ubuntu with a2enmod rewrite, and restart Apache. The same error with Header or ProxyPass points to mod_headers or mod_proxy.

In Apache, settings go in the server's configuration files, and each website has its own VirtualHost block. When the AllowOverride setting allows it, the server also reads .htaccess files in the website directories, but on a server where you have access to the configuration files, it's better to write the rules in the VirtualHost. The equivalent .htaccess rules are on the .htaccess cheat sheet, the equivalent Nginx settings are on the Nginx cheat sheet, and the differences between web servers are explained on the web servers page. The domain names, paths, and IP addresses on this page are examples, so replace them with your real values.

Before any change, save a copy of the file, and after the change, run apachectl configtest and only then reload the configuration. Every directive belongs to a specific module, and if the module isn't loaded, the configuration test fails. The apachectl -M command lists the loaded modules.

To check the headers your website sends after the change, use the HTTP header analyzer, and to check the redirect chain of a URL, use the redirect checker.

Did you know?

On a Linux VPS, you connect over SSH with full root access and install the web server that suits your website. This way, you can edit every Apache configuration file, from website settings and SSL certificates to PHP-FPM and a reverse proxy. With web hosting plans, you can set redirects and rules for your website in a .htaccess file.

Linux VPS plans

Apache FAQ

How do I apply a change to the Apache configuration without taking my website down?

After editing the file, run apachectl configtest to check the syntax, and if you get Syntax OK, reload the configuration with systemctl reload apache2, or systemctl reload httpd on RHEL-family distributions. During a reload, open connections aren't dropped and requests in progress finish as usual, so visitors don't notice the change. A full restart is needed only in cases such as switching the MPM.

How do I move a website on Apache to HTTPS?

Once an SSL certificate is installed, set up a VirtualHost for port 443 with SSLEngine on and the SSLCertificateFile and SSLCertificateKeyFile directives. In the VirtualHost for port 80, add Redirect permanent to the HTTPS address, and every URL on the website is redirected to the same path on the encrypted version. This is the method the Apache documentation recommends, and it's simpler than mod_rewrite rules. You can get a free certificate from Let's Encrypt with Certbot.

Which is better, settings in the VirtualHost or in a .htaccess file?

When you have access to the server's configuration files, it's better to write the rules in the VirtualHost and set AllowOverride None. This way, the server doesn't look for .htaccess files in every directory on every request, and the website is faster. A .htaccess file suits cases where you have no access to the server configuration, for example on web hosting, or where the content management system writes rules in it on its own.

How do I set up Apache as a reverse proxy for an application?

Enable the proxy and proxy_http modules, and in the website's VirtualHost, add ProxyPass and ProxyPassReverse with the address and port the application listens on, for example http://127.0.0.1:3000/. With ProxyPreserveHost On, the application gets the original domain name, and with the X-Forwarded-Proto header, it knows the visitor came over HTTPS. For WebSocket connections, add the upgrade=websocket parameter to the matching path. This way, Apache handles the SSL certificate, compression, and caching, and the application can focus on its own logic.

How do I connect Apache to PHP-FPM?

Enable the proxy_fcgi module, and in a FilesMatch block for PHP files, set SetHandler with the PHP-FPM socket path. This way, PHP runs in its own separate processes, and you can use MPM event, which handles many requests at the same time with lower memory use. The socket path differs between distributions, and the listen setting in the PHP-FPM pool file shows the exact path.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement