Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 30 ยท Real-World Projects

Project: A PHP Application with Clean URLs

Build a production-style setup for a Laravel-style PHP app: front controller, PHP-FPM, clean URLs, protected storage and dotfiles, upload limits, on Nginx and Apache.

In this project you will put a typical PHP application online the way framework authors intend: one front controller (index.php) receives every request that is not a real file, PHP-FPM runs it, and nothing outside a single public folder is ever reachable from the web. The same job is done twice, once with Nginx and once with Apache, so you can compare them line by line.

The application is "Laravel-style", which means the layout is shared by Laravel, Symfony, Slim and many others. You do not need to know any framework to follow along. If a step feels unfamiliar, the lessons PHP, FastCGI and Application Servers, Location Blocks and Matching Order and Redirects and Rewrites explain the ideas behind each directive.

The real servers cannot run on this site, so the configuration appears in read-only blocks. The live examples are JavaScript stand-ins: they reproduce the routing decisions of the config so you can test them. They are not nginx, Apache or PHP.

The goal and the folder layout

The goal is simple to say and easy to get wrong:

  1. https://app.example.com/posts/42/edit must work although no file has that name.
  2. /build/app.js and /storage/avatars/ada.png must be served directly, fast, without starting PHP.
  3. /.env, /.git/config, /vendor/... and the storage/ folder must never be downloadable.
  4. Uploads up to 20 MB must work, and larger ones must fail cleanly.

The trick for points 1 to 3 is the folder layout. Frameworks keep secrets, code and data above the web root, and expose only a public/ folder:

TEXT
/var/www/app/
โ”œโ”€โ”€ .env                  secrets, never public
โ”œโ”€โ”€ app/  config/  routes/  vendor/
โ”œโ”€โ”€ storage/              logs, caches, private uploads
โ””โ”€โ”€ public/               <- the only folder the web server serves
    โ”œโ”€โ”€ index.php         front controller
    โ”œโ”€โ”€ build/app.js
    โ”œโ”€โ”€ robots.txt
    โ””โ”€โ”€ storage -> ../storage/app/public   (symlink for public uploads)

Point root (nginx) or DocumentRoot (Apache) at /var/www/app/public, not at /var/www/app. That one decision removes whole classes of leaks: even a mistake in a location block cannot expose .env, because the file is not under the root at all. The rules below are a second layer of defense, not the first.

Step 1: the Nginx server block

NGINX
server {
    listen 80;
    server_name app.example.com;

    root /var/www/app/public;
    index index.php;
    charset utf-8;

    client_max_body_size 20m;

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    # Clean URLs: real file, real directory, or the front controller
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Only index.php may be executed
    location ~ ^/index\.php(/|$) {
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }

    # Dotfiles are private, except .well-known (certificate checks)
    location ~ /\.(?!well-known).* {
        deny all;
    }
}

Read it as a decision list. A request for /robots.txt hits the exact-match location and is served without logging noise. Everything else starts at location /, where try_files checks the file, then a directory, then falls back to /index.php?$query_string. That fallback is an internal redirect: nginx starts the location search again for /index.php, and this time the regex location with fastcgi_pass wins. The query string is kept so ?page=2 still reaches the application.

Why ^/index\.php(/|$) instead of the usual \.php$? Because with \.php$, every .php file under the root becomes executable. If someone uploads avatar.php into a public folder, it runs. With the narrow pattern, any other .php file is not executed at all (it would simply be served as plain text if it exists, which is why the docroot should contain no other PHP files). The (/|$) part allows /index.php/api/users style URLs. For the matching order that makes the regex win over location /, see Location Blocks and Matching Order.

$realpath_root instead of $document_root matters when you deploy with symlinked release folders: it resolves the symlink, so PHP's opcache and your app see the real release path instead of caching the old one after a switch.

Test and apply:

Terminal
sudo nginx -t && sudo systemctl reload nginx
curl -I https://app.example.com/.env        # expect 403
curl -I https://app.example.com/posts/42    # expect whatever your app returns

Step 2: the Apache virtual host

Apache needs mod_rewrite (or FallbackResource), mod_proxy and mod_proxy_fcgi for PHP-FPM, plus mod_alias for blocking, which is loaded by default:

Terminal
sudo a2enmod rewrite proxy proxy_fcgi
sudo a2enconf php8.4-fpm        # Debian packages ship this snippet
APACHE
<VirtualHost *:80>
    ServerName app.example.com
    DocumentRoot /var/www/app/public

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

        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^ /index.php [L]
    </Directory>

    # Run only index.php through PHP-FPM
    <Files "index.php">
        SetHandler "proxy:unix:/run/php/php8.4-fpm.sock|fcgi://localhost"
    </Files>

    # Dotfiles and dot-folders are private, except .well-known
    RedirectMatch 404 "/\.(?!well-known)"

    # Uploads: 20 MB (value in bytes)
    LimitRequestBody 20971520

    ErrorLog ${APACHE_LOG_DIR}/app-error.log
    CustomLog ${APACHE_LOG_DIR}/app-access.log combined
</VirtualHost>

The structure mirrors nginx. The two RewriteCond lines say "if this is not an existing file and not an existing directory", and the RewriteRule sends it to the front controller. <Files "index.php"> limits PHP handling to one file name, like the narrow nginx regex. AllowOverride None turns .htaccess off, which is faster and safer because the rules live in the one file you review (see .htaccess, Directory Rules and AllowOverride).

If you cannot edit the vhost (shared hosting), the same rewrite rules go into public/.htaccess and AllowOverride FileInfo must be allowed. If you do control the vhost and your rules are just "everything else goes to index.php", Apache has an even shorter tool:

APACHE
FallbackResource /index.php

It does the same job as the two conditions and the rule, with no regular expressions. Use it when you do not need other rewrites. One difference to remember: Apache's LimitRequestBody ends with a 413 response, but PHP's own limits still apply behind it, as the next section shows.

Step 3: uploads need three limits to agree

A file upload passes three gates, and each can say no with a different symptom:

Gate Setting Failure
Web server nginx client_max_body_size, Apache LimitRequestBody 413 before PHP starts
PHP post_max_size in php.ini whole POST silently dropped, $_FILES empty
PHP upload_max_filesize UPLOAD_ERR_INI_SIZE for that file

Nginx's default client_max_body_size is only 1 MB, so "uploads fail with 413 on the server but work locally" is one of the most common deployment surprises. Set the web server value slightly above post_max_size, and post_max_size above upload_max_filesize, so the error a user sees is the most specific one. Remember that a form with several files counts all of them toward post_max_size. The stand-in below shows which gate rejects which size.

JS Stand-in: which upload limit says no?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try changing the numbers so the order is right (nginx 25, post 20, upload 16) and watch which message each size produces. Also remember the other limits on slow uploads: client_body_timeout in nginx, RequestReadTimeout in Apache, and PHP's max_input_time.

Step 4: a test suite for the routing rules

Configuration is code, and code deserves tests. You cannot run nginx here, but you can write down the rules as a function and check a table of URLs against it. On a real server the same table becomes a curl script that you run after every deploy. The function below follows the nginx config from Step 1 in the exact order nginx uses: exact locations, then regex locations in file order, then location / with try_files.

JS Stand-in: a request router test suite

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two things are worth noticing. /build/missing.js reaches PHP, because try_files cannot tell a missing asset from a clean URL: your framework returns the 404 page, which costs a PHP call per missing asset. Many teams add a dedicated location /build/ { try_files $uri =404; } so missing assets get a cheap 404 without PHP. And /.env is blocked by the regex even though the stand-in pretends it exists in public/: that is the second layer of defense working as intended. Try adding "/other.php" to publicFiles and see the safety check warn.

Step 5: protect storage and write permissions

Uploaded files are the classic way PHP sites get hacked, so follow three rules:

  • Private uploads stay outside public/ (in storage/app) and are streamed by your application after a permission check.
  • Public uploads go through the symlink (public/storage), and the web server must never execute scripts in that folder. With the narrow index.php rule, it cannot. In a config that uses \.php$ instead, you would add location ^~ /storage/ { location ~ \.php$ { return 403; } } or similar.
  • The PHP-FPM user owns only what it must write: storage/ and bootstrap/cache/. Code under app/ and vendor/ should be owned by the deploy user and be read-only to the web user.

Finally, check what an anonymous visitor can actually fetch, because tests of the config text are no substitute for tests of the running server:

Terminal
for p in /.env /.git/HEAD /storage/logs/laravel.log /vendor/autoload.php /composer.json; do
  printf '%-28s ' "$p"; curl -s -o /dev/null -w '%{http_code}\n' "https://app.example.com$p"
done

Every line should print 403 or 404, never 200. Put this script into your deploy pipeline and a misplaced docroot is caught within seconds.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should the document root point at the public/ folder and not at the project folder?

    Files outside the document root cannot be reached by any URL. This is the strongest protection, and the location rules are only a second layer.
  2. 2. In the nginx config, what does try_files $uri $uri/ /index.php?$query_string do for /posts/42/edit when no such file exists?

    The last argument of try_files is an internal redirect. The URL in the browser stays the same, and nginx runs the location search again for /index.php.
  3. 3. Why is the PHP location written as ^/index.php(/|$) rather than .php$?

    With .php$ every PHP file under the root is executed, which turns any upload bug into remote code execution. The narrow pattern runs one known script.
  4. 4. A user uploads a 22 MB file and gets a 413 page. The php.ini values are post_max_size=25M and upload_max_filesize=16M. What most likely rejected it?

    413 is sent by the web server. PHP's limits produce an empty $_FILES or an UPLOAD_ERR_INI_SIZE error instead, not a 413 page.

Summary

  • Serve only public/; keep .env, vendor/, and storage/ above the web root.
  • Clean URLs are try_files $uri $uri/ /index.php?$query_string in nginx, and a !-f/!-d rewrite pair (or FallbackResource) in Apache.
  • Execute only index.php through PHP-FPM, never every .php file.
  • Deny dotfiles with an exception for .well-known, in both servers.
  • Align the three upload limits: web server, post_max_size, upload_max_filesize.
  • Test the rules with a URL table, then confirm with curl against the live server after each deploy.

Next: Project: Reverse Proxy for Several Apps.