.htaccessUpdated November 2026 for Apache 2.4. The complete, current reference is Advanced Mod_Rewrite in THE Ultimate Htaccess.
URL rewriting is a powerful technique used to create cleaner, more user-friendly URLs, enhance SEO, and maintain backward compatibility. In Apache, this is accomplished using the mod_rewrite module in .htaccess files.
mod_rewriteBefore using URL rewriting, ensure mod_rewrite is enabled. Add this line to your main Apache configuration (on Debian and Ubuntu, run a2enmod rewrite). It cannot go in .htaccess:
LoadModule rewrite_module modules/mod_rewrite.so
In .htaccess, start by enabling the rewrite engine:
RewriteEngine On
Simple Redirect: Redirect a URL to a new location.
RewriteRule ^old-page\.html$ /new-page.html [R=301,L]
^old-page\.html$: Matches the old URL./new-page.html: Redirects to the new URL.[R=301,L]: Performs a 301 permanent redirect and stops further rules. Test it as R=302 first, because browsers cache a 301 aggressively.Clean URLs: Convert dynamic URLs to clean URLs.
RewriteRule ^products/([0-9]+)/([a-zA-Z-]+)$ product.php?id=$1&name=$2 [L]
^products/([0-9]+)/([a-zA-Z-]+)$: Matches /products/123/product-name.product.php?id=$1&name=$2: Rewrites to product.php?id=123&name=product-name.Wildcard Redirects:
Redirect all .php pages to .html.
RewriteRule ^(.*)\.php$ /$1.html [R=301,L]
Conditional Redirects:
Redirect based on conditions, such as the visitor's preferred language. (Do not test for a User-Agent starting with Mozilla: every modern browser's does.)
RewriteCond %{HTTP:Accept-Language} ^de [NC]
RewriteRule ^$ /de/ [R=302,L]
Use a 302 here, because the answer depends on who is asking and must not be cached as permanent.
[R=301] for permanent redirects to inform search engines of the change.[END] for Internal Rewrites: in .htaccess, [L] only ends the current pass and the rewritten URL runs through the file again. [END] stops for good.URL rewriting with .htaccess is a versatile tool for managing URLs, improving SEO, and enhancing user experience. By leveraging mod_rewrite, you can create intuitive and clean URLs, ensuring your website is both user-friendly and search engine optimized.