WordPress multisite – a rewrite infinite loop bug

When I created my new home page I used WordPress multisite feature. By the way, I noticed an interesting bug. When I try to view a non-existent image from wp-content directory, the server returns an error with code 500 instead of 404. At first I thought it was a problem with hosting, but it turned out to be a bug in the default configuration of .htaccess for WordPress running as a multisite with path-based network. It looks like this:

The problem exist in two marked lines. They make all the addresses to files like http://rob006.net/en/wp-content/file.jpg treated as http://rob006.net/wp-content/file.jpg. The expression ([_0-9a-zA-Z-]+/)? is responsible for handling prefixes for sub-directories, but the problem is a ? at the end. It makes the prefix optional, so if the http://rob006.net/wp-content/file.jpg file does not exist, server is trying to internal redirect request to http://rob006.net/wp-content/file.jpg (yes, exactly the same address). Since there is no such file, server search rewrite rules again, find the same rule as before and try performs it again. That creates a redirect loop that causes the error 500. Then in the logs you can find these entries:

The solution is to remove ? sign from these rules.

TL;DR

Correct content of .htaccess file looks like that:

 

3 responses to “WordPress multisite – a rewrite infinite loop bug

  1. Amazing, thank you very much Robert for this post – it helps me alot!
    I have searched for the answer more than 5 hours all over the internet and tried almost everything, and only your decision worked – like charm. 🙂
    By the way, I get this error on my multisite platform only when enabled https (ssl certificate). Without ssl, even with using “?” symbol I didn’t have problems.

  2. Does removing those question marks make the subdirectory site more vulnerable for database injections? How safe is to use this method? I am very hesitant about this. If you could me advice I would be very thankful. With kind regards

    1. It is 100% safe. Rewrite rules are not related to database interactions, so there is no way it could create SQL Injection. The only result of this change is that URLs that previously created infinite loop (and 500 response code) now throws Not found error, so it is more efficient and semantically correct.

Leave a Reply

Your email address will not be published.