Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

The error means the Apache process parsing your configuration does not have mod_rewrite loaded, or the rewrite directive is being read in a context where it is not allowed. Loading the module and turning on the rewrite engine are separate steps. If rules are in .htaccess, Apache must also permit the required overrides in the matching <Directory> block.

Identify the Apache installation that actually serves the request, enable mod_rewrite there, add RewriteEngine On in the correct server, virtual-host, directory, or per-directory context, validate the configuration, reload Apache, and then test the exact URL and virtual host that should match the rule.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the mod_rewrite error is telling you

Apache’s URL-rewriting directives are supplied by the mod_rewrite module. Directives such as RewriteEngine, RewriteRule, and RewriteCond are recognized only when that module is loaded and the directive is permitted in the current configuration context.

A message such as Invalid command 'RewriteEngine' normally appears during apachectl configtest, apache2ctl configtest, a service restart, or a deployment check. At that point Apache has not accepted the configuration, so changing the regular expression will not help. The usual causes are:

  • The running Apache instance has not loaded mod_rewrite.
  • You enabled the module in a different installation, container, chroot, or image than the one serving traffic.
  • The directive is inside a context that does not allow it.
  • A request is reaching another virtual host, document root, or container than the one you edited.

When configuration testing succeeds but a rule appears to do nothing, the problem has shifted from module loading to engine state, override policy, path matching, virtual-host selection, or the rule itself.

Confirm which Apache instance is running

Do this before editing files. Systems can contain more than one Apache binary, a host service plus a container, or separate development and production configurations. Run the inspection commands on the machine or container that receives the request.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Inspect the loaded-module list

Use the control command belonging to the active installation:

apachectl -M | grep rewrite
apache2ctl -M | grep rewrite
httpd -M | grep rewrite

A loaded module is normally listed as rewrite_module (shared) or an equivalent entry. If the command itself points to a different binary than your service manager uses, correct that mismatch first. You can compare the binary path reported by your operating system’s service definition with the command you are running and inspect the service’s process arguments.

Check the service and configuration locations

On Debian-family systems, the service is commonly named apache2; on many Red Hat-family and other distributions it is commonly httpd. The names of configuration directories and module helpers vary. A successful command on one host does not prove that a separate container or virtual machine has the module.

  • Run the module-list command from inside the web container if the request is containerized.
  • Check the virtual host selected for the request rather than assuming the first file in a configuration directory is active.
  • Verify that the document root and .htaccess file belong to the same Apache instance you are testing.

Load mod_rewrite

Debian and Ubuntu

Enable the packaged module with:

sudo a2enmod rewrite

The helper enables the distribution’s module configuration, typically by linking it into the active modules directory. It does not turn rewriting on for a site; you still need RewriteEngine On in each context that owns rules. If the command reports that the module is already enabled, continue by checking the running binary and configuration path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Other Linux distributions and custom builds

Ensure the active configuration contains the platform-appropriate LoadModule entry. A typical form is:

LoadModule rewrite_module modules/mod_rewrite.so

The module filename and directory are distribution-specific, so use the path installed by your package or build rather than copying a path from another operating system. Place the directive in a configuration file that the running Apache actually includes. If Apache was compiled without the module, install the distribution package that supplies it or rebuild Apache with the module enabled.

Confirm the result

Run the module-list command again and make sure the same service that will be reloaded reports rewrite_module. If it does not, stop and resolve the installation or include-path mismatch before editing rewrite rules.

Turn the rewrite engine on in the right context

Loading the module only makes its directives available. Each server, virtual host, directory, or .htaccess context that needs rewriting must enable the engine:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
RewriteEngine On

Rewrite configuration is not automatically inherited by every virtual host. If several virtual hosts have independent rules, put RewriteEngine On in each virtual host that needs it. A rule in one host does not silently apply to another host that happens to use the same server.

Server or virtual-host example

A minimal redirect in server or virtual-host configuration looks like this:

RewriteEngine On
RewriteRule ^old$ /new [R=301,L]

This sends a request matching the intended path to /new with a permanent redirect. Put the directives inside the active server or virtual-host configuration, not in an unrelated file that Apache never includes. A permanent redirect can be cached by browsers and intermediaries, so use a temporary redirect while testing if you are not certain the destination is final.

Directory and .htaccess example

When rules live in a directory context or .htaccess, the directory prefix has already been removed from the string being matched. A simple per-directory rule is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
RewriteEngine On
RewriteRule ^old$ new [L]

