URL Rewriting with .htaccess

Updated 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.

Enabling mod_rewrite

Before 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

Basic URL Rewriting

Simple Redirect: Redirect a URL to a new location.

RewriteRule ^old-page\.html$ /new-page.html [R=301,L]

Clean URLs: Convert dynamic URLs to clean URLs.

RewriteRule ^products/([0-9]+)/([a-zA-Z-]+)$ product.php?id=$1&name=$2 [L]

Advanced Techniques

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.

Best Practices

  1. Use Permanent Redirects: Use [R=301] for permanent redirects to inform search engines of the change.
  2. Test Thoroughly: Test rules in a development environment to avoid disrupting live traffic.
  3. Use [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.
  4. Keep Rules Organized: Document and organize rewrite rules to maintain clarity and ease of maintenance.

Conclusion

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.

Comments