Linux Administration

LAMP Stack Setup: Apache, MariaDB, PHP-FPM, Virtual Hosts and TLS

Intermediate8 min readUpdated

A LAMP server is four independent services that have to agree about sockets, users and file permissions. This guide sets one up deliberately rather than by copying a one-liner: Apache with the event MPM and named virtual hosts, MariaDB with a least-privilege application account, PHP-FPM in its own pool, sensible ownership of the document root, and TLS from Let's Encrypt. Each step ends with a way to verify it.

What you will learn

  • Install and verify Apache, MariaDB and PHP-FPM on a Debian or RHEL-family server
  • Configure name-based virtual hosts with separate document roots and log files
  • Create a database and an application account with only the privileges it needs
  • Connect Apache to PHP-FPM over a socket and tune a pool for the available memory
  • Obtain and renew a Let's Encrypt certificate and apply a basic hardening checklist

LAMP has been the default way to serve a dynamic website for twenty-five years, and the acronym has quietly changed meaning underneath. The Linux is the same. The A is still Apache, but the recommended process model is different. The M is now usually MariaDB. And the P no longer runs inside the web server at all — PHP is a separate service that Apache talks to over a socket.

That last change is the one worth understanding, because it explains most of the configuration below. This guide builds a working server step by step on a current Debian or Ubuntu host, notes the RHEL-family equivalents, and verifies each layer before moving to the next. Nothing here is exotic; the value is in doing it deliberately, so that when something breaks you know which of the four services to look at.

Install the pieces

# Debian / Ubuntu
sudo apt update
sudo apt install apache2 mariadb-server php-fpm php-mysql php-mbstring php-xml php-curl php-zip

# RHEL family (Rocky, Alma, RHEL) — Apache is packaged as httpd
sudo dnf install httpd mariadb-server php-fpm php-mysqlnd php-mbstring php-xml
sudo systemctl enable --now httpd mariadb php-fpm

Package names differ (apache2 versus httpd, php-mysql versus php-mysqlnd) and so do the configuration layouts: Debian uses /etc/apache2/ with sites-available and sites-enabled plus the a2ensite and a2enmod helpers, while RHEL uses a flat /etc/httpd/conf.d/. Everything else transfers. If package management itself is unfamiliar, the package management guide covers repositories and version pinning.

Check the services are up before touching any configuration:

$ systemctl is-active apache2 mariadb php8.3-fpm
active
active
active
$ sudo ss -ltnp | grep -E ':(80|3306)'
LISTEN 0 511  0.0.0.0:80   0.0.0.0:* users:(("apache2",pid=1201,fd=4))
LISTEN 0 80  127.0.0.1:3306 0.0.0.0:* users:(("mariadb",pid=1408,fd=25))

Note that MariaDB listens only on loopback by default. That is correct for a single-server LAMP host and should stay that way: a database with a public address is an invitation, and the networking guide explains how to reach it through an SSH tunnel when you need a client on your laptop.

Apache: process model and modules

Apache 2.4 chooses a multi-processing module at build or configuration time. prefork gives one process per connection and exists mainly for mod_php; event is a threaded model that keeps idle keep-alive connections off the worker threads and handles far more concurrency for the same memory. With PHP running under FPM, event is the right choice.

sudo a2dismod php8.3 mpm_prefork 2>/dev/null
sudo a2enmod mpm_event proxy_fcgi setenvif rewrite headers ssl http2
sudo a2enconf php8.3-fpm
sudo systemctl restart apache2
apache2ctl -M | grep -E 'mpm|fcgi|rewrite'

proxy_fcgi is what forwards PHP requests to FPM; rewrite is required by nearly every PHP framework's front controller; headers lets you set security headers; ssl and http2 you will want shortly. Enable nothing else: every module is code in the request path.

Tuning the event MPM is a matter of arithmetic rather than folklore. Apache itself is small now that PHP is elsewhere, so the limits mostly protect you from queueing more work than the machine can do:

# /etc/apache2/mods-available/mpm_event.conf
<IfModule mpm_event_module>
    StartServers             2
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadsPerChild         25
    MaxRequestWorkers      150
    MaxConnectionsPerChild   0
