Как настроить nginx для обслуживания gitlabhq по SubURI

Конфигурация nginx для gitlab:

# GITLAB
# Maintainer: @randx
# App Version: 3.0

upstream gitlab {
  server unix:/home/gitlab/gitlab/tmp/sockets/gitlab.socket;
}

server {
  listen YOUR_SERVER_IP:80;         # e.g., listen 192.168.1.1:80;
  server_name YOUR_SERVER_FQDN;     # e.g., server_name source.example.com;
  root /home/gitlab/gitlab/public;

  # individual nginx logs for this gitlab vhost
  access_log  /var/log/nginx/gitlab_access.log;
  error_log   /var/log/nginx/gitlab_error.log;

  location / {
    # serve static files from defined root folder;.
    # @gitlab is a named location for the upstream fallback, see below
    try_files $uri $uri/index.html $uri.html @gitlab;
  }

  # if a file, which is not found in the root folder is requested,
  # then the proxy pass the request to the upsteam (gitlab unicorn)
  location @gitlab {
    proxy_read_timeout 300; # https://github.com/gitlabhq/gitlabhq/issues/694
    proxy_connect_timeout 300; # https://github.com/gitlabhq/gitlabhq/issues/694
    proxy_redirect     off;

    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   Host              $http_host;
    proxy_set_header   X-Real-IP         $remote_addr;

    proxy_pass http://gitlab;
  }
}

Что я должен изменить, чтобы использовать gitlab в качестве surURI, www.mysuperserver.com/gitlab

я пробовал много разных вещей, но ничего не получилось спасибо


person Jeff    schedule 05.11.2012    source источник


Ответы (5)


Начиная с Gitlab 5.3 вы можете настроить его для запуска в субури из коробки, используя официальный документ по установке.

Раскомментируйте строку 8 файла config/puma.rb: ENV['RAILS_RELATIVE_URL_ROOT'] = "/"

Аналогично для строки 23 в config/gitlab.yml: relative_url_root:/

Мне вообще не нужно было изменять конфигурацию nginx, чтобы она работала.

person Chris Chou    schedule 08.07.2013

Я успешно заставил его работать под URL-адресом subdir.

  • следуйте инструкциям в исходном коде, как в /home/git/gitlab/config/gitlab.yml
    # Uncomment and customize the last line to run in a non-root path
    # WARNING: We recommend creating a FQDN to host GitLab in a root path instead of this.
    # Note that four settings need to be changed for this to work.
    # 1) In your application.rb file: config.relative_url_root = "/gitlab"
    # 2) In your gitlab.yml file: relative_url_root: /gitlab
    # 3) In your unicorn.rb: ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
    # 4) In ../gitlab-shell/config.yml: gitlab_url: "http://127.0.0.1/gitlab"
    # To update the path, run: sudo -u git -H bundle exec rake assets:precompile RAILS_ENV=production
    #
    relative_url_root: /gitlab
  • измените конфигурацию nginx для обслуживания субури, пожалуйста, обратитесь к моему примеру ниже:

Ключевым моментом является root в контексте server и alias в контексте location. Пожалуйста, обратитесь к подводным камням nginx, корневая заметка nginx для более подробной информации.

