URL rewriting with `mod_rewrite` in Apache HTTP Server allows you to manipulate URLs to be more user-friendly, SEO-friendly, and to enable smooth redirections. By using `mod_rewrite`, you can transform an ugly URL like `http://example.com/index.php?page=something` into a cleaner, easier-to-read URL like `http://example.com/something`.
To configure URL rewriting, you first need to ensure that the `mod_rewrite` module is enabled. Here is a step-by-step guide, complete with examples and sources for further reference:
1. Enable `mod_rewrite` if it’s not already enabled: – Run the command: `sudo a2enmod rewrite` – Restart Apache to apply the changes: `sudo systemctl restart apache2`
1. Add rewrite rules: – Here’s a basic example that rewrites a request for `http://example.com/something` to `http://example.com/index.php?page=something`: \`\`\`apache RewriteEngine On RewriteRule ^([a-zA-Z0-9]+)$ index.php?page=$1 [L] \`\`\`
1. Explanation of the above rewrite rule: – `RewriteEngine On`: Enables the `mod_rewrite` engine. – `RewriteRule`: The core directive to define a rewrite rule. – `^([a-zA-Z0-9]+)$`: This pattern will match any single word consisting of letters and numbers. – `index.php?page=$1`: The target URL that includes the captured group as a query parameter. – `[L]`: The flag to indicate that this is the last rule and no further rewriting should be done.
1. Redirect from `http` to `https`: \`\`\`apache RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.\*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] \`\`\` – Forces any request over `http` to be redirected to `https`.
1. Removing `www` from URLs: \`\`\`apache RewriteEngine On RewriteCond %{HTTP\_HOST} ^www.(.\*)$ [NC] RewriteRule ^(.\*)$ http://%1/$1 [R=301,L] \`\`\` – Redirects `http://www.example.com` to `http://example.com`.
By following these steps and examples, you can effectively configure URL rewriting with `mod_rewrite`, making your URLs cleaner, more user-friendly, and improving overall site navigation.