</IfModule>

Virtual hosts

A name-based virtual host lets one address serve many sites; Apache picks the block whose ServerName or ServerAlias matches the Host header. Give every site its own file, document root and log files.

# /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
    ServerName  example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public

    <Directory /var/www/example.com/public>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    # Never serve the application's internals, even if a path escapes the root
    <DirectoryMatch "/(\.git|vendor|storage)/">
        Require all denied
    </DirectoryMatch>

    ErrorLog  ${APACHE_LOG_DIR}/example.com-error.log
    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
</VirtualHost>
sudo a2ensite example.com
sudo apache2ctl configtest       # or: httpd -t
sudo systemctl reload apache2

Four details in that block are worth explaining. DocumentRoot points at a public/ subdirectory, not at the project root, so configuration files and dependencies are physically outside the served tree. Options -Indexes stops Apache generating a directory listing when there is no index file — a routine source of accidental disclosure. AllowOverride None disables .htaccess, which means Apache does not stat for those files on every request and your configuration lives in one place; enable it only for applications that genuinely require it. And Require all granted is the 2.4 authorisation syntax that replaced Order allow,deny — old tutorials showing the 2.2 form will produce a configuration that does not load.

Always run configtest before reloading. A syntax error on reload leaves the old configuration serving; a syntax error found only at restart leaves the site down.

MariaDB: secure it, then create least privilege

The first thing to run after installation is the hardening script, which removes the anonymous accounts and the test database and offers to disable remote root login:

sudo mariadb-secure-installation     # mysql_secure_installation on MySQL

On current MariaDB the root account authenticates through the unix_socket plugin, meaning sudo mariadb works with no password and remote root login is impossible by construction. Leave it that way. Applications get their own account, restricted to their own database and to the host they connect from:

CREATE DATABASE shop CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE USER 'shop_app'@'localhost' IDENTIFIED BY 'a-long-random-passphrase';
GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'shop_app'@'localhost';

-- A separate account for migrations, used only by the deployment process
CREATE USER 'shop_ddl'@'localhost' IDENTIFIED BY 'another-long-passphrase';
GRANT ALL PRIVILEGES ON shop.* TO 'shop_ddl'@'localhost';

FLUSH PRIVILEGES;
SHOW GRANTS FOR 'shop_app'@'localhost';

utf8mb4 is the only correct character set choice; the older utf8 in MySQL stores at most three bytes per character and cannot represent emoji or some CJK characters. Splitting the runtime account from the schema-migration account means a SQL-injection flaw in the application cannot drop a table, which is a cheap and effective control. The schema and query side of this is covered in SQL best practices.

Two operational tasks belong here rather than later. Take a backup and prove you can restore it:

sudo mariadb-dump --single-transaction --routines --events shop | zstd -o /srv/backups/shop-$(date +%F).sql.zst
zstd -dc /srv/backups/shop-2026-09-07.sql.zst | sudo mariadb shop_restore_test

And keep credentials out of shell history and process listings by putting them in a mode-600 option file rather than on the command line:

# /root/.my.cnf   (chmod 600)
[client]
user = root
password = only-if-you-are-not-using-socket-auth

PHP-FPM

FPM runs pools — independent groups of worker processes, each with its own user, socket and limits. Give every site its own pool so that one runaway application cannot starve the others and so file ownership stays separated.

; /etc/php/8.3/fpm/pool.d/example.com.conf
[example.com]
user = www-example
group = www-example
listen = /run/php/php8.3-fpm-example.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6
pm.max_requests = 500

php_admin_value[error_log] = /var/log/php/example.com-error.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 256M
php_admin_value[upload_max_filesize] = 16M
php_admin_value[post_max_size] = 16M
php_admin_value[open_basedir] = /var/www/example.com:/tmp

pm.max_children is the number that matters. Multiply it by the average memory a request uses — measure it, do not guess — and the result must fit comfortably in RAM with room for MariaDB and the page cache. Twenty workers at 80 MB is 1.6 GB, which is already too much for a 2 GB machine. pm.max_requests recycles a worker after a number of requests, papering over slow leaks in third-party code.

