Search code examples
apachemod-rewriteapache-config

Apache mod rewrite rule issue


I am trying to write a mod_rewrite rule for my apache server. My requirement is that I have three web applications on a server, out of which all request to HTTP scheme should be redirected to HTTPS.

Here's what I have written :

RewriteEngine On

RewriteCond $1 ^abc$ [NC]
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R]

This doesn't seems to be working fine. I am trying to run application with abc context root to run on HTTP and all other requests to be redirected to HTTPS URL.

Can anyone tell me what am I doing wrong.


Solution

  • I see a couple of problems with your first rule:

    1. The rule probably isn't matching, because the REQUEST_URI is /abc, not abc.
    2. If the rule were matching, you'd have an infinite redirect loop, leading to a 500 Internal Server Error to the client, and a "Redirect limit exceeded" error in your logs. The problem is that the rule target is identical to the original request, so it will enter a redirect loop.

    I suggest getting rid of the first rule, and adding the /abc exclusion to the second rule:

    RewriteEngine On
    
    RewriteCond %{HTTPS} off
    RewriteCond %{REQUEST_URI} !^/abc$ [NC]
    RewriteRule $ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]
    

    If you also want to force /abc to be on HTTP and not HTTPS, then you could add a second rule:

    RewriteCond %{HTTPS} on
    RewriteCond %{REQUEST_URI} ^/abc$ [NC]
    RewriteRule $ http://%{HTTP_HOST}%{REQUEST_URI} [L,R]