在 Nginx 中配置新站点并代理 GitLab

发表于 2025-09-09 14:08:33 分类于 默认分类 阅读量 100

在 Nginx 中配置新站点并代理 GitLab

在实际运维中,我们经常需要通过 Nginx 配置反向代理,为内部服务提供域名访问。下面以 gitlab.xzsoft.com 为例,演示如何在 Nginx 中新增一个站点,并将请求代理到内部 GitLab 服务 172.16.1.28


1️⃣ 新建站点配置文件

在 Nginx 的配置目录 /etc/nginx/sites-available/ 下,新建一个站点配置文件:

sudo nano /etc/nginx/sites-available/gitlab.xzsoft.com

写入以下内容:

server {
    listen 80;
    server_name gitlab.xzsoft.com;

    # 日志路径
    access_log /var/log/nginx/gitlab.access.log;
    error_log /var/log/nginx/gitlab.error.log;

    # 代理到 GitLab 内部 IP
    location / {
        proxy_pass http://172.16.1.28;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # WebSocket 支持
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

2️⃣ 启用站点

创建软链接到 sites-enabled 目录:

sudo ln -s /etc/nginx/sites-available/gitlab.xzsoft.com /etc/nginx/sites-enabled/

3️⃣ 检查配置是否正确

执行以下命令验证配置语法:

sudo nginx -t

如果输出包含:

nginx: configuration file /etc/nginx/nginx.conf test is successful

说明配置没有问题。


4️⃣ 重新加载 Nginx

修改配置后,需要重新加载 Nginx 才能生效,可以使用以下两种方式之一:

# 使用 systemctl
sudo systemctl reload nginx

# 或者使用 nginx 自带命令
sudo nginx -s reload

至此,访问 http://gitlab.xzsoft.com 时,就会自动代理到内网 172.16.1.28 的 GitLab 服务。 🎉


要不要我再帮你加一段 常见问题排查(502/403 等错误) 的补充说明?这样博客就更完整了。

正物博客
一路向前,山海自平