Redirect All Requests for a Nonexistent File to the Actual File

Published Tuesday, August 12, 2008 @ 11:47 pm • 21 Responses

In my previous article on redirecting 404 requests for favicon files, I presented an HTAccess technique for redirecting all requests for nonexistent favicon.ico files to the actual file located in the site’s web-accessible root directory:

# REDIRECT FAVICONZ
<ifmodule mod_rewrite.c>
 RewriteCond %{THE_REQUEST} favicon.ico [NC]
 RewriteRule (.*) http://domain.tld/favicon.ico [R=301,L] 
</ifmodule>

As discussed in the article, this code is already in effect here at Perishable Press, as may be seen by clicking on any of the following links:

Clearly, none of these URL requests target the “real” favicon.ico file, yet thanks to the previous method they are all happily redirected to the proper location. This is useful for a variety of reasons, including preventing excessive and unnecessary server strain due to malicious scripts.

Shortly after posting this method, Chris Coyier of CSS Tricks discovered that the code was causing an infinite redirection loop when applied to his site. After some experimentation, I have resolved the infinite loop issue, improved the syntax, and adapted the code to work from virtually any location.

The previous favicon redirection method works as advertised, but only if placed in a subdirectory, such as would be the case for WordPress installations located in their own non-root directory. For example, this WordPress installation for Perishable Press is located in a subdirectory named “press”. Within the HTAccess for the press subdirectory, the first version of this redirection technique works perfectly. When placed in the root directory, however, the code fails by creating the infinite loop. Thus, a better solution is needed..

Universal Redirect for Nonexistent Files

The following technique works in any directory — subdirectory or site root:

# REDIRECT 404 FILES
<ifmodule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{REQUEST_URI} !^/favicon\.ico [NC]
 RewriteCond %{REQUEST_URI} favicon\.ico [NC]
 RewriteRule (.*) http://domain.tld/favicon.ico [R=301,L] 
</ifmodule>

To implement this technique, replace both instances of “favicon.ico” with any file that you would like to redirect. The favicon is a good a choice for reasons discussed in the previous article, but other good candidates would be your site’s robots.txt file or any other file that seems impossible for people and bots to find. Further, if the location of the “real” file is located somewhere other than the root directory, indicate such in the first RewriteCond (e.g., !^/images/favicon\.ico). Then, after the rewrite conditions are taken care of, edit the RewriteRule to reflect the full URL of the actual file.

A couple of notes.. First, it is recommended that you place this code as far up the directory structure as possible. Begin with the site root HTAccess file. In most configurations, that should work fine; however, in some cases, such as when WordPress is installed in a subdirectory but is serving permalinks written without the subdirectory showing in the URL, the redirect may simply not happen. If this is the case, or if the redirect does not occur for some other reason (conflicting rewrite rules, etc.), try placing the code in the subdirectory. Bottom line: place the code in the root HTAccess and if the redirects don’t kick in, place the code in the blog subdirectory. The good news here, and the main reason for this improved method, is that the code will no longer trigger an infinite loop and crash your site; it is much safer, much cleaner, and more widely applicable.

Having bored you to tears with all of that detail, allow me to deliver the death blow with an explanation as to what’s actually happening when this code is executed. I think a nice, numbered list will help simplify the process:

  1. Check for the required Apache module, mod_rewrite
  2. Enable rewriting by activating the RewriteEngine
  3. Check if the requested URI is the actual file
  4. Match any nonexistent URI that contains the target file
  5. Redirect any matching URI to the actual file
  6. Close the module check container

Conclusion

Hopefully, this technique will be useful for anyone needing to stop those relentless 404 requests for nonexistent files. Doing so will not only help increase the effectiveness of your error-log investigations, but also help reduce the unwanted server load associated with automated directory prowling via arbitrary file candidates. Or something ;)


Dialogue

21 Responses Jump to comment form

1Louis

August 13, 2008 at 2:21 am

I wonder if it’s a good idea to redirect the request to the favicon. That won’t make the automatic requests stop, and that will burn some bandwidth that would not have been burned if you just ignore the request.

My point would be that your idea is cleaner, but will waste ressources :/

2Jeff Starr

August 13, 2008 at 9:42 am

Let’s think this through. With the rewrite rule in place, all requests for favicon.ico require a redirect and an image request. Without the rewrite rule in place, the htaccess file is still parsed yet instead of an image, a web page is served. Which of these cases consumes more resources? I don’t know for sure, but if I remember correctly, servers deliver images at much lower cost than web documents. It also may depend on the size of the image or file being requested. Favicons and robots.txt files are pretty small, but larger files would likely have a greater impact on performance.

3IMaggie

August 14, 2008 at 1:08 pm

I am pretty new to this, exactly where do I put the script. Is in the htaccess file?

4Jeff Starr

August 17, 2008 at 7:06 am

Hi IMaggie, technically the code presented in the article is not a script, but yes, if you are planning on using it, you would place it in an htaccess file, as described in the post itself. I hope that helps :)

5play games

August 24, 2008 at 3:15 pm

Great Work Perishable

I’ve customised your code to meet my specific reqs, namely to protect against hotlinkers linking directly to my content.

RewriteCond %{HTTP_REFERER} xx\.xxxxx\.com [NC,OR]
RewriteCond %{HTTP_REFERER} xxxxx\.org [NC]
RewriteRule \.(swf)$ redirect.swf [NC,L]

If you were in the UK I’d buy you a beer.

6Jeff Starr

September 1, 2008 at 9:29 am

Thanks for the feedback — I’ll be taking you up on that beer next time I’m in the UK! ;)

7htaccess redirect

September 11, 2008 at 7:37 pm

I was looking for this rewrite code for Wordpress for quite awhile, couldn’t get it to work myself. Thanks!

8Piller

September 17, 2008 at 3:46 pm

Hello,

I am having some trouble redirecting URL on my site. I used Expression Engine to mount it, and suddenly something happened and this kind of redirectioning are not working anymore:

http://loscuchillos.com/letras should go to http://loscuchillos.com/index.php/letras

So, what I basically need to perform is an automatic redirection to /index.php/NAME of whatever NAME typed as a subfolder. Without showing the whole address.

So the code the Expression Engine provides to get this kind of redirectioning (http://expressionengine.com/wiki/Remove_index.php_From_URLs/) is not working anymore.

It was working before and now I wounder what could be wrong.

Rewrite Module is enabled, same as .httaccess

Is there anythins else I should consider?

I’d really appreciate any comments on this issue.

Thanks,

Piller

9Gabriel H.

September 28, 2008 at 12:32 am

Hello,

Be careful with the redirection, you can have an infinite loop.

To avoid that, you can rename the favicon.ico file by something else.

Eg :

RewriteCond %{THE_REQUEST} favicon.ico [NC]
RewriteRule (.*) /favicon_all.ico [R=301,L]

If I don’t do this, I get infinite redirections…

10Jeff Starr

September 28, 2008 at 8:01 am

Hi Gabriel, I am wondering if you read the entire article, or happened to copy & paste that first chunk of code. The reason I say this is because this article is essentially about preventing infinite loops. The htaccess code presented at the beginning of the article was given in a previous article and may indeed cause infinite loops, which is precisely why I wrote this article. If you read through, you will see that the infinite loop issue is resolved with a new and improved version of the code. I know of at least several sites that use the technique with no problems whatsoever. With the proper technique there should be no need to rename any files. I hope this helps!

11Gabriel H.

September 28, 2008 at 7:27 pm

Hello Jeff Starr,

My apologies, you are right, I didn’t read the whole article and just copy-pasted blindly the code… Now that works much better with the new code ;)

Have a nice day.

12JK

December 20, 2008 at 6:17 am

Hi Jeff,

First of all, you have a great site.

I too get tons of 404s with favicon.ico missing like your example post URLs from your site shown above. I followed your steps and read several times to get this correct. For some reason, the redirect does not happen at all. Let me explain further on my site configuration.

I have the main site in the root directory which is not blog (plain static site). In the sub-directory I have a blog with it’s own domain name. So I have a .htaccess file specifc to my blog in this sub-directory. Currently that’s where I have all rewrite commands. So I added your rewrite commands to this file towards the bottom. Still I get 404s for favicon.ico & .gif files.

What am I missing?

Thanks for your help.

13JK

December 20, 2008 at 6:41 am

Ok. I found the problem.

The set of lines that you suggested to be in put in .htaccess file should go all the way to the top of the file - only then it kicks in. Otherwise it has been ignored.

Thanks.

14Jeff Starr

December 21, 2008 at 9:49 am

@JK: yes, that may be the case, depending on the contents of your htaccess file(s), it might be necessary to arrange the various rewrite rules in such a way as to avoid potential conflicts. In any case, I am glad to hear you got it working! :)

15Kalle

December 29, 2008 at 2:48 am

I just discovered all these favicon 404’s after installing CyStats. Rather annoying. Thanks for the code, it seems to help. But what ARE all these 404’s? Who or what is looking for my favicon in all possible places, and above all - why??

16Jeff Starr

January 1, 2009 at 9:51 am

Hi Kalle, Glad to hear the method is helping you. I recently participated in a comment thread over at CSS Tricks that discusses the technique in greater detail and even gets into “why” these types of requests occur in the first place. Check it out at:

http://css-tricks.com/weird-file-requests-and-easing-server-stress-with-htaccess/

17Jeff

April 5, 2009 at 11:12 pm

Thanks so much!!! This saved my butt. I was hit with this problem in the worst way and this completely cleared it up in 5 minutes.

18Jeff Starr

April 6, 2009 at 12:26 pm

Happy to help, Jeff — Thanks for the positive feedback! :)

Subscribe to comments on this post


[ Comments are closed for this post. ]

If you have additional information, contact me.

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

heading out of town on a photographic excursion. great way to break up the routine.

Perishable on Tumblr

Office painted a warmish/neutral off-white color. New 2.1...

Tue, 02 Feb 2010


New office digs..


Night view..


Potential..

Office painted a warmish/neutral off-white color. New 2.1 Altec/Lansing speakers for crisp, clear sound. Two new executive desks: one for computer biz and another workspace for drawing, painting, and other offline pursuits. And of course, a big, cushy black office chair to make it all sweet.

Quick Photoshop Reset

Tue, 19 Jan 2010

Very good Photoshop trick to know: If you hold down ALT+CTRL+SHIFT (Mac: CMD+OPT+SHIFT) while starting Photoshop you can reset all settings back to factory default. Very useful if you have problems with some tools or the interface. – http://bit.ly/4A5LJ5

Insane October

Sun, 01 Nov 2009

By far the most insane month of 2009, October included the following activities:

1st week: Trip to the East Coast, beginning with some business in Connecticut.

2nd week: East Coast trip continues with much pleasure in downtown Manhattan.

3rd week: Photo and art excursions with good friend visiting from Portland, OR.

4th week: Marathon book-editing and fine-tuning for Digging into WordPress.

Now that November is here, things remain busy, but I am hoping to get a chance to restore some balance and regain my equilibrium. Of course, the holidays are right around the corner..

Import Feeds to Facebook

Mon, 07 Sep 2009

Seems like a lot of misinformation and confusion out there on how to import and display your feeds on Facebook. Here is what worked for me:

1. In the lower left-hand corner of your Facebook account, click on “Applications” > “Notes”.

2. In the upper mid-right column, click on “Import a blog” in the “Notes Settings” panel.

3. In the “Import an External Blog” panel, enter your feed URL and check the little box.

4. Click the “Start importing” button and then click on “Confirm Import” on the preview page.

That’s all there is to it. Don’t forget to edit your “Notes Privacy” settings to ensure that people can see and comment on your imported feed items.

Once you successfully import your feed(s), they will appear by clicking on the “Notes” button in the left sidebar of your Home page. Also, your timeline or “Wall” will also display the most recent post from each of your feeds as they are published and pulled into Facebook. This makes it easy for your “Friends” to see what you have been up to elsewhere on the Web.

help me in plain english

Mon, 31 Aug 2009

This has got to be the most ironic comment I have ever read:

“hi i dun a stupid noooby mistake and dint think about encrytion i just put a pass in the change pass box and now when i attempt to see my main.php or index.php its sayin password no and error how can i reset back to having no password or were can i edit the bit so that a pass is automattically seen or if not posable how can i make it so i can put in the pass i made at some point so i can login this way? the 3rd is most prefered as this will help me with other projects i am planning as i am a php noob :s plz sum1 hu is clever help me in plain english”

Thanks, “jay” — you made my week with that one.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • kn33ch41: "But for good browsers such as Opera and Safari, most users are quite savvy, understanding the game and always keeping their browsers...
  • Paul: First off great list. Probably the one of the best I've ever seen. I enjoyed your limiting of The Wall, and Dark Side of the Moon. He...
  • kn33ch41: I use method three, and use method four when a selector only requires one property....
  • r-a-y: Great code. Just wondering if, in certain scenarios, a permalink can be longer than 255 characters. I can think of a weird exam...
  • Jeff Starr: Thanks Oliver! Glad you enjoy the book. Thanks for the great feedback :)...
  • Perry: I've read a number of these Image Preloading techniques today and would like to know the best approach to use. I use PHP 5.3 on th...
  • Infographiste PAO: I didn't know that Jeff, that's a kind of great news, usually ppl don't know about no or dofollow so now it's gonna be alright withou...
  • Bill Brown: @Jakub: Of course, there are many ways to bypass the XML declaration issue when you have PHP short tags enabled. Since the intenti...
  • bucabay: AT Jakub ...
  • Jakub Lédl: Oh sh*t, I came back. What happened to that code I posted? Does this CMS remove PHP from comments or what? I now look like an idiot :...

Read more recent comments..

Attention: Do NOT follow this link!