.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_rewrite
Before using URL rewriting, ensure mod_rewrite
is enabled. Add this line to your Apache configuration:
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.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 browser type or referrer.
RewriteCond %{HTTP_USER_AGENT} ^Mozilla [NC]
RewriteRule ^old-browser$ /upgrade.html [R=302,L]
[R=301]
for permanent redirects to inform search engines of the change.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.