To set up a redirect using mod_rewrite for Apache, follow these steps:
- Enable the rewrite module:
- On RHEL-based systems (like CentOS or Fedora), ensure the rewrite module is enabled by checking if
LoadModule rewrite_module modules/mod_rewrite.sois present in your main Apache configuration file.
- On RHEL-based systems (like CentOS or Fedora), ensure the rewrite module is enabled by checking if
- Place the rewrite rules:
- If you're configuring this for a specific domain, add these rules to your VirtualHost configuration file.
- For single-site configurations, place them in your
.htaccessfile.
- Add the following mod_rewrite directives:
On Debian-based systems (like Ubuntu), enable it using:
sudo a2enmod rewrite
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/secure/(.*)
RewriteRule ^/?(.*) https://www.example.com/secure/$1 [R=301,L]
Explanation:
RewriteEngine On: Enables the rewrite module.RewriteCond %{REQUEST_URI} ^/secure/(.*): This condition checks if the request URI starts with/secure/. The(.*)captures any path following/secure/.RewriteRule ^/?(.*) https://www.example.com/secure/$1 [R=301,L]: This rule redirects any request matching the condition tohttps://www.example.com/secure/followed by the captured path. The flags:R=301: Issues a 301 (permanent) redirect.L: Allows the rewrite engine to continue processing after the redirect.
Notes:
- Temporary Redirect: Replace
R=301withR=302for a temporary redirect. - Testing: Clear your browser cache and test accessing
/secure/via both HTTP and HTTPS to ensure the redirect works correctly. - ServerName: Ensure your VirtualHost configuration sets
ServerNametowww.example.comfor the redirect to function properly.