The substitution is relative to that directory. Per-directory matching commonly uses no leading slash, whereas server-level rules are evaluated against the request path in the server context. Copying a pattern between these contexts without adjusting it is a common reason for a rule that loads correctly but never matches.

Make .htaccess rules permissible

Apache reads a .htaccess file only when the matching <Directory> policy permits the directives it contains. Locate the <Directory> block for the exact document root or parent directory, then check its AllowOverride setting.

<Directory /path/to/document-root>
    AllowOverride FileInfo
</Directory>

AllowOverride FileInfo is commonly sufficient for rewrite directives and is narrower than enabling every override class. The exact path must match the directory that contains the file; changing a different block has no effect. If the policy is AllowOverride None, Apache will ignore or reject the per-directory rewrite configuration according to the directive and version. Use the narrowest override policy that supports the site’s rules rather than enabling unrestricted overrides across the filesystem.

Check file placement and permissions

  • Confirm the file is named exactly .htaccess, including the leading dot.
  • Place it below the document root or another directory for which overrides are enabled.
  • Make it readable by the Apache worker account and ensure parent directories can be traversed.
  • Check for another .htaccess higher or lower in the path that changes processing.
  • Make sure the request is not being served by a different virtual host, proxy, container, or application entry point.

Do not use a broad filesystem-wide override as a shortcut. A narrowly scoped directory policy makes it easier to audit which files can alter request routing.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Validate before reloading Apache

Always test syntax before restarting or reloading:

sudo apachectl configtest
sudo apache2ctl configtest
sudo httpd -t

Use the command appropriate for the active installation; do not run all three blindly. The expected successful result is typically Syntax OK. Fix every reported error, including one in an unrelated included file, before reloading. Apache will not safely apply a configuration that fails validation.

After a successful test, reload the service so workers receive the new configuration:

sudo systemctl reload apache2
sudo systemctl reload httpd

If your deployment does not support a graceful reload, use its documented restart operation and plan for the connection impact. Then request a URL that definitely exercises the rule, using the intended hostname and scheme. Testing only an IP address can select a different virtual host.

Diagnose an immediate Invalid command error

If configtest still reports Invalid command 'RewriteEngine', the directive is being parsed before mod_rewrite is available or by a different Apache process than the one you enabled.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Run the module-list command through the same binary or service environment used for the reload.
  2. Inspect the active include tree and confirm the LoadModule rewrite_module line is included before the file containing rewrite directives.
  3. Check whether a container image, hosting control panel, or orchestration file replaces the configuration at startup.
  4. Verify that you did not enable the module on the host while the request is handled inside a container, or enable it in one container while another serves the port.
  5. Run the configuration test as the service’s installation expects; a shell alias or alternate PATH can invoke a different binary.

Do not hide the error by deleting RewriteEngine while leaving RewriteRule or RewriteCond directives behind. All of those directives depend on the module.

When the configuration is valid but rules do nothing

Engine state and virtual-host selection

Confirm that RewriteEngine On appears in the active virtual host or directory context. Then verify the hostname, port, and TLS termination path used by the test request. A proxy or HTTPS terminator can forward traffic to a different backend or alter headers that conditions inspect.

Per-directory pattern syntax

In .htaccess, remove the directory prefix from your mental model and test the remaining path. A file at /var/www/site/blog/.htaccess sees a request for /blog/old as old for the local rule. A server-level rule sees the request in the server’s URL-path context. Adjust anchors, slashes, and substitutions accordingly.

Rule order and flags

Rules are processed in order. A preceding rule with [L] can stop processing, while a redirect can send the next request through the rules again. Review every condition and substitution, not only the line you just added. Ensure the destination is not itself rewritten back to the original URL.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Document root and file bypasses

Static files, aliases, proxy handlers, and application front controllers can bypass the directory containing your .htaccess. Confirm that the requested path actually traverses that directory and that an Alias or proxy mapping has not routed it elsewhere.

Recover from a 500 error after adding .htaccess

A 500 response after the file is read generally indicates a disallowed directive, malformed syntax, or an environment policy required by per-directory rewriting. Read the Apache error log for the exact directive and file location.

  • If the log says a directive is not allowed, adjust the matching AllowOverride policy or move the rule into server or virtual-host configuration.
  • If it reports a malformed rule, simplify the pattern and substitution, then run configtest again.
  • If the deployment requires FollowSymLinks or an equivalent policy for per-directory rewriting, satisfy that policy in the appropriate directory configuration rather than guessing in the file.
  • Check ownership and permissions so Apache can read the file and every parent directory.

