Nginx 配置 React、API 和 SSL 出现 ERR_SSL_PROTOCOL_ERROR

Nginx 配置 React、API 和 SSL 出现 ERR_SSL_PROTOCOL_ERROR

我正在尝试设置一个 React 应用程序、一个单独的 API 和 SSL。最初,当我从 React 调用 API 时,浏览器控制台中会出现“混合内容”错误。因此,我更改了应用程序,以便在网站通过 https 加载时对 API 进行 https 调用。现在,当调用 api 时,我在 chrome 浏览器中收到此错误: https://www.example.com:3030/authentication net::ERR_SSL_PROTOCOL_ERROR。网站的其余部分确实在 https 下加载。React 应用程序在端口 5000 上提供服务。api 在端口 3030 上。

StackExchange 上有许多类似的问题,我尝试了他们提供的答案。也许我没有正确实施答案。有比我聪明的人可以看看并指出我正确的方向吗?任何帮助都将不胜感激。我将 nginx 配置分为 2 个部分以尝试解决问题——不确定这是否是个好主意。这是 nginx 配置:

server {
  listen 80;
  listen [::]:80;

  root path_to_build_dir;
  index index.html index.htm;
  server_name example.com;

  ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
  ssl_trusted_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
  include /etc/nginx/snippets/ssl.conf;
  include /etc/nginx/snippets/letsencrypt.conf;

  location / {
    proxy_pass http://xxx.xx.xxx.xxx:5000;
  }

  location /authentication {
    proxy_pass http://xxx.xx.xxx.xxx:3030;
  }
}

server {
  listen 443 default_server ssl http2;
  listen [::]:443 ssl http2;

  root path_to_build_dir;
  index index.html index.htm;
  server_name example.com;

  ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
  ssl_trusted_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
  include /etc/nginx/snippets/ssl.conf;
  include /etc/nginx/snippets/letsencrypt.conf;

  location / {
    proxy_pass http://xxx.xx.xxx.xxx:5000;
  }

  location /authentication {
    proxy_pass http://xxx.xx.xxx.xxx:3030;
  }
}

提前致以万分谢意。

答案1

您正在代理端口的请求30305000https://example.com:443
因此不要使用https://www.example.com:3030/authentication
使用https://www.example.com/authentication
而且您不必在端口 80 块上指定 SSL 证书。

使用以下格式正确编写您的 nginx 配置。您甚至可以使用完全相同的代码,它也会起作用。

由于端口 80 和 443 是标准 HTTP 和 HTTPS 端口,因此您无需指定端口在浏览器中当你在443端口访问一个使用https协议的网站时。

server {
  listen 80;
  listen [::]:80;
  server_name example.com www.example.com;
  return 301 https://$host$request_uri; #redirects http request to https
}

server {
  listen 443 default_server ssl http2;
  listen [::]:443 ssl http2;

  root path_to_build_dir;
  index index.html index.htm;
  server_name example.com www.example.com;
  # Make Sure your SSL certificate allows www version of your site
  # Or Else you are gonna get Certificate common name invalid error when you use www.example.com

  ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
  ssl_trusted_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
  include /etc/nginx/snippets/ssl.conf;
  include /etc/nginx/snippets/letsencrypt.conf;

  location / {
    proxy_pass http://xxx.xx.xxx.xxx:5000;
  }

  location /authentication {
    proxy_pass http://xxx.xx.xxx.xxx:3030;
  }
}

相关内容