Apache · Configuration and operations

How does mod_rewrite work at a high level?

Mediummod_rewriterewriteroutingUpdated Oct 2026
Quiz this track

Short answer

mod_rewrite matches the request URL against RewriteRule patterns and can rewrite, redirect or proxy it, optionally guarded by RewriteCond conditions. Rules run in order, so flags and context determine the final result.

RewriteEngine On enables processing. RewriteCond adds conditions that must all pass for the following RewriteRule. The rule pattern matches the URL path, and the substitution can be a new path, an absolute URL for a redirect or a proxy target with the P flag.

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
Force HTTPS, then send unknown paths to a front controller.

Context matters

  • In server or virtual host context the pattern sees the path starting with a slash
  • In directory and .htaccess context the leading slash is stripped
  • RewriteBase sets the base for relative substitutions in directory context
  • L stops the current rule pass, but may not stop all processing; END does
  • PT passes the rewritten URI back through the URL-to-filename mapping

Use the simplest tool that works. A single permanent redirect belongs in Redirect or RedirectMatch from mod_alias. Rewrite rules are justified when the decision depends on headers, query strings, filesystem existence or a chain of conditions.

Rewrite logging is enabled with LogLevel alert rewrite:trace3. It is verbose, so turn it on briefly and only for the affected virtual host.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between RewriteRule and RewriteCond?
  2. 2Why does a pattern behave differently in .htaccess?
  3. 3When would you use Redirect instead of mod_rewrite?
  4. 4How do you debug a rewrite loop?

Say it in the interview

mod_rewrite evaluates conditions and rules in order. Conditions must all match, then the rule can rewrite, redirect or proxy. The context changes what the pattern sees, especially the leading slash in .htaccess. I use mod_alias for simple redirects and reserve rewrite for conditional routing, and I debug with rewrite trace logging.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Apache mock interview and get scored feedback on depth, clarity and confidence.