React Web App with Nginx not redirecting properly

2019-07-30 16:31发布

I'm trying to deploy a React Web App on digital ocean using nginx.

My root points to the build folder in my git repo. This way I can update my app by git pull whenever I make a change.

At first, everything worked ok, but then I did a git pull and now I'm getting redirect errors or 500 errors. I'm not sure what happened.

If I open the site in the browser to the home page, it just shows a blank white screen. If I try accessing a subdomain, it gives a 500 internal error.

My sites-available/default file looks like:

server {
    server_name portal.productive.city www.portal.productive.city;
    root /www/Productive-Website/my-app/build;
    index index.html index.htm;
    rewrite ^/(.*)/$ $1 permanent;
    location / {
       try_files $uri $uri/ /index.php?$args;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/portal.productive.city/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/portal.productive.city/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

}

When I check the error-log I keep seeing

2018/08/31 13:32:26 [error] 29118#29118: *13 rewrite or internal redirection cycle while internally redirecting to "/index.php", client: 74.105.149.67, server: portal.productive.city, request: "GET /signin/signin HTTP/1.1", host: "www.portal.productive.city", referrer: "https://www.portal.productive.city/service-worker.js"

If I run nginx -t it says my config is ok and successful.

标签: nginx
1条回答
啃猪蹄的小仙女
2楼-- · 2019-07-30 16:42

Looks like index.php doesn't exists on /www/Productive-Website/my-app/build maybe it should be a .html or .htm file? This makes your webserver try to render index.php and because it doesn't exists, you get redirected to index.php. If that is the case it would happen on any path.

Edit that file so that your location file looks like:

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

This means, "When receiving a request, search for a file matching $uri OR $uri/ OR $uri.html and if none of those works, render /index.html?$args". This means your React app should manage all errors on /index.html, so adequate your application accordingly.

查看更多
登录 后发表回答