Apache Rewrite: Do Not Redirect For A Certain Port Using RewriteCond

This seems to be the week of the Rewrite Engine for me as this is the second semi unique modification I have needed to make to one of our servers rewrite rule sets. This time we have a site where all traffic destined for HTTP is redirected to HTTPS via the LiteSpeed Rewrite Engine. Currently there are no exceptions to this rule on the server except if you are already visiting HTTPS you obviously do not get redirected to HTTPS. So a description of the project along with the necessary syntax to exclude certain ports from your rewrite rule set are below.

Rewrite Rule Set: Skip Rewrite For Certain Specific Ports

One of the developers that works on the development server I was configuring this on had requested that the debug-ruby gem and the mongrel gem be installed. This would allow him to debug Ruby in real time from the CLI using the below syntax.

Debug Ruby From A Shell In Real Time Using The Ruby-Debug Gem:

ruby script/server --debugger -p 3000

So once the ruby-debug and mongrel gem are installed properly the above syntax from the root of a Ruby project will launch that project in debug mode from a console that is outputting the data sent to Mongrel on port 3000. The problem is since the server is off site to hit port 3000 you have to use the public interface of the server where all HTTP requests are being redirected to HTTPS which will cause an error because Mongrel is not configured for SSL. So what we need to do is modify our Rewrite Rules to redirect everything except for any HTTP requests coming in on port 3000 and in our case we specified ports 3000 to 3003 so multiple developers could launch debug consoles at the same time. Below is our current Rewrite Rule set in Litespeed followed by the addition of the exclude rules in the form of RewriteCond statements.

LiteSpeed Rewrite Rule Set To Redirect All HTTP Traffic to HTTPS:

rewriteCond %{HTTPS} !on
rewriteCond %{HTTP:X-Forwarded-Proto} !https
rewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Rewrite Rule: Redirect HTTP Traffic to HTTPS Excluding HTTP Traffic On Ports 3000 to 3002:

rewriteCond %{HTTPS} !on
RewriteCond %{SERVER_PORT} !^3000$
RewriteCond %{SERVER_PORT} !^3001$
RewriteCond %{SERVER_PORT} !^3002$
RewriteCond %{SERVER_PORT} !^3003$
rewriteCond %{HTTP:X-Forwarded-Proto} !https
rewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

As you can see you could easily modify the port if you need to exclude a different port. You could also easily add multiple ports as shown in the above Rewrite Rule set. Once you modify the Rewrite Rules make sure to gracefully restart Litespeed or Apache for the changes to take place.

Apache Cookbook: Solutions and Examples for Apache Administrators (Paperback)

List Price: $34.99 USD
New From: $16.84 USD In Stock
Used from: $4.01 USD In Stock