# default.conf for nginx
upstream gitlab {
  server unix:/home/git/gitlab/tmp/sockets/gitlab.socket;
}
server {
    listen       80;
    server_name  $YOUR_DOMAIN;
    # other settings, especially root settings, like below
    # root /usr/local/nginx/html;
    location /gitlab {
        # serve static files from defined root folder;
        alias /home/git/gitlab/public;

        # individual nginx logs for this gitlab vhost
        access_log  /var/log/nginx/gitlab_access.log;
        error_log   /var/log/nginx/gitlab_error.log;

        # @gitlab is a named location for the upstream fallback, see below
        try_files $uri $uri/index.html $uri.html @gitlab;
    }

    location @gitlab {
        proxy_read_timeout 300; # https://github.com/gitlabhq/gitlabhq/issues/694
        proxy_connect_timeout 300; # https://github.com/gitlabhq/gitlabhq/issues/694
        proxy_redirect     off;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_set_header   Host              $http_host;
        proxy_set_header   X-Real-IP         $remote_addr;
        proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;

        proxy_pass http://gitlab;
    }
    # other locations' settings...
}
person Ace    schedule 21.01.2014
comment
+1. какую версию GitLab вы использовали? Вы тестировали его с URL-адресом push/pull ssh? адрес https? - person VonC; 21.01.2014
comment
филиал 6-4-stable. никто не жалуется на push/pull. URL-адрес https еще не настроен. - person Ace; 21.01.2014

Для старых версий, например, gitlab 7.4.5, нет gitlab-git-http-server (gitlab-workhorse). Но есть некоторые решения для gitlab 7.4.5, чтобы использовать субури в документе.

config/application.rb

# Relative url support
# Uncomment and customize the last line to run in a non-root path
# WARNING: We recommend creating a FQDN to host GitLab in a root path instead of this.
# Note that following settings need to be changed for this to work.
# 1) In your application.rb file: config.relative_url_root = "/gitlab"
# 2) In your gitlab.yml file: relative_url_root: /gitlab
# 3) In your unicorn.rb: ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
# 4) In ../gitlab-shell/config.yml: gitlab_url: "http://127.0.0.1/gitlab"
# 5) In lib/support/nginx/gitlab : do not use asset gzipping, remove block starting with "location ~ ^/(assets)/"
#
# To update the path, run: sudo -u git -H bundle exec rake assets:precompile RAILS_ENV=production
#
# config.relative_url_root = "/gitlab"

config/gitlab.yml

# WARNING: See config/application.rb under "Relative url support" for the list of
# other files that need to be changed for relative url support
# relative_url_root: /gitlab

Настройка gitlab 7.4.5 с другим веб-сайтом, использующим тот же порт и то же доменное имя в конфигурации nginx или файле конфигурации apache, по-прежнему кажется сложной задачей. Я не понял. Я могу получить доступ к gitlab как www.mydomain.com/gitlab , но я не получил свой другой веб-сайт в другом корневом каталоге с www.mydomain.com. Это должно быть разрешено путем настройки nginx или apache. Надеюсь, что люди, знакомые с nginx или apache, могут дать решение.

Другие ссылки.Поддержка установки GitLab по относительному URL-адресу или подкаталогу #1950

ИЗМЕНИТЬ
Теперь все работает.

stackoverflow предлагает использовать здесь www.example.com в качестве примера.

www.example.com/gitlab доступ к gitlab.

www.example.com открывает доступ к другому веб-сайту, например моему блогу.

Шаги:

  1. Файл config/application.rb: config.relative_url_root = "/gitlab"
  2. Файл config/gitlab.yml: относительный_url_root: /gitlab
  3. config/unicorn.rb: ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
  4. ../gitlab-shell/config.yml: gitlab_url: "http://www.example.com/gitlab"
  5. скопируйте lib/support/nginx/gitlab в gitlab.conf для nginx и не используйте сжатие ресурсов, удалите блок, начинающийся с "location ~^/(assets)/"
  6. выполнить: sudo -u git -H bundle exec rake assets:precompile RAILS_ENV=production

URL-адреса:

  1. Файл config/gitlab.yml: хост: example.com порт: 80
  2. config/unicorn.rb: слушайте "127.0.0.1:9095"
  3. ../gitlab-shell/config.yml: gitlab_url: http://www.example.com/gitlab

gitlab предоставит git два способа доступа:

  1. [email protected]:sample-project.git
  2. http://example.com/gitlab/sample-project.git

Я не использую https.

Если вы получили:

Вы можете настроить config/gitlab.yml как host: example.com/gitlab. Просто удалите /gitlab.

