Using Phalcon with Apache

Phalcon is a high-performance PHP framework designed with speed, low overhead, and scalability in mind. Unlike traditional PHP frameworks written in PHP, Phalcon is implemented as a C extension, giving developers the benefits of a full-stack framework with the performance of a compiled library. When paired with the Apache web server—one of the most widely deployed web servers worldwide—Phalcon becomes a powerful platform for building robust, efficient, and feature-rich web applications.

This guide contains a comprehensive explanation around showing how to install, configure, and optimize Phalcon with Apache. It covers everything from prerequisite software, mod_rewrite configuration, vhost setup, routing, environment management, security practices, troubleshooting, and advanced deployment strategies.

1. Introduction to Running Phalcon on Apache

Phalcon’s low-level integration with the PHP engine provides performance advantages such as lower memory usage and faster execution times. When deploying a Phalcon app, Apache acts as the delivery engine responsible for handling incoming HTTP/S requests and forwarding them properly to the framework’s front controller.

Apache remains popular due to its flexibility, maturity, and extensive module ecosystem. Integrating Phalcon and Apache provides a balance of performance and ease of configuration. The most important part of getting Phalcon to work with Apache is enabling URL rewriting so that all requests are routed through a single front controller—usually public/index.php. This enables the MVC routing system inside Phalcon to handle request parsing.

This guide follows best practices and teaches you how to:

  • Install Phalcon for your environment
  • Configure Apache Virtual Hosts
  • Enable mod_rewrite
  • Point your DocumentRoot to the correct folder
  • Create rewrite rules for clean URLs
  • Configure permissions and security
  • Optimize Apache for performance
  • Troubleshoot common problems

2. Understanding the Phalcon Directory Structure

Before diving into Apache configuration, it is important to understand how a typical Phalcon project is organized. The standard structure looks like this:

project/
 ├─ app/
 │   ├─ controllers/
 │   ├─ models/
 │   ├─ views/
 │   ├─ config/
 │   └─ bootstrap.php
 ├─ public/
 │   ├─ index.php
 │   ├─ css/
 │   ├─ js/
 │   └─ assets/
 ├─ vendor/
 ├─ cache/
 ├─ storage/
 └─ composer.json

The most important directory for Apache is the public folder. This folder contains:

  • The front controller (index.php)
  • Public assets like images, CSS, JavaScript
  • Any static files that should be available to the browser

By setting your Apache DocumentRoot to the public directory, you ensure that only publicly accessible resources can be reached by the user, while application logic inside app/ remains protected.


3. Installing Phalcon Extension on Your Server

Phalcon must first be installed as an extension before the framework can run. Installation varies depending on the operating system. Although this guide does not require a step-by-step installation tutorial, here is a brief overview of how Phalcon is usually installed on Linux systems:

3.1 Installing on Ubuntu/Debian

sudo apt-get update
sudo apt-get install php-dev
sudo pecl install phalcon

After installation, enable it:

