Thursday, September 17, 2020

Using apache mod_rewrite to redirect everything except selected folders

We can use setup Apache Web server's mod_rewrite to redirect everything except selected directories.

Let's consider two scenarios. 

  1. Whole site redirection. Let's assume we want to redirect http://www.mydomain.com to https://secure.mydomaintoo.com, however, except directories upload1 and upload2, we place a .htaccess file at the root directory of the system, e.g., /var/www/html,
    
    RewriteEngine On
     RewriteCond %{REQUEST_URI} !^/upload1/.*
     RewriteCond %{REQUEST_URI} !^/upload1$
     RewriteCond %{REQUEST_URI} !^/upload2/.*
     RewriteCond %{REQUEST_URI} !^/upload2$
     RewriteRule ^(.*)$ https://secure.mydomaintoo.com/$1 [R=301,L]
    
  2. Subsite redirection. Let's assume we want to redirect http://www.mydomain.com/~subsite/ to https://secure.mydomaintoo.com, however, except directories upload1 and upload2, we place a .htaccess file at the root directory of the system, e.g., /var/www/html,
    
    RewriteEngine On
     RewriteCond %{REQUEST_URI} !^/~subsite/upload1/.*
     RewriteCond %{REQUEST_URI} !^/~subsite/upload1$
     RewriteCond %{REQUEST_URI} !^/~subsite/upload2/.*
     RewriteCond %{REQUEST_URI} !^/~subsite/upload2$
     RewriteRule ^(.*)$ https://secure.mydomaintoo.com/$1 [R=301,L]
    
    

1 comment: