Skip to content

Commit

Permalink
Redirect old % URLs to new - encoded URLs, closes #1650
Browse files Browse the repository at this point in the history
Refs #1439
  • Loading branch information
simonw committed Mar 7, 2022
1 parent 1baa030 commit 644d25d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
7 changes: 7 additions & 0 deletions datasette/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1211,6 +1211,13 @@ async def route_path(self, scope, receive, send, path):
return await self.handle_404(request, send)

async def handle_404(self, request, send, exception=None):
# If path contains % encoding, redirect to dash encoding
if "%" in request.path:
# Try the same path but with "%" replaced by "-"
# and "-" replaced with "-2D"
new_path = request.path.replace("-", "-2D").replace("%", "-")
await asgi_send_redirect(send, new_path)
return
# If URL has a trailing slash, redirect to URL without it
path = request.scope.get(
"raw_path", request.scope["path"].encode("utf8")
Expand Down
6 changes: 6 additions & 0 deletions tests/test_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -952,3 +952,9 @@ def test_no_alternate_url_json(app_client, path):
assert (
'<link rel="alternate" type="application/json+datasette"' not in response.text
)


def test_redirect_percent_encoding_to_dash_encoding(app_client):
response = app_client.get("/fivethirtyeight/twitter-ratio%2Fsenators")
assert response.status == 302
assert response.headers["location"] == "/fivethirtyeight/twitter-2Dratio-2Fsenators"

0 comments on commit 644d25d

Please sign in to comment.