「Jenkins」- 使用 Nginx 反向代理 Jenkins 服务



详细的内容参考官方的「Running Jenkins behind Nginx」文档


upstream jenkins {
  keepalive 32; # keepalive connections
  server; # jenkins ip and port

server {
  listen          80;       # Listen on port 80 for IPv4 requests

  server_name     jenkins.example.com;

  #this is the jenkins web root directory (mentioned in the /etc/default/jenkins file)
  root            /var/run/jenkins/war/;

  access_log      /var/log/nginx/jenkins/access.log;
  error_log       /var/log/nginx/jenkins/error.log;
  ignore_invalid_headers off; #pass through headers from Jenkins which are considered invalid by Nginx server.

  location ~ "^/static/[0-9a-fA-F]{8}\/(.*)$" {
    #rewrite all static files into requests to the root
    #E.g /static/12345678/css/something.css will become /css/something.css
    rewrite "^/static/[0-9a-fA-F]{8}\/(.*)" /$1 last;

  location /userContent {
    #have nginx handle all the static requests to the userContent folder files
    #note : This is the $JENKINS_HOME dir
	root /var/lib/jenkins/;
    if (!-f $request_filename){
      #this file does not exist, might be a directory or a /**view** url
      rewrite (.*) /$1 last;
	sendfile on;

  location / {
      sendfile off;
      proxy_pass         http://jenkins;
      proxy_redirect     default;
      proxy_http_version 1.1;

      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;
      proxy_max_temp_file_size 0;

      #this is the maximum upload size
      client_max_body_size       10m;
      client_body_buffer_size    128k;

      proxy_connect_timeout      90;
      proxy_send_timeout         90;
      proxy_read_timeout         90;
      proxy_buffering            off;
      proxy_request_buffering    off; # Required for HTTP CLI commands in Jenkins > 2.54
      proxy_set_header Connection ""; # Clear for keepalive



在反向代理后,出现 HTTP Basic authentication 重复认证

为了提高安全性,使用Nginx反向代理 Jenkins 后,又在 Nginx 中配置了 HTTP Basic Authentication 功能,但是出现了“认证窗口不停弹出”的问题。
关于 HTTP Basic Authentication 的配置参考 Restricting Access with HTTP Basic Authentication 一文。

使用 curl 命令请求(curl --user user:password http://),返回 401 认证失败页面,该页面是 Jenkins 返回的(页面上由 Jetty…… 等内容)。
修改 Jenkins 调试等级并打开访问日志,请求日志中出现了 401 认证失败的请求。
前端 Nginx 将 Authorization 请求头传给 Jenkins 服务,但是 Jenkins 并没有配置认证,而导致认证失败。
但实际上,我们并不需要把 Authorization 头传递给 Jenkins 服务。

修改Nginx配置文件,在转发时移除Authorization头:proxy_set_header Authorization "";
通过置空来移除头部,参考官方文档说明:「Module ngx_http_proxy_module/proxy_set_header


Running Jenkins behind Nginx
Wikipedia/Basic access authentication
Hide a client request header with a Nginx reverse proxy server
How to define the basic HTTP authentication using cURL correctly?