服务器与本地资源同步,在ubuntu自建git库,使用nginx远程http访问

xshell在linux与windows之间传文件虽然方便,但使用git才能真正实现资源同步。

为实现服务器与本地资源同步,在ubuntu服务器端自建git库。

使用 git-http-backend 搭建 git 服务的原理都是类似的, 主要是利用 web 服务器 (apache/nginx) 进行用户认证, 并将用户信息传递给 CGI 程序 git-http-backend , 从而实现通过 http 完成 git 操作。nginx自带的FastCGI。

1、版本

本地:windows

服务器:腾讯云轻量服务器 ubuntu20.04

2、参考

git 官方使用手册 https://git-scm.com/book/en/v2

网友分享 https://beginor.github.io/2016/03/12/http-git-server-on-nginx.html

3、接下来开始傻瓜式操作

4、安装git

(1)ubuntu中安装稳定版本中的最新版 sudo apt-get install git

(2)windows 10 中安装git https://git-scm.com/download/win  运行下载下来的*.exe,我是一直直接 ”下一步“ 的

(3)git 和 git for windows 分别是两个项目

(4)设置当前系统用户操作 git 的用户名和邮箱

git config --global user.name "someone's name"
git config --global user.email someone@gmail.com

5、创建自己的git库

(1)cd 到要创建版本控制的文件所在的目录,假设该目录在 /home/test

(2)执行 git init ,立马就会在当前目录下创建一个空的 git 库

(3)将当前目录下所有文件和目录加入该库,提交第一个版本

git add *
git commit -m 'Initial project version'

6、重点来了,如何使本地 windows 10 可以访问到 ubuntu 上的 git库呢?

我将使用 git 版本 1.6.6 之后支持的 Smart HTTP 协议来建立服务器 git 库的对外服务。

(1)cd /home

(2)git clone --bare test test.git  从 test 目录克隆需要的 .git,不携带工作目录

(3)将 test.git 放到单独的目录 /home/mygit 中,作为服务仓库的存在,注意!!!不携带 test 目录中的工作目录!!!

mkdir /home/mygit

mv test.git /home/mygit

chown -R www-data:www-data /home/mygit  将 /home/mygit 及其目录下文件的所有者更改为 www-data ,否则 git push 会失败,因为 git 和 nginx 使用的是 www-data,不这么做的话,git push 会出现的错误是:

【error: remote unpack failed: unable to create temporary object directory
To http://我的IP地址/git/test.git
! [remote rejected] master -> master (unpacker error)
error: failed to push some refs to 'http://我的IP地址/git/test.git'】

(4)安装 fcgiwrap

apt install fcgiwrap

(5)修改nginx.conf

nginx.conf 可能在 /usr/local/nginx/conf, /etc/nginx, /usr/local/etc/nginx

我的在 /etc/nginx。

添加以下内容到 server 模块中(可以到该篇看如何安装和简易安装 nginx :https://www.cnblogs.com/fanyann/p/17500960.html)

# 配置以 /git 开始的虚拟目录
location ~ /git(/.*) {
# 使用 Basic 认证
auth_basic "Restricted";
# 认证的用户文件
auth_basic_user_file /etc/nginx/passwd; # /etc/nginx/passwd 稍后创建,别急!
# FastCGI 参数
fastcgi_pass unix:/var/run/fcgiwrap.socket;
fastcgi_param SCRIPT_FILENAME /usr/lib/git-core/git-http-backend;
fastcgi_param GIT_HTTP_EXPORT_ALL "";
# git 库在服务器上的根目录
fastcgi_param GIT_PROJECT_ROOT /home/mygit; #目录 /home/mygit 要根据你的实际仓库地址修改哦!
fastcgi_param PATH_INFO $1;
# 将认证用户信息传递给 fastcgi 程序
fastcgi_param REMOTE_USER $remote_user;
# 包涵默认的 fastcgi 参数;
include fastcgi_params;
# 将允许客户端 post 的最大值调整为 100 兆
client_max_body_size 100M;
}

(6)检查命令 htpasswd 是否存在,没有的话,执行 apt-get install apache2-utils 安装

(7)使用 htpasswd 创建远程http访问时需要输入的用户名及密码

htpasswd /etc/nginx/passwd userName

userName替换为你想要的名称,接着根据提示设定密码

(8)重启 nginx 执行 nginx -s reload

(9)使用 http 而不是 https;git clone 执行后输入(7)中设置的用户名及密码就能远程获取 test.git 库了

git clone http://服务器域名/git/test.git

git clone http://服务器IP地址:80/git/test.git  因为我使用的是 nginx 的默认端口80,所以这里必须指定端口为80,否则这条命令默认会访问 443 端口

 

posted @ 2023-06-25 23:40  范饭饭  阅读(147)  评论(0编辑  收藏  举报