open_basedir confines the interpreter to the paths listed, so a file-inclusion bug cannot read /etc/passwd. php_admin_value cannot be overridden by the application at runtime, unlike plain php_value.

Point the virtual host at the socket:

    <FilesMatch \.php$>
        SetHandler "proxy:unix:/run/php/php8.3-fpm-example.sock|fcgi://localhost/"
    </FilesMatch>
    <FilesMatch "\.(env|ini|log|sh|sql|bak)$">
        Require all denied
    </FilesMatch>
sudo systemctl reload php8.3-fpm apache2

For production, turn on the opcode cache and turn off the settings that leak information. In /etc/php/8.3/fpm/php.ini:

display_errors = Off
expose_php = Off
opcache.enable = 1
opcache.memory_consumption = 192
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 0
session.cookie_httponly = 1
session.cookie_secure = 1
session.cookie_samesite = Lax

opcache.validate_timestamps = 0 stops PHP checking file modification times on every request, which is a measurable win — and means you must reload FPM on every deployment. Make that part of your deployment script rather than a thing you remember.

Permissions for the document root

This is where most LAMP installations quietly go wrong, usually by way of chmod -R 777. The principle is simple: the web server should be able to read the application and write only the few directories that genuinely need it.

sudo useradd -r -M -d /var/www/example.com -s /usr/sbin/nologin www-example
sudo chown -R deploy:www-example /var/www/example.com
sudo find /var/www/example.com -type d -exec chmod 750 {} +
sudo find /var/www/example.com -type f -exec chmod 640 {} +

# Only these need to be writable by the PHP worker
sudo chown -R www-example:www-example /var/www/example.com/storage /var/www/example.com/var/cache
sudo chmod -R 770 /var/www/example.com/storage

Files are owned by the deployment account and readable by the pool's group; the pool user owns only the writable directories. Nothing is world-readable, and uploaded files cannot be executed because the interpreter only runs paths matching the FilesMatch handler — which is also why an upload directory should be served from a path where .php handling is switched off entirely. The reasoning behind these modes, and the ACL alternative when the ownership becomes awkward, is in users, groups and permissions.

On a RHEL-family host, SELinux adds a second layer. Files must carry the right label and the daemon needs a boolean before it can, for example, open a network connection:

sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/example.com(/.*)?"
sudo semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/example.com/storage(/.*)?"
sudo restorecon -Rv /var/www/example.com
sudo setsebool -P httpd_can_network_connect_db on

Turning SELinux off is not a fix; ausearch -m avc -ts recent tells you precisely what was denied.

TLS with Let's Encrypt

Certbot obtains a certificate, edits the virtual host and installs a renewal timer.

sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d example.com -d www.example.com --redirect --agree-tos -m [email protected]
sudo certbot renew --dry-run
systemctl list-timers 'certbot*'

--redirect adds the permanent redirect from port 80 to 443. The HTTP-01 challenge needs port 80 open to the internet, so leave it reachable rather than firewalling it after the first issuance. Then set the protocol policy explicitly in the TLS virtual host:

    SSLProtocol -all +TLSv1.2 +TLSv1.3
    SSLHonorCipherOrder off
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    Header always set X-Content-Type-Options "nosniff"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    Protocols h2 http/1.1

Enable HSTS only once you are certain every subdomain will keep working over HTTPS: browsers cache the header for its full lifetime and there is no quick way to undo it. Start with a short max-age, confirm nothing broke, then raise it.

Verify the whole stack

$ curl -sS -o /dev/null -w '%{http_code} %{redirect_url}\n' http://example.com/
301 https://example.com/
$ curl -sSI https://example.com/ | head -6
HTTP/2 200
server: Apache
strict-transport-security: max-age=31536000; includeSubDomains
$ printf '<?php echo "db: ", (new PDO("mysql:host=localhost;dbname=shop","shop_app","...")) ? "ok" : "fail";' \
    | sudo -u www-example php
db: ok
$ sudo tail -n 20 /var/log/apache2/example.com-error.log

