使用 nginx 在同一个 IP 地址上为两个不同的应用程序(两个域)提供服务

使用 nginx 在同一个 IP 地址上为两个不同的应用程序(两个域)提供服务

我正在尝试配置 nginx 以在同一个 IP 地址上为两个不同的站点提供服务,但我遇到了麻烦。

server_tokens off;  # hide nginx version

# site1.com app is served from localhost:3006
# site2.com is served from a socket:
upstream puma {
  server unix:/var/www/site1/sockets/puma.sock fail_timeout=0;
}

# Site 1 should be served over HTTP
server {
  listen   80;
  server_name site1.com;

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:3006/;
  }

  access_log /var/www/site2/log/site1.nginx.access.log;
  error_log  /var/www/site2/log/site1.nginx.error.log;
}

# Site 2 over HTTP should redirect to site 2 HTTPS
server {
  listen 80;
  server_name site2.com;
  return 301 https://$host$request_uri;
}

# Site 2 should be served over HTTPS
server {
  listen 443 ssl;

  ssl_certificate /etc/letsencrypt/live/site2.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/site2.com/privkey.pem;

  access_log /var/www/site2/log/nginx.access.log;
  error_log  /var/www/site2/log/nginx.error.log;

  # if the maintenance file exists, we return it
  if (-f /var/www/site2/public/system/maintenance.html) {
    return 503;
  }

  error_page 503 @maintenance;
  location @maintenance {
    rewrite ^(.*)$ /system/maintenance.html last;
    break;
  }

  # .well-known is for letsencrypt certificates
  location ~ ^/(static|assets|files|system|.well-known)/ {
    root /var/www/site2/public;
  }

  location / {
    proxy_pass http://puma;

    # Keep the original host and pass it to the Rails app,
    # so it can handle differently requests from different
    # subdomains.
    # If proxy_set_header is not used, Rails will only see
    # 'puma' as host of requests.
    proxy_set_header Host $host;
    # More headers are needed by rack, for various reasons,
    # including security checks
    # see https://github.com/rails/rails/issues/22965
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Ssl on;  # optional
    proxy_set_header X-Forwarded-Port $server_port;
    proxy_set_header X-Forwarded-Host $host;
  }
}

目前,site2.com 运行正常,但对 site1.com 的请求导致“证书配置错误”错误。

所有对域的请求难道不应该site1.com由第一个指令处理吗server

答案1

错误的一部分是我使用了 nginx docker 镜像,其中的 Dockerfile 如下:

FROM nginx

COPY nginx.prod.conf /etc/nginx/conf.d/default.conf

他们说用来sudo docker exec [name] nginx -s reload在docker里面重新加载nginx,但是这不会在docker里面导入新的conf,它只是重新加载相同的...

我的解决方案:不要使用 docker。就我而言,它只是增加了一层复杂性,而且容易出错。当然,YMMV,如果由您的部署工具正确管理,docker 确实很有用。

相关内容