Beginner Fundamentals
URL Rewriting with mod_rewrite
The mod_rewrite module changes URLs on the fly using rules based on regular expressions. It is one of the most powerful Apache features.
Enable the Module
sudo a2enmod rewrite
sudo systemctl restart apache2
Turn On the Engine
Rewriting only works after you enable the engine in your config or .htaccess:
RewriteEngine On
RewriteRule
A rule matches the requested path and rewrites it:
# Map /products to /products.php
RewriteRule ^products/?$ products.php [L]
The pattern uses a regular expression. The [L] flag means “last rule”, stop processing further rules.
RewriteCond
A condition runs a rule only when it is met:
# Force HTTPS when the request is not secure
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
%{HTTPS} and %{HTTP_HOST} are server variables. R=301 issues a permanent redirect.
Common Flags
[L]: stop after this rule.[R=301]: redirect permanently.[NC]: case-insensitive match.
Test carefully, since a bad pattern can create redirect loops. Check the error log if rules misbehave.