Redirect all requests to HTTPS if they access files under /secure/

Author:Lars Nyström
Updated:May 27, 2025

To set up a redirect using mod_rewrite for Apache, follow these steps:

  1. 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.so is present in your main Apache configuration file.
    • On Debian-based systems (like Ubuntu), enable it using:
      sudo a2enmod rewrite
      
  2. 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 .htaccess file.
  3. Add the following mod_rewrite directives:

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 to https://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=301 with R=302 for 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 ServerName to www.example.com for the redirect to function properly.