使用Nginx与Create-React-App开发服务器和npm start

3
令人沮丧的问题。我有一个使用created-react-app创建的React项目,它在需要使用Nginx进行外部连接/HTML服务器的服务器上运行。我需要做的是将nginx用作代理服务器,当浏览器中输入URL时,请求会路由到localhost:3000,并由react应用程序生成结果,然后由nginx传递给客户端。
因此,以下是到目前为止的nginx文件,但我无法让它正常工作。一些问题:
1. 是否需要将root指定到react项目中的/public目录以获取index.html? 2. 假设您运行npm start并在编译完成后在浏览器中输入完全限定域名(FQDN),它就会路由到localhost:3000
我的Nginx配置如下:
    server_name         server-name.com;   
    listen              443 ssl;
    ssl_certificate     /etc/letsencrypt/live/site-name/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/site-name/privkey.pem;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;

    proxy_read_timeout 60s;
    client_max_body_size 64M;
    
    # should this be routed to /public in the react project to pick up index.html?
    # root /var/www/html;

    index index.html index.htm;

    location / {
        #try_files $uri $uri/ =404;
        
        # Make sure React Application return is index.html so client routing remains in sync/reachable        
        #try_files $uri /index.html;
   
        proxy_pass  http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }    

    location /_api {
       rewrite ^/_api/(.+) /$1 break;
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:3030;
    }
}

server {
    server_name         server-name.com   
    listen              80;

    allow 10.0.0.0/16;
    deny all;

    proxy_read_timeout 60s;
    client_max_body_size 64M;

    # Should this be routed to /public in the react project to pick up index.html?
    # root /var/www/html;

    index index.html index.htm;

    location / {
        #try_files $uri $uri/ =404;
        
        # Make sure React Application return is index.html so client routing remains in sync/reachable        
        try_files $uri /index.html;

    }    

    location /_api {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:3030;
   }
} 
1个回答

1
请打开您的nginx文件vi sites-enabled/default,如果您不知道如何操作,请告诉我。
然后删除该文件中的所有内容,只需粘贴以下内容:
server {
    listen 80;
    client_max_body_size 10M;
    server_name YourWebsiteNameWithDomain yourIPV4;
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
     }
}

不要忘记重新启动您的nginx


1
嗨,Sumit,谢谢你的建议。我正在使用Centos7,没有sites-enabled/default文件。我只有conf.d目录和我的nginx-site.conf文件。这个应该放在里面吗? - Rachel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接