Large sites that need to protect their application use something called a Network IDS (Intrusion Detection System, also known as an IPS (Intrusion Prevention System) which can reject packets based on certain criteria (Source IP, behavior, fingerprint, etc). Many IDSes will allow you to drop a packet on the floor (e.g. no response at all), terminate a TCP/UDP session immediately, add you to a blackhole list, direct the session to a honeypot, etc. This topic can be extremely complicated and very interesting: Cisco and others sell expensive appliances to to this for you, some security admins spend their career doing this, etc. Large sites like Facebook, Twitter and Google have extremely complicated IDSes which do very interesting things.
An IDS is a device on the network level, not the application level. An application-level IDS is still subject to a number of other attacks such as DDOS, TCP & IP-level attacks, etc.
However, not everyone can implement a network IDS. At the Apache level, many people use mod_security as an Application-level IDS. By default, mod_security ships with the ability to protect a site from a number of common attacks already, and can be customized to do specific things that you want. mod_security can be run in 'Permissive mode' where it will warn about attacks and print what it thinks it should do, and 'blocking mode' where it will actively block perceived attacks. From their FAQ:
https://github.com/SpiderLabs/ModSecurity/wiki/ModSecurity-Frequently-Asked-Questions-%28FAQ%29#wiki-What_exactly_is_ModSecurity
ModSecurity™is an open source, free web application firewall (WAF)
Apache module. With over 70% of all attacks now carried out over the
web application level, organizations need all the help they can get in
making their systems secure. WAFs are deployed to establish an
external security layer that increases security, detects and prevents
attacks before they reach web applications. It provides protection
from a range of attacks against web applications and allows for HTTP
traffic monitoring and real-time analysis with little or no changes to
existing infrastructure.
Dropping a session at this level in the OSI stack is a bit clumsy, but some people do something close. See How to drop all requests using mod_security
mod_security is not always an easy prospect, but mod_rewrite can also get very complicated. mod_security does have a lot of documentation and experienced community of users to draw from.