конфигурационный файл nginx:

###################################
##         configuration         ##
###################################
##

upstream gitlab {
  server unix:/home/git/gitlab/tmp/sockets/gitlab.socket fail_timeout=0;
}

## Normal HTTP host
server {
  #listen *:80 default_server;
  listen *:80 default_server;
  server_name www.example.com; ## Replace this with something like gitlab.example.com
  server_tokens off; ## Don't show the nginx version number, a security best practice
  #root /home/git/gitlab/public;
  root html;
  location /{
    #root html;
    index index.html index.htm;
  }
  ## Increase this if you want to upload large attachments
  ## Or if you want to accept large git objects over http
  client_max_body_size 20m;

  ## Individual nginx logs for this GitLab vhost
  access_log  logs/example.gitlab_access.log;
  error_log   logs/example.gitlab_error.log;

  location /gitlab {
    alias /home/git/gitlab/public;

    ## Serve static files from defined root folder.
    ## @gitlab is a named location for the upstream fallback, see below.
    try_files $uri $uri/index.html $uri.html @gitlab;
  }

  ## If a file, which is not found in the root folder is requested,
  ## then the proxy passes the request to the upsteam (gitlab unicorn).
  location @gitlab {
    ## If you use HTTPS make sure you disable gzip compression
    ## to be safe against BREACH attack.
    # gzip off;

    ## https://github.com/gitlabhq/gitlabhq/issues/694
    ## Some requests take more than 30 seconds.
    proxy_read_timeout      300;
    proxy_connect_timeout   300;
    proxy_redirect          off;

    proxy_set_header    Host                $http_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;
    proxy_set_header    X-Frame-Options     SAMEORIGIN;

    proxy_pass http://gitlab;
  }

  ## Enable gzip compression as per rails guide:
  ## http://guides.rubyonrails.org/asset_pipeline.html#gzip-compression
  ## WARNING: If you are using relative urls remove the block below
  ## See config/application.rb under "Relative url support" for the list of
  ## other files that need to be changed for relative url support
  #location ~ ^/(assets)/ {
  #  root /home/git/gitlab/public;
  #  #gzip_static on; # to serve pre-gzipped version
  #  expires max;
  #  add_header Cache-Control public;
  #}

  error_page 502 /502.html;
}

Файл конфигурации Apache (2.2.9): ссылка gitlab.conf для gitlab 6.0.6 и gitlab-8.0-apache2.2.conf для gitlab 8.0.0 на apache 2.2

#  Module dependencies
#  mod_rewrite
#  mod_proxy
#  mod_proxy_http
<VirtualHost *:80>


  ServerAdmin [email protected]
  DocumentRoot "/data/webapp/www/wordpress"

  ServerName www.example.com
  ServerAlias example.com

  #ErrorLog "logs/wordpress-error_log"
  #CustomLog "logs/wordpress-access_log" common

    #SetEnv ZF2_PATH "/data/webapp/www/ZendFramework-2.3.3/library"
  SetEnv APPLICATION_ENV "development"
  <Directory /data/webapp/www/wordpress>
    DirectoryIndex index.php
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>

  #ServerName www.example.com
  ServerSignature Off

  ProxyPreserveHost On

  # Ensure that encoded slashes are not decoded but left in their encoded state.
  # http://doc.gitlab.com/ce/api/projects.html#get-single-project
  AllowEncodedSlashes NoDecode

  <Location /gitlab>
    Order deny,allow
    Allow from all

    ProxyPassReverse http://127.0.0.1:9095
    ProxyPassReverse http://www.example.com//

    RewriteEngine on
    #RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
    RewriteRule .* http://127.0.0.1:9095%{REQUEST_URI} [P,QSA,NE]
  </Location>

  #apache equivalent of nginx try files
  # http://serverfault.com/questions/290784/what-is-apaches-equivalent-of-nginxs-try-files
  # http://stackoverflow.com/questions/10954516/apache2-proxypass-for-rails-app-gitlab
  #  RewriteEngine on
  #  RewriteCond /code/gitlab/{REQUEST_FILENAME} !-f
  #  RewriteRule .* http://127.0.0.1:9095%{REQUEST_URI} [P,QSA,NE]

  # needed for downloading attachments
  #DocumentRoot /home/git/gitlab/public
  Alias /gitlab /home/git/gitlab/public
  #Set up apache error documents, if back end goes down (i.e. 503 error) then a maintenance/deploy page is thrown up.
  ErrorDocument 404 /404.html
  ErrorDocument 422 /422.html
  ErrorDocument 500 /500.html
  ErrorDocument 503 /deploy.html

  LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b" common_forwarded
  ErrorLog  logs/example.com_error.log
  CustomLog logs/example.com_forwarded.log common_forwarded
  CustomLog logs/example.com_access.log combined env=!dontlog
  CustomLog logs/example.com.log combined

</VirtualHost>
person Nick Dong    schedule 09.03.2016

Вы уже решили эту проблему?

Если нет, попробуйте обновить директиву location / на:

location /gitlab {
  # serve static files from defined root folder;.
  root /home/gitlab/gitlab/public;
  # @gitlab is a named location for the upstream fallback, see below
  try_files $uri $uri/index.html $uri.html @gitlab;
}

Если это не сработает, вставьте последние несколько строк /var/log/nginx/gitlab_error.log.

person myanimal    schedule 15.12.2012
comment
У меня проблема, аналогичная исходному вопросу, и я попробовал ваш подход к ее решению. В моем журнале ошибок нет новых записей, и кажется, что это само по себе не решает проблему. Я пытаюсь применить ваше предложение к чему-то вроде этого: unicorn.bogomips.org/ примеры/nginx.conf. - person ctrlc-root; 04.07.2013

Эта конфигурация работает

# GITLAB
# Maintainer: @randx
# App Version: 3.0

upstream gitlab {
  server unix:/home/gitlab/gitlab/tmp/sockets/gitlab.socket;
}

server {
  listen 80;         # e.g., listen 192.168.1.1:80; 37.59.125.28:
  server_name gitlab.<YOUR_DOMAIN>.com;     # e.g., server_name source.example.com;
  root /home/gitlab/gitlab/public;

  # individual nginx logs for this gitlab vhost
  access_log  /var/log/nginx/gitlab_access.log;
  error_log   /var/log/nginx/gitlab_error.log;

  location / {
    # serve static files from defined root folder;.
    # @gitlab is a named location for the upstream fallback, see below
    try_files $uri $uri/index.html $uri.html @gitlab;
  }

  # if a file, which is not found in the root folder is requested,
  # then the proxy pass the request to the upsteam (gitlab unicorn)
  location @gitlab {
    proxy_read_timeout 300; # https://github.com/gitlabhq/gitlabhq/issues/694
    proxy_connect_timeout 300; # https://github.com/gitlabhq/gitlabhq/issues/694
    proxy_redirect     off;

    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   Host              $http_host;
    proxy_set_header   X-Real-IP         $remote_addr;

    proxy_pass http://gitlab;
  }
}

И у меня была плохая символическая связь между доступной конфигурацией nginx и включенной конфигурацией.

person Jeff    schedule 15.12.2012
comment
Мне трудно увидеть разницу между вашей конфигурацией и той, что указана в вашем вопросе (за исключением имени сервера). Где та часть, которая позволяет www.mysuperserver.com/gitlab? - person VonC; 16.12.2012
comment
Приведенная выше конфигурация предназначена для поддомена. Мой ответ, хотя и непроверенный, должен работать на вопрос, как он был задан, www.mysuperserver.com/gitlab. Если кто попробует, было бы неплохо получить подтверждение. - person myanimal; 18.12.2012