.htaccess mod_rewrite Redirect Root / path to /blog directory
I've just setup an HTTP Redirect from www.philihp.com to www.philihp.com/blog. This makes it so people don't see my ugly project listing when they come here, they go right to the blog. I still wanted people to be able to go to the root path, though, because a lot of times whenever I put some small project, gizmo, or widget up, I'll just stuff it in a new directory from the root path. I settled on allowing only listing when the HTTP header value HTTP_REFERER begins with a path from my blog.
To replicate this again elsewhere, create an .htaccess
file in your root directory and put in it (or it if it exists, append to it) the following:
RewriteEngine on RewriteCond %{HTTP_REFERER} !^http://www.philihp.com/ [NC] RewriteRule ^$ /blog/ [R,L]
The first line turns mod_rewrite on. It's off by default to make serving static files very fast, but mod_rewrite is very fast, and we need it anyway, so turn it on. RewriteRules come in chunks, where every RewriteRule has the RewriteConditions that came immediately before applied to it. So the second and third lines come as a chunk, which reads "If the path is empty (i.e. root path), and the HTTP_REFERER[sic] variable does not (!
) begin (^
) with http://www.philihp.com/
, send the request to /blog/
. But wait, I have 2 flags, R
to Redirect instead of Forward, and L
because this is the Last rule we need to process for this request.
The bad thing about this practice is similar to the problem we used to have where HTML frames would break bookmarks. A user might go to the directory listing and bookmark it, but if they return, their HTTP_REFERER is different, and the redirect would trigger. But in my case, that's not a terribly terrible to the user.
It's not too difficult for a malicious attacker to craft their own HTTP_REFERER tag, so be careful depending on it for anything where security is a priority.