ENGINEERING JOURNAL

Clean URLs with mod_rewrite on shared hosting (no framework)

How this site serves /projects and /contact with Apache rewrite rules on LiteSpeed — canonical redirects, genuine 404s and no redirect loops.

THE ARTICLE 01 — 01

This site serves clean URLs — /projects, /contact — with plain Apache rewrite rules on LiteSpeed. No framework router, no front controller. Here is the pattern that works and the traps I avoided.

The basic rewrite

Each clean URL maps to a PHP file internally:

RewriteRule ^projects$ projects.php [L]
RewriteRule ^contact$ contact.php [L]

The visitor sees /projects; the server runs projects.php. One rule per page is explicit and easy to audit — on a small site I prefer that over a catch-all.

Redirecting the .php variants

Without a redirect, both /projects and /projects.php would serve the same content — duplicate URLs. The fix inspects the original request line so the internal rewrite does not trigger it:

RewriteCond %{THE_REQUEST} \s/+(projects|contact)\.php[\s?] [NC]
RewriteRule ^(projects|contact)\.php$ /$1 [R=301,L]

THE_REQUEST is key: it holds what the browser actually asked for, so the internally rewritten request does not match and there is no redirect loop.

Trailing slashes and 404s

A trailing-slash variant (/projects/) is another duplicate. A single rule normalizes it, skipping real directories:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]

For missing pages, ErrorDocument 404 /404.php serves a styled 404 page with a genuine 404 status. Nested routes like /tech-stack/laravel go through a dispatcher PHP file that validates the slug against an allowlist and renders the same 404 page for unknown slugs — so there is no way to reach arbitrary files through route parameters.

The checklist

  • Valid pages return 200; missing pages return a genuine 404.
  • .php variants 301-redirect to the clean URL.
  • Trailing slashes normalize to one canonical form.
  • Direct navigation and refresh work on nested URLs.

Simple, auditable, and it survives shared hosting. The deployment side of this story is in deploying a no-framework PHP site on LiteSpeed shared hosting.

Muhammad Aqib ← ALL ARTICLES
KEEP EXPLORING

More ideas.
Better engineering.

Explore the journal ↗