WordPress and .htaccess

Having installed a number of WordPress blogs lately, one thing I frequently find myself doing after a new installation is editing the .htaccess file. What is .htaccess all about?

On an Apache server, .htaccess files allow you to make configuration changes to a directory (and its subdirectories); multiple .htaccess files can be present in your directory structure, with lower ones overriding higher rules where they conflict. They’re often used for access control, helping to keep the wrong people from poking around in your files. Today we’ll talk specifically about how they interact with WordPress.

Aside from the basic WordPress functions, I’ve mostly used the .htaccess file to force my webhost to use the correct version of PHP. My preferred host offers both PHP4 and PHP5, but defaults to PHP4; this tends to cause issues with WordPress plugins. The solution? Just add the following line to the .htaccess file in your WordPress directory (or a higher directory):

AddType x-mapp-php5 .php

This tells Apache to use PHP5 when interpreting a .php file, and all is well.  Of course, this assumes that your host actually has PHP5 installed; given that it’s been out since 2004, if your host doesn’t support it, it’s probably time to find a new host.

What else can we do with the .htaccess file? WordPress uses it to store the rewrite rules for permalinks. Be careful editing the .htaccess file that WordPress uses; if you put your code in the wrong place, it will be overwritten next time WordPress updates the file. I often prefer to simply go up a directory, where feasible.

Often the default amount of memory allocated for PHP is insufficient; you can increase it with the following line:

php_value memory_limit 64M

The above line is hopefully fairly self-explanatory;  other attributes you can set include upload_max_filesize and post_max_size, which often default to 2M each.

Host a site with a lot of photos? Find people stealing your bandwidth? Try this code:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+.)?mysite.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

Obviously, replace “mysite” with your own URL and “/images/nohotlink.jpg” with the image you want to display on the site that’s attempting to display your image. (Thanks to WPRecipies for this tip) You may want to host the second image on a different server to avoid the possibility that your host will get into an infinite loop.

Next time: using .htaccess to prevent spam.