htaccess to 404
April 13, 2011 8:49 AM   Subscribe

.htaccess rule to direct results to 404 page.

I run a cms that returns results based on a templating system. It will return content pretty much with any URL parsed through it. I'd like to direct blatantly false results to a 404.


Basically I want to have only "safe" URL structures go ahead and give results.

example.com/segment1/segment2/post

So anything past the above is invalid. So example.com/segment1/segment2/segment3/post would redirect, but example.com/segment1/post would not. example.com/post would not. example.com would not.

I want three valid URL segments past the domain and that's it.

Bonus for syntax to exempt a URL structure from the above rule.

So example.com/blueberry/pancakes/syrup/post which would normally trip the rule I've specifically exempted (I can't think of a reason I'd need to do this, but would like the option).
posted by cjorgensen to Computers & Internet (2 answers total)
 
Assuming you are on a recent version of Apache, the syntax you want is:

RedirectMatch 404 [pattern]

where [pattern] is a regular expression that my margin is to small to contain. See the Apache docs on mod_alias (redirect rules).

If RedirectMatch isn't powerful enough, take a look at mod_rewrite.

For the bonus question: either your regex will have to exclude the valid URL patterns, or you will have to create another rule to catch them that executes first. For RedirectMatch, the order of processing goes first to last, so put your more specific rule first. For mod_rewrite rules, you'll also have to specify that you want to stop processing after that rule is matched, which you do by adding an L flag.
posted by expialidocious at 10:20 AM on April 13, 2011


Response by poster: Well, that was helpful for another reason. I didn't realize that there was a parse order to the rules. This explains why one of my rewrites wasn't working.

I haven't done anything with RegEx before. So I'm not quite following what your saying I need in the [pattern].
posted by cjorgensen at 6:41 PM on April 13, 2011


« Older Need a Better iPhone Protection Solution   |   How can I find discrete geographic areas around... Newer »
This thread is closed to new comments.