I mentioned this in a post about jiggering Google and Multisite WordPress, and my buddy Jan went “WOW!” So I’ll start with the best thing ever in Apache, to me at least. Apache 2.4 allows for real if/else statements in .htaccess.

Benjamin Franklin's glasses - because revolution jokes are funny

In 2012, I wrote about how I did a lot of request header detection in order to make myriad blocks of checks to sort out my .htaccess anarchy. As I explained here, I have to do a check for the domain for each and every rewrite rule:

Why did I duplicate the RewriteCond? Typically, you cannot use multiple RewriteRule statements following a single RewriteCond. That means for ever call I make to a domain, I can use but one rewrite rule. There are ways around that, but none of them worked well for me.

It’s ugly on Apache 2.2. Since that time, however, I’ve moved to Apache 2.4, and the world is vastly different thanks to If/Else calls!

Let’s take this old section I had from my move (about 6 years ago) from blog.ipstenu.org to ipstenu.org, as well as some permalink changes and a change to my uploads folder:

# Ipstenu Moves
RewriteCond %{HTTP_HOST} ^blog\.ipstenu\.org
RewriteRule ^(.*) https://ipstenu.org/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^ipstenu\.org
RewriteRule ^blog/([0-9]{4})/([0-9]{2})/(.*)$ https://ipstenu.org/$1/$3 [L,R=301]
RewriteCond %{HTTP_HOST} ^ipstenu\.org
RewriteRule ^blog/(.*)$ https://ipstenu.org/$1 [L,R=301]

Taking each block at a time, the first was easy:

<If "%{HTTP_HOST} == 'blog.ipstenu.org'">
    RewriteRule ^(.*) https://ipstenu.org/$1 [L,R=301]

Pretty simple. If the host is blog.ipstenu.org, redirect. And it mostly worked. Except where http://blog.ipstenu.org/dsfasfsdf sent me to https://ipstenu.org/home/ipstenu/public_html/dsfasfsdf … Which isn’t good! The fix here is that you use RedirectMatch instead of RewriteRule, which gives us this!

<If "%{HTTP_HOST} == 'blog.ipstenu.org'">
	RedirectMatch (.*) https://ipstenu.org$1

Excellent, then on the second one which becomes this:

<If "%{HTTP_HOST} == 'ipstenu.org' ">
	RedirectMatch ^/blog/([0-9]{4})/([0-9]{2})/(.*) https://ipstenu.org/$1/$3
	RedirectMatch ^/blog/(.*) https://ipstenu.org/$1

What’s the difference here? Well, RewriteRule is handled by Apache’s mod_rewrite, while Redirect is handled by mod_alias. I know I have mod_rewrite on, but I don’t know why it insists on tossing in the path statement.

However I can assure you that these ifs work perfectly. I’m using them right here on this site. My whole .htaccess is wrapped with them.

Reader Interactions


  1. Thanks! This looks awesome!

    I look forward to testing it with my network… I’ve been struggling with htaccess lately and am building a nice library of code examples. Thanks again 🙂

    Kind Regards, Max

%d bloggers like this: