Table of Contents

如果你想让自己的 Git 仓库对外展示,除了使用类似 GitHub 的托管网站外,也可以自己建立一个基于网页的简易查看器,本文介绍如何搭建一个 GitWeb 服务器,并可透过 HTTP 协议对远端仓库进行 pull、push 等操作。实际使用时可以直接使用我封装好的 Docker Image 进行快速部署。

准备工作

安装依赖软件

  • git
  • gitweb:Git 自带 GitWeb 的 CGI 脚本
  • fcgiwrap:为 Nginx 提供 cgi 支持
apt-get install git gitweb fcgiwrap

架设 HTTP 协议的 Git 服务器

鉴权配置

使用 HTTP Basic authentication 对请求进行鉴权。

如配置文件存放位置为 /htpasswd

创建用户命令:htpasswd /htpasswd awesome-user

Nginx 及 FastCGI 配置

请求路由到3个位置:

  • 静态文件:针对 clone 操作的请求,直接读取裸仓库静态文件
  • git http backend:对仓库的操作的请求,如提交等操作
  • gitweb:处理网页查看器数据的请求
server {
    listen 80;
    listen [::]:80;
    server_name localhost;
    root /usr/share/gitweb;

    #auth_basic "Restricted";
    auth_basic_user_file /htpasswd;

    # static repo files for cloning over https
    location ~ ^.*\.git/objects/([0-9a-f]+/[0-9a-f]+|pack/pack-[0-9a-f]+.(pack|idx))$ {
        root /repos;
    }

    # requests that need to go to git-http-backend
    location ~ ^.*\.git/(HEAD|info/refs|objects/info/.*|git-(upload|receive)-pack)$ {
        root /repos;

        fastcgi_pass unix:/var/run/fcgiwrap.socket;
        fastcgi_param SCRIPT_FILENAME   /usr/lib/git-core/git-http-backend;
        fastcgi_param PATH_INFO         $uri;
        fastcgi_param GIT_PROJECT_ROOT  /repos;
        fastcgi_param GIT_HTTP_EXPORT_ALL "";
        fastcgi_param REMOTE_USER $remote_user;
        include fastcgi_params;
    }

    # send anything else to gitweb if it's not a real file
    try_files $uri @gitweb;
    location @gitweb {
        root /usr/share/gitweb;

        fastcgi_pass unix:/var/run/fcgiwrap.socket;
        fastcgi_param SCRIPT_FILENAME   /usr/share/gitweb/gitweb.cgi;
        fastcgi_param PATH_INFO         $uri;
        fastcgi_param GITWEB_CONFIG     /etc/gitweb.conf;
        include fastcgi_params;
    }
}

GitWeb

仓库位置 修改 /etc/gitweb.conf 为:

$projectroot = "/repos"

界面主题 网页主题资源存放在 /usr/share/gitweb/static,更换为 kogakure/gitweb-theme 可拥有更好体验

mv /usr/share/gitweb/static /usr/share/gitweb/static.bak
git clone https://github.com/kogakure/gitweb-theme.git /usr/share/gitweb/static

Docker 镜像使用

使用以下 docker-compose.yml 启动

version: '3'
services:
  gitweb:
    container_name: gitweb
    image: mzcabc/gitweb
    volumes:
      - ./repos:/repos  # 仓库位置
      # - ./htpasswd:/htpasswd  # 鉴权信息
      # - ./indextext.html:/indextext.html  # 首页自定义展示信息
    ports:
      - 80:80
    environment:
      - THEME=alternative    # default, alternative
      - HOST=direct          # direct, router

建立用户

docker exec -it gitweb addauth user pass

建立仓库

docker exec -it gitweb addrepo awesome-project

克隆仓库

git clone http://127.0.0.1:80/awesome-project.git

网页展示

GitWeb