当前位置:首页 > 行业动态 > 正文

https访问git服务器

需配置SSL证书并确保服务端监听443端口,客户端使用https://域名/路径

配置HTTPS访问Git服务器

前提条件

  1. 域名:需拥有公网域名(如无域名可使用IP+自签名证书)
  2. SSL证书
    • 免费方案:Let’s Encrypt(需公网访问80/443端口)
    • 自签名证书:适合内网环境
  3. Git服务器:已安装Git并配置好仓库

配置步骤

安装Web服务器(以Nginx为例)

# Ubuntu/Debian
sudo apt update && sudo apt install nginx
# CentOS/RHEL
sudo yum install epel-release -y && sudo yum install nginx

申请/生成SSL证书

方案 命令/操作 适用场景
Let’s Encrypt sudo certbot --nginx -d your_domain.com 公网域名
自签名证书 openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 内网/测试环境

配置Nginx支持Git

server {
    listen 443 ssl;
    server_name your_domain.com;
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    location /git/ {
        try_files $uri $uri/ /git/index.html;
        auth_basic "Git Access"; # 启用基础认证
        auth_basic_user_file /etc/nginx/.htpasswd; # 存储用户名密码
    }
}

设置Git仓库权限

# 创建仓库目录并初始化
sudo mkdir -p /var/git/your_repo.git
sudo chown -R www-data:www-data /var/git/your_repo.git
cd /var/git/your_repo.git
git init --bare
# 配置hooks权限(允许Web服务器写入)
sudo chmod -R 770 /var/git/your_repo.git

配置防火墙和端口转发

# 开放443端口(Ubuntu示例)
sudo ufw allow 443/tcp
# 特殊场景:通过非标准端口访问(如4443)
sudo ufw allow 4443/tcp

客户端操作

  1. 克隆仓库

    git clone https://your_domain.com/git/your_repo.git
  2. 推送/拉取代码

    git push https://username:password@your_domain.com/git/your_repo.git master
  3. 保存凭证(避免重复输入密码):

    git config --global credential.helper store

常见问题排查

问题 解决方案
SSL certificate error 检查证书路径是否正确,或更新CA证书
Repository not found 确保Nginx location路径与仓库实际路径匹配
Authentication failed 检查.htpasswd文件格式或用户权限

相关问题与解答

Q1:如何更新SSL证书?

A1

  1. 使用Let’s Encrypt更新:sudo certbot renew --dry-run
  2. 手动替换证书文件后重启Nginx:sudo systemctl restart nginx
  3. 自签名证书需重新生成并更新配置。

Q2:HTTPS与SSH访问Git的区别?

A2
| 对比项 | HTTPS | SSH |
|——–|——-|—–|
| 传输协议 | TLS加密 | 非对称加密 |
| 认证方式 | 用户名+密码 | 密钥对 |
| 端口 | 443/自定义 | 22 |
| 防火墙穿透 | 更易穿透 |

0