自建gitea仓库后,为提高网站速度以及充分利用gitea仓库,故将网站资源镜像到仓库。

在网站请求仓库资源时,被浏览器corb(Cross-Origin-Read-Blocking)。

需要从两个方向解决此问题,允许空请求头跨域以及正确配置mime type。

正确设置跨域

在gitea的配置文件app.ini中添加如下代码

[cors]
ENABLED = true
ALLOW_DOMAIN = *

并且nginx反代配置文件应该做如下编写来允许空请求头跨域

server {
    ...#location外的自己配置,主要是location内的内容
    location / {
        client_max_body_size 512M;
        proxy_pass http://localhost:3000; # 假设 Gitea 运行在 localhost:3000
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
        add_header 'Access-Control-Allow-Credentials' 'true';
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }
    }
}

正确设置mime type

由于浏览器会阻止mime type不匹配的资源的加载,翻阅gitea官方配置文件文档,只需要正确设置mime type就可以解决corb问题。

app.ini中添加如下代码

[repository.mimetype_mapping]
.js = text/javascript
.css = text/css
.woff = font/woff
.woff2 = font/woff2
.ttf = font/ttf

其中.xxx是要请求资源的扩展名,xxxx/xxxx是mime type,可以在这里查阅相关扩展名的mime type。