Change one item at a time and retest. Removing the entire file may make the error disappear while also removing unrelated security or routing rules, so preserve a copy and restore directives deliberately.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Investigate redirect loops and wrong destinations

A loop means a request is repeatedly transformed into another request that meets the same conditions. Compare the original URL, the Location header, and the URL received on the next request. Inspect conditions involving scheme, host, forwarded headers, and trailing slashes when a proxy or TLS terminator sits in front of Apache.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a temporary redirect during diagnosis and verify that the substitution points to the canonical destination. If an HTTPS condition relies on proxy headers, confirm that the proxy sets and Apache trusts the expected header; otherwise Apache may believe every request is HTTP and redirect indefinitely. After correcting the rule, retest with a fresh browser session or a command-line client so a cached permanent redirect does not obscure the result.

Use rewrite tracing only while debugging

Apache describes rewrite trace logging as indispensable for seeing how each rule is processed. Temporarily raise rewrite logging for the relevant server or virtual host, reproduce one failing request, and inspect the error log for the matched pattern, conditions, substitution, and termination flag. Keep the trace window short and narrow.

Trace output can be voluminous and may expose request data. Return logging to the normal production level immediately after collecting the evidence, and do not expose detailed logs through a public endpoint. The log should answer a specific question such as whether the request reached the expected virtual host or which condition failed.

Decide whether mod_rewrite is the right tool

mod_rewrite is powerful and can express conditional, regular-expression-based routing, but complexity increases the chance of loops, unintended matches, and difficult maintenance. Apache’s documentation recommends simpler directives when they meet the requirement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Requirement Prefer Why
One fixed old URL permanently moved to one new URL Redirect Clear intent with no regular-expression or condition processing.
Map a URL prefix to a filesystem directory Alias Expresses a static path mapping directly.
Conditional routing based on host, headers, scheme, or captured path mod_rewrite Conditions and regular expressions are part of the requirement.
Application-specific routing, authentication, or business decisions Application router where practical Business logic is easier to test and observe in the application layer.

Replacing a simple rewrite with Redirect or Alias reduces the number of directives that must be permitted in .htaccess and makes the resulting policy easier to review.

Security and reliability practices

Treat rewrite rules as executable routing policy, not harmless text substitutions. Constrain user-controlled input with explicit patterns and conditions. Avoid unconstrained substitutions that turn request data into arbitrary filesystem paths or internal proxy targets. Keep canonicalization rules narrow enough that a malformed path cannot escape the intended directory or create a loop.

  • Prefer a small number of named, documented patterns over one expression that attempts to match every case.
  • Use explicit host and scheme conditions when generating absolute redirects.
  • Keep permanent redirects only after the destination has been verified.
  • Review changes in the same configuration repository or deployment process used for other server policy.
  • Limit AllowOverride to the classes and directories that require it.
  • Disable elevated rewrite trace logging after diagnosis.

A complete fix checklist

  1. Identify the Apache binary, service, container, and virtual host that serve the failing request.
  2. Run the matching module-list command and confirm rewrite_module is loaded.
  3. On Debian or Ubuntu, run sudo a2enmod rewrite; elsewhere, enable the correct LoadModule rewrite_module entry in the active configuration.
  4. Add RewriteEngine On to every server, virtual-host, directory, or .htaccess context that owns rewrite rules.
  5. If using .htaccess, enable the narrowest suitable override class, commonly AllowOverride FileInfo, in the matching <Directory> block.
  6. Verify the file’s location, permissions, document root, and virtual-host selection.
  7. Adjust patterns for the context: per-directory rules omit the directory prefix and commonly the leading slash.
  8. Run the appropriate apachectl configtest, apache2ctl configtest, or httpd -t and fix every error.
  9. Reload Apache, then test the exact hostname, scheme, port, and URL that should match.
  10. If behavior remains unclear, collect a short rewrite trace, inspect the error log, and return logging to normal.

The durable fix is not merely adding a line to a rule file. It is making sure the correct Apache instance loads mod_rewrite, the owning context enables the engine, per-directory policy allows the directives, and the tested request reaches the file and virtual host you changed.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.