echo "extension=phalcon.so" | sudo tee /etc/php/*/mods-available/phalcon.ini
sudo phpenmod phalcon
sudo systemctl restart apache2

3.2 Installing on CentOS/RHEL

yum install php-devel
pecl install phalcon

Enable the extension:

echo "extension=phalcon.so" > /etc/php.d/40-phalcon.ini
systemctl restart httpd

Once installed, confirm with:

php -m | grep phalcon

4. Enabling Apache’s mod_rewrite Module

Phalcon relies on clean URLs. For example:

https://yourdomain.com/products/list

should internally map to:

public/index.php?_url=/products/list

To enable this routing behavior, Apache must have mod_rewrite enabled.

4.1 On Ubuntu/Debian

sudo a2enmod rewrite
sudo systemctl restart apache2

4.2 On CentOS/RHEL

Open /etc/httpd/conf/httpd.conf and ensure:

LoadModule rewrite_module modules/mod_rewrite.so

Then restart:

sudo systemctl restart httpd

Without mod_rewrite, the Phalcon router cannot process routes properly, leading to 404 errors or broken controllers.


5. Configuring Apache Virtual Host for Phalcon

Correct Apache VirtualHost configuration is essential. A typical configuration looks like this:

<VirtualHost *:80>
ServerName yourdomain.com
DocumentRoot /var/www/project/public
&lt;Directory /var/www/project/public&gt;
    AllowOverride All
    Require all granted
&lt;/Directory&gt;
ErrorLog ${APACHE_LOG_DIR}/project_error.log
CustomLog ${APACHE_LOG_DIR}/project_access.log combined
</VirtualHost>

Key Points:

  • DocumentRoot must point to /public, not to the root of the project.
  • AllowOverride All enables .htaccess rules.
  • Permissions must allow Apache to read files.
  • Logging is included for debugging and monitoring.

Enabling the VirtualHost (Debian/Ubuntu)

sudo a2ensite project.conf
sudo systemctl reload apache2

6. Creating the .htaccess File for Phalcon Routing

Inside the public folder, create an .htaccess file with rewrite rules:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?_url=/$1 &#91;QSA,L]
</IfModule>

Explanation of Rules:

  • RewriteEngine On enables rewriting.
  • The two RewriteCond lines prevent rewriting for existing files or directories.
  • RewriteRule passes the requested URL into index.php, allowing the Phalcon router to interpret it.

This is the foundation of the MVC routing system in Phalcon.


7. Understanding How the Routing Mechanism Works

Phalcon uses the router component to decode the incoming _url parameter:

Example:

/products/view/10

Internally becomes:

index.php?_url=/products/view/10

Phalcon’s router then maps this URL to:

  • Controller: ProductsController
  • Action: viewAction
  • Parameter: 10

This pattern gives Phalcon developers great flexibility, allowing routes like:

/blog/2025/02/article-title

or even custom REST-style routing.


8. Index.php as the Front Controller

The index.php file in the public directory is responsible for:

  • Initializing the application
  • Loading services (DI container)
  • Handling requests
  • Sending responses

A typical index.php file looks like this:

<?php

use Phalcon\Mvc\Application;

require_once '../app/bootstrap.php';

$application = new Application($di);

try {
$response = $application-&gt;handle($_GET&#91;'_url'] ?? '/');
$response-&gt;send();
} catch (\Exception $e) {
echo $e-&gt;getMessage();
}

This structure ensures that all requests hitting the server will be properly processed by the framework.


9. Setting Proper File and Directory Permissions

Apache must be able to read files inside the project. Common permission recommendations:

sudo chown -R www-data:www-data /var/www/project
sudo find /var/www/project -type d -exec chmod 755 {} \;
sudo find /var/www/project -type f -exec chmod 644 {} \;

Ensure writable directories (cache, logs):

chmod -R 775 cache/
chmod -R 775 storage/

10. Configuring Environment Variables

You may want separate environments:

  • Development
  • Staging
  • Production

Set environment variables inside Apache using:

SetEnv APPLICATION_ENV "development"

Or use .env files with a loader library.


11. SSL Configuration with Apache for Phalcon

For production deployment, always configure HTTPS.

Example VirtualHost:

<VirtualHost *:443>
ServerName yourdomain.com
DocumentRoot /var/www/project/public
SSLEngine On
SSLCertificateFile /etc/ssl/certs/yourdomain.crt
SSLCertificateKeyFile /etc/ssl/private/yourdomain.key
&lt;Directory /var/www/project/public&gt;
    AllowOverride All
    Require all granted
&lt;/Directory&gt;
</VirtualHost>

Let’s Encrypt can also be used for free SSL certificates.


12. Optimizing Apache for Phalcon Performance

Since Phalcon is extremely fast, ensure that Apache is configured to take full advantage of its speed.

12.1 Use MPM Event Instead of Prefork

Check your active MPM:

apache2ctl -V | grep MPM

Enable event MPM:

sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2

12.2 Enable PHP-FPM

This improves concurrency:

sudo apt install php-fpm
sudo a2enconf php*-fpm
sudo systemctl reload apache2

12.3 Enable caching modules

  • mod_cache
  • mod_deflate
  • mod_expires

13. Security Best Practices

Security is essential in modern web applications.

13.1 Disable Directory Listing

Ensure:

Options -Indexes

13.2 Hide Server Details

ServerSignature Off
ServerTokens Prod

13.3 Protect Sensitive Folders

<Directory /var/www/project/app>
Deny from all
</Directory>

14. Troubleshooting Common Issues

14.1 404 Errors on All Pages

Symptoms: All URLs return a 404 error.

Cause: mod_rewrite not working.

Fix:

  • Ensure .htaccess is enabled
  • Set AllowOverride All in VirtualHost

14.2 index.php Downloads Instead of Executing

Cause: PHP is not installed or not configured.

Fix:

  • Install PHP
  • Enable PHP-FPM or mod_php

14.3 Forbidden 403 Error

Cause:

  • Permissions issue
  • Missing Require all granted

15. Deploying Phalcon Applications on Production Apache Servers

Deployment considerations include:

15.1 Keep Application Code Outside Public Directory

Only public is exposed.

15.2 Use Composer Autoloading

Handle dependencies cleanly.

15.3 Implement Caching

Phalcon offers:

  • Volt caching
  • Model caching
  • Metadata caching

15.4 Load Balancing and Scaling

Apache works well behind:

  • Nginx reverse proxies
  • AWS ELB
  • HAProxy

16. Monitoring and Logging

Use Apache logs plus Phalcon logging:

$app->logger = new \Phalcon\Logger\Adapter\File("../logs/app.log");

Tools:

  • ELK Stack
  • Graylog
  • Grafana + Loki
  • Filebeat

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *