Sub topic 5
Handling special characters and non-English text
This chapter assumes you can read basic Python and know what a slug is, as covered in the earlier chapters on URL anatomy and slug writing. It covers which characters belong in a slug, how browsers and servers encode the rest, and how to choose a strategy for titles written in other languages.
Which characters are safe in a slug
The URL standard (RFC 3986) splits characters into three groups.
| Group | Characters | Use in a slug |
|---|---|---|
| Unreserved | `a-z A-Z 0-9 - . _ ~` | Safe as they are |
| Reserved | `: / ? # [ ] @ ! $ & ' ( ) * + , ; =` | Each has a structural meaning, so avoid them |
| Everything else | spaces, quotes, `%`, accented letters, other scripts | Must be percent-encoded |
A reserved character inside a slug can change how the URL is parsed. A ? starts the query string, a # starts the fragment, and a / adds a path level. A title like "Why is my site slow?" must not become /why-is-my-site-slow?, because the server would see the path /why-is-my-site-slow and an empty query.
In practice, a slug should contain only lowercase letters, digits, and hyphens. Two further rules cover the remaining unreserved characters:
- Use hyphens, not underscores, as word separators. Google's documentation recommends hyphens because it treats them as word breaks.
- Avoid dots and tildes in slugs. They add nothing and can look like file extensions or home directories.
How percent-encoding works
Percent-encoding writes each byte of a character as % followed by two hexadecimal digits. A space becomes %20. Characters outside ASCII are first converted to UTF-8 bytes, and then each byte is encoded. The letter é is two bytes in UTF-8 (C3 A9), so it becomes %C3%A9.
from urllib.parse import quote, unquote
path = "/blog/café-guide"
encoded = quote(path, safe="/-")
print(encoded) # /blog/caf%C3%A9-guide
print(unquote(encoded)) # /blog/café-guideBrowsers usually show the decoded form in the address bar, so a visitor sees café-guide. When the URL is copied into an email, a spreadsheet, or a log file, the encoded form usually appears. Both forms refer to the same address. Search engines decode and compare the underlying characters.
Percent-encoding has a different meaning inside a query string, where + can stand for a space. In a path, a + is a literal plus sign. Do not use + as a word separator in slugs.
Two ways to handle non-English titles
Non-English titles raise a real design choice. Google states that non-ASCII characters in a URL path are acceptable when they are UTF-8 encoded, and that you should use words in the language of your readers. You have two main strategies.
- Transliterate to ASCII. Convert
Crème Brûléetocreme-brulee. The URL is short, easy to type, and never needs encoding. - Keep the native script. Use
руководство-по-слагамor東京-観光-ガイドas the slug. The URL is readable to your audience and encodes only when copied.
Use these criteria to decide:
- Audience. If searchers type queries in Cyrillic, Greek, or Thai, a native slug matches the language they use. For Latin-script languages with accents, transliteration is usually enough, since people often type queries without accents.
- Sharing and tooling. Encoded native slugs are long. Each Cyrillic letter takes six characters (
%D0%B0), so a 30-letter slug becomes about 180 characters. Some older tools, chat apps, and log processors handle this badly. - Consistency. Pick one strategy per language section of the site and apply it everywhere. Mixing them makes redirects and audits harder.
The domain name is a separate case. Internationalized domain names use Punycode (xn--...), not percent-encoding, and apply only to the host part of the URL. This chapter covers the path only.
A transliterating slug function
The slugify function from the earlier chapter works for simple accents but fails silently on some letters. Unicode decomposition (NFKD) splits é into e plus a combining accent, and the ascii step then drops the accent. Letters such as ß, ø, æ, and ł have no decomposition, so the ascii step deletes them whole. "Straße" would become strae.
This version fixes that with an explicit map, and it also handles titles that produce an empty slug:
import re
import unicodedata
TRANSLIT = {"ß": "ss", "æ": "ae", "œ": "oe", "ø": "o", "đ": "d", "ł": "l", "þ": "th"}
def slugify(title, max_length=60, fallback="page"):
text = title.lower()
for char, replacement in TRANSLIT.items():
text = text.replace(char, replacement)
# Decompose accented letters, then remove the combining marks
text = unicodedata.normalize("NFKD", text)
text = "".join(c for c in text if not unicodedata.combining(c))
text = text.encode("ascii", "ignore").decode("ascii")
text = re.sub(r"[^a-z0-9]+", "-", text).strip("-")
text = text[:max_length].rstrip("-")
return text or fallback
print(slugify("Straße & Café")) # strasse-cafe
print(slugify("你好")) # pageThe second call shows the main failure mode of ASCII-only slugs. A Chinese, Japanese, or Arabic title contains no ASCII letters, so everything is removed. A fallback such as page would make every such article collide on the same URL. In a real system, append a unique ID or a translated keyword, for example page-1042, and check for duplicates before saving.
Transliteration rules also depend on language. German ä is usually written ae, while Swedish and French treat it as a. The function above uses the language-neutral choice. If you publish in German, add ä, ö, and ü to the map with ae, oe, and ue, and apply the map before decomposition.
A native-script slug function
To keep the original script, you must decide which characters count as part of a word. A common mistake is to use the regular expression \w. In Python, \w does not match combining marks, so a Hindi word like हिंदी is split at its vowel signs. Checking Unicode categories avoids this:
import unicodedata
def unicode_slug(title):
text = unicodedata.normalize("NFC", title).lower()
# Keep letters (L), numbers (N), and combining marks (M); turn the rest into spaces
kept = [c if unicodedata.category(c)[0] in "LNM" else " " for c in text]
return "-".join("".join(kept).split())
print(unicode_slug("Руководство по слагам!")) # руководство-по-слагамScripts without word spaces, such as Chinese and Japanese, need a person or a language-aware tool to choose break points. A generic function keeps the whole title as one run, which is valid but may be long.
Normalization and case: duplicate URLs you did not intend
Unicode allows the same visible character to be stored in more than one way. The letter é can be one code point (NFC form) or e plus a combining accent (NFD form). The encoded URLs differ:
import unicodedata
from urllib.parse import quote
nfc = unicodedata.normalize("NFC", "é")
nfd = unicodedata.normalize("NFD", "é")
print(quote(nfc)) # %C3%A9
print(quote(nfd)) # e%CC%81A server treats these as two different paths. If your CMS stores NFC and a link written on a Mac or imported from a file uses NFD, the link can return a 404 or create a duplicate page. Normalize every slug to NFC when you create it, and normalize incoming paths the same way.
Two related rules prevent similar duplicates:
- Encode hex digits in uppercase.
%c3%a9and%C3%A9mean the same character in the standard, but string comparisons in some servers and tools treat them as different. Most libraries output uppercase, so follow them. - Keep paths lowercase. Paths are case-sensitive on most servers, so
/Cafe-Guideand/cafe-guidecan be two pages. Where case-insensitive duplicates already exist, use a 301 redirect or a canonical tag, as covered in the later chapters on stability and canonicalization.
Checking your work
Run a quick test before you publish a new slug rule:
- Feed the function titles with accents,
ß, symbols (&,?,#), emoji, and a title in another script. - Confirm that no output is empty, contains
%, or contains an uppercase letter (for ASCII strategy). - Confirm that two different titles never produce the same slug without a unique suffix.
- Open the resulting URL in a browser and in
curlto confirm the server returns 200 for the encoded form.
Exercise
A CMS generates slugs with title.encode("ascii", "ignore") after NFKD normalization. Describe two kinds of titles that give wrong results, and name one fix for each.
Show answer
Titles with letters that have no Unicode decomposition, such as "Straße" or "Łódź guide", lose those letters silently ("strae"). Fix this with an explicit transliteration map such as ß to ss and ł to l. Titles written entirely in a non-Latin script, such as Chinese or Arabic, produce an empty slug. Fix this by keeping the native script in UTF-8, or by adding a fallback with a unique ID so different pages do not collide.
Exercise
Two links point to the same page. One href is /blog/caf%C3%A9-guide, the other is /blog/cafe%CC%81-guide, and both are visible as "café-guide" in a browser. Why might the second fail, and how do you prevent it?
Show answer
The second link uses the decomposed (NFD) form of é, which is e plus a combining accent, so its bytes differ from the stored NFC path. The server compares bytes and may return a 404 or serve a duplicate. Prevent it by normalizing slugs to NFC when they are created and when incoming paths are processed, and by linking only to the canonical form.