chaihongjun.me

docsify简单配置应用

docsify是一个很神奇的文档生成工具,利用markdown文档动态生成文档网站。与 GitBook 不同,它不会生成静态的 HTML 文件。相反,它会智能地加载并解析Markdown 文件,并将它们展示为一个网站。这里简要介绍一下一个实例,在官方配置的基础上增加一个手动切换主题的功能,官方文档(https://docsify.js.org/#/zh-cn/)。



  
    
    第三方API接口收集文档
    
    
    
    
    
    
    
    
  
  
    
                                                   

再在文档根目录创建sw.js文件,增强离线功能:

/* ===========================================================
 * docsify sw.js
 * ===========================================================
 * Copyright 2016 @huxpro
 * Licensed under Apache 2.0
 * Register service worker.
 * ========================================================== */

const RUNTIME = 'docsify'
const HOSTNAME_WHITELIST = [
  self.location.hostname,
  'fonts.gstatic.com',
  'fonts.googleapis.com',
  'cdn.jsdelivr.net',
  'cdn.staticfile.net'
]

// The Util Function to hack URLs of intercepted requests
const getFixedUrl = (req) => {
  var now = Date.now()
  var url = new URL(req.url)

  // 1. fixed http URL
  // Just keep syncing with location.protocol
  // fetch(httpURL) belongs to active mixed content.
  // And fetch(httpRequest) is not supported yet.
  url.protocol = self.location.protocol

  // 2. add query for caching-busting.
  // Github Pages served with Cache-Control: max-age=600
  // max-age on mutable content is error-prone, with SW life of bugs can even extend.
  // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string.
  // Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190
  if (url.hostname === self.location.hostname) {
    url.search += (url.search ? '&' : '?') + 'cache-bust=' + now
  }
  return url.href
}

/**
 *  @Lifecycle Activate
 *  New one activated when old isnt being used.
 *
 *  waitUntil(): activating ====> activated
 */
self.addEventListener('activate', event => {
  event.waitUntil(self.clients.claim())
})

/**
 *  @Functional Fetch
 *  All network requests are being intercepted here.
 *
 *  void respondWith(Promise r)
 */
self.addEventListener('fetch', event => {
       if (event.request.url.includes('/logout')) {
           return; // 跳过缓存
     }
  //
  // Skip some of cross-origin requests, like those for Google Analytics.
  if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) {
    // Stale-while-revalidate
    // similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale
    // Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1
    const cached = caches.match(event.request)
    const fixedUrl = getFixedUrl(event.request)
    const fetched = fetch(fixedUrl, { cache: 'no-store' })
    const fetchedCopy = fetched.then(resp => resp.clone())

    // Call respondWith() with whatever we get first.
    // If the fetch fails (e.g disconnected), wait for the cache.
    // If there’s nothing in cache, wait for the fetch.
    // If neither yields a response, return offline pages.
    event.respondWith(
      Promise.race([fetched.catch(_ => cached), cached])
        .then(resp => resp || fetched)
        .catch(_ => { /* eat any errors */ })
    )

    // Update the cache with the version we fetched (only for ok status)
    event.waitUntil(
      Promise.all([fetchedCopy, caches.open(RUNTIME)])
        .then(([response, cache]) => response.ok && cache.put(event.request, response))
        .catch(_ => { /* eat any errors */ })
    )
  }
})

因为配置了密码登陆,所以需要后端nginx配置一下:

yum install httpd-tools

htpasswd -c /etc/nginx/.htpasswd your_username

注意目录/etc/nginx要存在,your_username是账户,执行上述命令后,系统会提示你输入密码,并将其加密存储到 .htpasswd 文件中。

然后是具体的nginx配置,http段:

http{
# 其他配置
map $status $auth_realm {
    ~^4  "Restricted_$request_time";  # 动态生成 realm
  }

}

server段:

add_header Vary "Cookie,Authorization";  # 确保不同凭证得到不同缓存副本
add_header X-Content-Type-Options "nosniff";  # 阻止 MIME 类型嗅探

auth_basic $auth_realm;  # 使用动态 realm

location / {
    auth_basic "Restricted Access";  # 提示信息
    auth_basic_user_file /etc/nginx/.htpasswd;  # 密码文件路径
    
    if($arg_auth_required){
    
        return 401;
     }
   
    try_files $uri $uri/ /index.html;
  }

# 文档页面退出登录URL  
location = /logout {
    
    # 生成动态 realm 使浏览器认为这是新认证域
    # add_header WWW-Authenticate 'Basic realm="Restricted_$request_time"'; 

    # 强制清除认证缓存
   add_header WWW-Authenticate 'Basic realm="Restricted Area" charset="UTF-8"';
     add_header Cache-Control "no-cache, no-store, must-revalidate";
     add_header Pragma "no-cache";
     add_header Expires "0";

    # 清除浏览器数据(部分浏览器生效)
    add_header Clear-Site-Data '"cache", "storage"';

    # 返回 401 触发浏览器认证弹窗
    return 401; 
 
  }
  
 error_page 401 /401.html;
 
 location = /401.html{
   auth_basic off;  # 关键设置:确保错误页面不需要认证 
    internal;
 
 }


知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:柴宏俊»docsify简单配置应用