Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

handle-redirects.js 2.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  1. const patterns = require('../../lib/patterns')
  2. const { URL } = require('url')
  3. module.exports = async function handleRedirects (req, res, next) {
  4. // never redirect assets
  5. if (patterns.assetPaths.test(req.path)) return next()
  6. // blanket redirects for languageless homepage to English homepage
  7. if (req.path === '/') {
  8. return res.redirect(301, '/en')
  9. }
  10. // begin redirect handling
  11. let redirect = req.path
  12. let queryParams = req._parsedUrl.query
  13. // update old-style query params (#9467)
  14. // have to do this now because searchPath replacement changes the path as well as the query params
  15. if (queryParams) {
  16. queryParams = '?' + queryParams.replace('q=', 'query=')
  17. redirect = (redirect + queryParams).replace(patterns.searchPath, '$1')
  18. }
  19. // remove query params temporarily so we can find the path in the redirects object
  20. let redirectWithoutQueryParams = removeQueryParams(redirect)
  21. // look for a redirect in the global object
  22. // for example, given an incoming path /v3/activity/event_types
  23. // find /en/developers/webhooks-and-events/github-event-types
  24. redirectWithoutQueryParams = req.context.redirects[redirectWithoutQueryParams] || redirectWithoutQueryParams
  25. // add query params back in
  26. redirect = queryParams ? redirectWithoutQueryParams + queryParams : redirectWithoutQueryParams
  27. // do not redirect a path to itself
  28. // req._parsedUrl.path includes query params whereas req.path does not
  29. if (redirect === req._parsedUrl.path) return next()
  30. // do not redirect if the redirected page can't be found
  31. if (!req.context.pages[removeQueryParams(redirect)]) {
  32. // display error on the page in development, but not in production
  33. // include final full redirect path in the message
  34. if (process.env.NODE_ENV !== 'production' && req.context) {
  35. req.context.redirectNotFound = redirect
  36. }
  37. return next()
  38. }
  39. // do the redirect!
  40. return res.redirect(301, redirect)
  41. }
  42. function removeQueryParams (redirect) {
  43. return new URL(redirect, 'https://docs.github.com').pathname
  44. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...