Skip to content

Commit a93da62

Browse files
Maledongmarswong
authored andcommitted
[Fix] Make the redirectToEnglishUrl behaves properly for local debugging (#1715)
1 parent 30bd529 commit a93da62

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

server.js

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,28 +34,34 @@ const opts = {
3434
const locales = chokidar.watch(path.join(__dirname, 'locale'), opts)
3535
const layouts = chokidar.watch(path.join(__dirname, 'layouts'), opts)
3636
const statics = chokidar.watch(path.join(__dirname, 'static'), opts)
37+
const fs = require('fs')
38+
// Read all the langs under `locale`
39+
const SUPPORTED_LANGUAGES = new Set(fs.readdirSync(path.join(__dirname, 'locale')))
3740

3841
// Redirect mechanism meant as a fix for languages where some pages
3942
// have not been translated yet, therefore redirect to the english equivalent,
4043
// which isn't the correct language, but better than a 404-page
4144
function redirectToEnglishUrl (req, res) {
4245
return () => {
43-
// Union the Url to lower case (ignore the case sensitive)
44-
// E.g: `zh-cn` equals to `zh-CN`
45-
const url = req.url.toLowerCase()
46-
47-
const isAlreadyEnglish = url.startsWith('/en')
48-
const urlContainsLanguage = url.split('/').length > 2
49-
50-
if (isAlreadyEnglish || !urlContainsLanguage) {
51-
res.writeHead(404, 'Not found')
52-
return res.end()
46+
// Url should be case insensitive.(e.g: zh-CN = zh-cn),
47+
// So we should make a convert to the lower case and check the route values.
48+
let url = req.url.toLowerCase()
49+
const splitedValues = url.split('/')
50+
// For urls like `/blog`, add `en` before that
51+
if (splitedValues.length === 2) {
52+
splitedValues[0] = 'en'
53+
url = splitedValues.join('/').trim()
54+
} else if (splitedValues[1] !== 'en' && SUPPORTED_LANGUAGES.has(splitedValues[1])) {
55+
// For urls like `/lang/docs/`.
56+
// If we found the lang in our set, this means the specific lang
57+
// doesn't have proper translated pages yet, so force the default
58+
// lang to `en`.
59+
splitedValues[1] = 'en'
60+
url = splitedValues.join('/').trim()
5361
}
5462

55-
const englishUrl = url.replace(/^\/\w+\//, '/en/')
56-
5763
res.writeHead(302, {
58-
location: englishUrl
64+
location: url
5965
})
6066
res.end()
6167
}
@@ -93,6 +99,11 @@ statics.on('add', (filePath) => {
9399

94100
// Initializes the server and mounts it in the generated build directory.
95101
http.createServer((req, res) => {
102+
// If we are accessing the root, it should be redirected to `/en` instead.
103+
// We shouldn't get a 404 page.
104+
if (req.url === '/') {
105+
req.url = '/en'
106+
}
96107
mount(req, res, redirectToEnglishUrl(req, res))
97108
}).listen(port, () => console.log(`http://localhost:${port}/en/`))
98109

0 commit comments

Comments
 (0)