使用 SSL 和前端 + 后端相同服务器的 Nginx

安德马丁

我有一台带有 Ubuntu 的服务器(VPS Amazon)。在这个服务器上运行我的后端节点和我的前端 React。我的 ReactApp 在 nginx 上运行,我的后端在 pm2 上运行。

在我的 React 应用程序中,我定义了 REACT_APP_BASE_URL:http://[my_ip_server]:4000。所以一切正常,但在 nginx 中配置 SSL 后,我可以访问我的前端登录页面,但是当我发送请求时,我发现以下错误:

a) 如果我在 REACT_APP_BASE_URL (https://[my_ip_server]:4000) 中设置了 https,则会收到此错误:ERR_SSL_PROTOCOL_ERROR。b) 如果我使用 http,我会收到混合内容错误

有人知道我是如何做这项工作的吗?

非常感谢!

我的 nginx.conf。目前我只使用端口 80,直到我解决我的问题。

server {

        #listen [::]:443 ssl ipv6only=on; # managed by Certbot
        #listen 443 ssl; # managed by Certbot

        #ssl_certificate /etc/letsencrypt/live/mysite.com.br/fullchain.pem; # managed by Certbot
        #ssl_certificate_key /etc/letsencrypt/live/mysite.com.br/privkey.pem; # managed by Certbot
        #include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        #ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

        #if ($host = surveys.alcancenet.com.br) {
        #  return 301 https://$host$request_uri;
        #} # managed by Certbot


        listen 80 default_server;
        listen [::]:80 default_server;
        server_name mysite.com.br;
        #return 404; # managed by Certbot

        root /var/www/html;
        
        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        
        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri /index.html;


        }


}
马基多

首先,运行应用程序(这是我假设您使用 PS2 的目的)和通过 nginx 代理公开它们之间存在差异。

最好向我们展示您的 nginx 配置文件,并告诉我们您的后端在哪个端口上运行(假设前端在端口 4000 上运行)。

编辑; 感谢您的配置和后端端口。

我认为您不需要将 create react app base url 设置为 https,只需设置端口并使用 PS2 在 VPS 上运行它即可。

我看不到你的配置中有任何指向 4000 的代理——你不暴露后端吗?

唯一暴露的部分是静态 html 文件。相关代码是;

root /var/www/html;

# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;


location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri /index.html;
} 

如果您想使用 https 调用后端,或使用某些工具生成您的站点,该工具的过程需要 HTTPS 调用,您需要在前端正确执行此操作。IE 的东西在这里不加起来。

通常的做法是;将后端和前端只暴露在SSL的443端口,使用不同的子域(例如api.mydomain.com),然后使用nginx中的代理将每个域的443流量重定向到对应的本地端口(4000,以及前端端口或静态文件目录更有可能)。

代替:

location / {
        try_files $uri $uri /index.html;
} 

使用类似的东西:

location / {
            proxy_pass http://localhost:4000;
} 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章