...

Tuesday, July 20, 2010

Misc 42

Now I'll touch up a little on our apache2 knowledge. Remember how we set up SSL over HTTP (HTTPS) in this article? Now, what if we decide that we want to force users accessing through HTTP into using SSL as well?
This short article would briefly describe a mod in apache2 known as mod_rewrite. mod_rewrite is an advanced, extremely comprehensive URI rewriting mod that works with REGEXP.

We'll now pick up where we ended in that article, where our server has both port 80 and port 443 access. Now, we'll want to first enable the rewriting mod, so we'll type:
a2enmod mod_rewrite

Next, we'll want to access the 000default file found in sites-enabled so that we can directly affect port 80 connections. We'll modify it so that we have:
<VirtualHost *:80>
RewriteEngine on
RewriteCond %{SERVER_PORT} 80
RewriteRule ^{.*}$ https://%{SERVER_NAME}/$1 [L,R]
</VirtualHost>


First of all, RewriteEngine tells the server to turn on the mod_rewrite engine at that point. Next, the RewriteCond specifies the condition in which rewriting would trigger. The condition here is that the SERVER_PORT variable, specified using the %{} symbols, be 80.

Now I'll move on to the RewriteRule. ^{.*}$ simply means starting with anything. How we read this is that ^ starting with, and $ stands for ending with. If you start and end with something, then you're doing an exact match. Here, we're matching for .* which is anything.

Once matched, the rewriting will substitute the SERVER_NAME into the URL. SERVER_NAME is substituted with whatever the host references the server with (either IP, or domain name). Finally, the [L,R] represent flags, with L meaning to stop at this rewrite, and R means to redirect.

No comments :

Post a Comment

<