Skip to content

Commit 5ade60f

Browse files
committed
Return plain text 404 for non-HTML requests
Checks the `Accept` header for 404 responses. If HTML is not preferred, a plain text 404 is returned, avoiding the `_default_404.sql` processing. HTML-preferring clients continue to receive the custom SQL-based 404 page.
1 parent 674da32 commit 5ade60f

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
- fixes an issue introduced in 0.35 where custom SQLite extension loading would not work.
88
- When an user requests a page that does not exist (and the site owner did not provide a custom 404.sql file), we now serve a nice visual 404 web page instead of the ugly textual message and the verbose log messages we used to have.
99
- ![screenshot 404](https://github.com/user-attachments/assets/02525f9e-91ec-4657-a70f-1b7990cbe25f)
10+
- still returns plain text 404 for non-HTML requests
1011

1112

1213
## v0.35.1

src/webserver/http.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -377,11 +377,21 @@ pub async fn main_handler(
377377
};
378378
match routing_action {
379379
NotFound => {
380-
let mut response =
381-
process_sql_request(&mut service_request, PathBuf::from("_default_404.sql"))
382-
.await?;
383-
*response.status_mut() = StatusCode::NOT_FOUND;
384-
Ok(response)
380+
let accept_header =
381+
header::Accept::parse(&service_request).unwrap_or(header::Accept::star());
382+
let prefers_html = accept_header.iter().any(|h| h.item.subtype() == "html");
383+
384+
if prefers_html {
385+
let mut response =
386+
process_sql_request(&mut service_request, PathBuf::from("_default_404.sql"))
387+
.await?;
388+
*response.status_mut() = StatusCode::NOT_FOUND;
389+
Ok(response)
390+
} else {
391+
Ok(HttpResponse::NotFound()
392+
.content_type(ContentType::plaintext())
393+
.body("404 Not Found\n"))
394+
}
385395
}
386396
Execute(path) => process_sql_request(&mut service_request, path).await,
387397
CustomNotFound(path) => {

tests/common/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ pub async fn get_request_to_with_data(
2424
Ok(test::TestRequest::get()
2525
.uri(path)
2626
.insert_header(ContentType::plaintext())
27+
.insert_header(header::Accept::html())
2728
.app_data(payload_config(&data))
2829
.app_data(form_config(&data))
2930
.app_data(data))

0 commit comments

Comments
 (0)