Rewriting URLs with the mod_rewrite module
The mod_rewrite module in Apache allows you to rewrite URLs dynamically. On ruachost.com, you can use it to create cleaner, SEO‑friendly links, hide internal implementation details, and redirect visitors to secure connections.
Why Use mod_rewrite?
Section titled “Why Use mod_rewrite?”- SEO benefits: Search engines prefer human‑readable URLs.
- Security: Hide query strings and internal file structures.
- User experience: Provide simple, memorable links.
- Flexibility: Redirect traffic based on conditions (e.g., HTTPS enforcement).
Enabling mod_rewrite
Section titled “Enabling mod_rewrite”- On most Ruachost shared hosting accounts,
mod_rewriteis already enabled.
Basic Example: Clean Product URLs
Section titled “Basic Example: Clean Product URLs”Instead of:
http://www.example.com/products.php?id=232&cat=11You can rewrite to:
http://www.example.com/products/calculator.htaccess Rule:
Section titled “.htaccess Rule:”RewriteEngine OnRewriteRule ^products/calculator$ /products.php?id=232&cat=11 [L]RewriteEngine On→ enables rewriting.RewriteRule→ matches incoming URL and maps it to the target file.[L]→ stops processing further rules once matched.
Common Use Cases
Section titled “Common Use Cases”1. Redirect to HTTPS
Section titled “1. Redirect to HTTPS”RewriteEngine OnRewriteCond %{HTTPS} offRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]2. Remove .php Extension
Section titled “2. Remove .php Extension”RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME}\.php -fRewriteRule ^([^/]+)$ $1.php [L]3. Force Trailing Slash
Section titled “3. Force Trailing Slash”RewriteEngine OnRewriteCond %{REQUEST_FILENAME} -dRewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]Testing Your Rules
Section titled “Testing Your Rules”- Use browser developer tools to confirm redirects.
- Check Apache error logs if rules don’t work.
- Avoid infinite loops by testing carefully.