Skip to content

Commit d8a9841

Browse files
Serve a better 404 page (#58)
* add the error stuff and redirect * original url header * get original url via header * add base url * optionally use header --------- Co-authored-by: evan <evanuxd@gmail.com>
1 parent f685a7c commit d8a9841

3 files changed

Lines changed: 22 additions & 2 deletions

File tree

modules/constants.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
11
import enum
22

3+
NOT_FOUND_HTML = """
4+
<h1>Url not found.</h1>
5+
6+
<p>The requested URL "{requested_url}" could not be found on this server.</p>
7+
8+
<p>Return to <a href="{base_url}">homepage</a></p>
9+
"""
10+
311
class HttpResponse(enum.Enum):
412

513
OK = (200, "success")
614
BAD_REQUEST = (400, "<h1>No URL was found in your request</h1>")
7-
NOT_FOUND = (404, "<h1>URL not found</h1>")
15+
NOT_FOUND = (404, NOT_FOUND_HTML)
816
CONFLICT = (409, "<h1>Alias already exists</h1>")
917
INVALID_ARGUMENT_EXCEPTION = (422, "<h1>Alias is invalid</h1>")
1018
INTERNAL_SERVER_ERROR = (500, "<h1>Internal server error</h1>")

nginx.conf

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ http {
1616
resolver 127.0.0.11 valid=15s;
1717
proxy_set_header Host $host;
1818
set $upstream http://app:8000;
19+
proxy_set_header X-Original-URL $http_x_original_url;
20+
proxy_set_header X-Base-URL $http_x_base_url;
1921
proxy_pass $upstream;
2022
rewrite /s/(.*) /find/$1 break;
2123
}
@@ -28,6 +30,8 @@ http {
2830
resolver 127.0.0.11 valid=15s;
2931
proxy_set_header Host $host;
3032
set $upstream http://app:8000;
33+
proxy_set_header X-Original-URL $http_x_original_url;
34+
proxy_set_header X-Base-URL $http_x_base_url;
3135
proxy_pass $upstream;
3236
rewrite /qr/(.*) /qr/$1 break;
3337
}

server.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,16 @@ async def qr(alias: str):
175175
@app.exception_handler(HTTPException)
176176
async def http_exception_handler(request, exc):
177177
status_code_enum = http_code_to_enum[exc.status_code]
178+
content = status_code_enum.content
179+
if status_code_enum == HttpResponse.NOT_FOUND:
180+
original_url = request.headers.get("x-original-url", request.url)
181+
base_url = request.headers.get("x-base-url", request.base_url)
182+
content = content.format(
183+
requested_url=str(original_url),
184+
base_url=str(base_url)
185+
)
178186
return HTMLResponse(
179-
content=status_code_enum.content, status_code=status_code_enum.code
187+
content=content, status_code=status_code_enum.code
180188
)
181189

182190

0 commit comments

Comments
 (0)