Confirm four things independently: the redirect works, TLS terminates with the headers you set, PHP can reach the database as the pool user, and the error log is quiet. Never leave a phpinfo() page behind — it publishes your paths, extensions, and often environment variables.

Hardening checklist

  • Keep the host patched, ideally with unattended security upgrades enabled.
  • Firewall everything except 80, 443 and SSH; keep MariaDB on loopback.
  • Run each site under its own FPM pool user, with open_basedir set.
  • display_errors = Off, expose_php = Off, ServerTokens Prod and ServerSignature Off.
  • Deny access to dot-files, .env, backups and version-control directories in the virtual host.
  • Disable .htaccess unless an application needs it.
  • Set LimitRequestBody, and use mod_reqtimeout and mod_evasive or a reverse proxy for basic rate limiting.
  • Rotate and monitor the per-site logs; ship them somewhere they survive the machine.
  • Back up the database and the uploads directory, and restore both into a scratch environment on a schedule.

Common mistakes

  • chmod -R 777 on the document root. Every local account can now rewrite your application. Fix ownership instead.
  • Pointing DocumentRoot at the project root. .env, composer.json and .git become downloadable.
  • Leaving AllowOverride All on by habit. It costs filesystem checks on every request and scatters configuration.
  • Using Apache 2.2 authorisation syntax. Order allow,deny no longer applies; use Require.
  • Restarting instead of reloading after a config change. configtest then reload keeps the site up if you made a typo.
  • Setting pm.max_children high because a tutorial did. Multiply by per-request memory first; over-provisioning turns a traffic spike into swapping.
  • Granting ALL PRIVILEGES to the application account. Split runtime and migration credentials.
  • Disabling SELinux to make a 403 go away. Label the files; ausearch tells you which ones.

Key takeaways

  • Modern LAMP runs PHP as a separate FPM service, which frees Apache to use the threaded event MPM and lets each site run as its own user.
  • Give every site its own virtual host file, document root under public/, log files and FPM pool.
  • Serve from a directory the web user can read and cannot write, with a short list of explicitly writable paths — never 777.
  • Secure MariaDB at install time, keep it on loopback, use utf8mb4, and split the runtime account from the migration account.
  • Size pm.max_children from measured per-request memory, and enable OPcache with timestamp validation off plus an FPM reload in your deployment.
  • Let's Encrypt via certbot handles issuance and renewal; add HSTS and the other security headers deliberately, starting with a short lifetime.
  • Verify each layer with configtest, curl -I, a database connection as the pool user, and a quiet error log before declaring the server done.

Sources and further reading

Frequently asked questions

Should I use MySQL or MariaDB?
For a new LAMP server either works, and both are in the default repositories. MariaDB is the default on most Linux distributions, is fully open source and remains protocol-compatible for typical PHP applications. Choose MySQL when an application explicitly requires an Oracle MySQL feature or a specific version. Whichever you install, keep the client library and the server on compatible versions and avoid mixing packages from both projects on one host.
What is the difference between mod_php and PHP-FPM?
mod_php embeds the interpreter in every Apache process, which forces the prefork MPM and one heavyweight process per connection. PHP-FPM runs PHP as a separate pool of workers that Apache talks to over a socket, so Apache can use the threaded event MPM, static files cost almost nothing, and each site can run under its own user with its own limits. FPM is the current recommendation for anything beyond a toy site.
Why do I get a 403 Forbidden on a directory that clearly exists?
Three causes account for nearly all of them. The Apache user cannot traverse every directory in the path, so check each one with namei -l. There is no Require all granted for that directory in the configuration. Or SELinux is enforcing and the files do not carry the httpd_sys_content_t label. Read the error log first: Apache states which of the three it hit, and guessing wastes far more time.
How do Let's Encrypt renewals actually happen?
The certbot package installs a systemd timer that runs twice a day, checks every certificate and renews any with fewer than thirty days remaining. Nothing is renewed until then, so the timer running frequently is normal. Verify the whole path with certbot renew --dry-run, which performs a real challenge against the staging environment, and make sure port 80 stays reachable because the HTTP-01 challenge needs it.