Преглед на файлове

增加 http 重定向功能;更新 cfworker 错误逻辑

zjcqoo преди 6 години
родител
ревизия
01680ce761
променени са 2 файла, в които са добавени 30 реда и са изтрити 13 реда
  1. 9 10
      cf-worker/index.js
  2. 21 3
      www.conf

+ 9 - 10
cf-worker/index.js

@@ -5,7 +5,7 @@
  */
 const ASSET_URL = 'https://zjcqoo.github.io'
 
-const JS_VER = 7
+const JS_VER = 8
 const MAX_RETRY = 1
 
 
@@ -22,14 +22,11 @@ const PREFLIGHT_INIT = {
 /**
  * @param {string} message
  * @param {number} status
+ * @param {any} headers
  */
-function makeRes(message, status) {
-  return new Response(message, {
-    status,
-    headers: {
-      'cache-control': 'no-cache'
-    }
-  })
+function makeRes(message, status = 200, headers = {}) {
+  headers['cache-control'] = 'no-cache'
+  return new Response(message, {status, headers})
 }
 
 
@@ -45,7 +42,7 @@ addEventListener('fetch', e => {
     ret = handler(req)
     break
   case '/works':
-    ret = makeRes('it works', 200)
+    ret = makeRes('it works')
     break
   default:
     // static files
@@ -190,7 +187,9 @@ async function proxy(urlObj, reqInit, acehOld, rawLen, retryTimes) {
           return proxy(urlObj, reqInit, acehOld, rawLen, retryTimes + 1)
         }
       }
-      return makeRes(`bad len (old: ${rawLen} new: ${newLen})`, 400)
+      return makeRes(`error`, 400, {
+        '--error': 'bad len:' + newLen
+      })
     }
 
     if (retryTimes > 1) {

+ 21 - 3
www.conf

@@ -16,13 +16,31 @@ error_page            404 = /404.html;
 location = /404.html {
   internal;
   root                ../www;
-}
 
-location = / {
-  rewrite             ^ /404.html;
+  # http 重定向到 https(忽略 localhost 或 IP 访问)
+  access_by_lua_block {
+    if ngx.var.scheme == 'https' then
+      return
+    end
+    local host = ngx.var.host
+    if host == 'localhost' then
+      return
+    end
+    if ngx.re.match(host, [[^\d+\.\d+\.\d+\.\d+$]]) then
+      return
+    end
+    local url = host .. ':8443' .. ngx.var.request_uri
+    ngx.redirect('https://' .. url, 301)
+  }
+
+  # 永久重定向申请: https://hstspreload.org/
+  more_set_headers
+    'strict-transport-security: max-age=99999999; includeSubDomains; preload'
+  ;
 }
 
 location / {
   access_log          logs/access.log log_www buffer=64k flush=1s;
   root                ../www;
+  index               404.html;
 }