Home > Back-end >  Nginx location regex not working for sub pages
Nginx location regex not working for sub pages

Time:01-25

I have two react applications, one at '/home/user/www' and one at '/home/user/builds/checkout'. I want any url starting with '/checkout' eg. '/checkout/complete', '/checkout/error' to use that application. I have the below setup in my Nginx config file:

    root /home/user/www;
    index index.html index.htm;        
    location / {
      if (!-e $request_filename){
        rewrite ^(.*)$ /index.html break;
      }
    }         

    location ~ ^/checkout?(.*)$ {
            allow all;
            root /home/user/builds;
     if (!-e $request_filename){
        rewrite ^(.*)$ /index.html break;
      }
            try_files $uri $uri/index.html =404;
     }

    location ~ ^. \.. $ {
            try_files $uri =404;
    }

going to the url '/checkout' is working correctly but any other url begining with '/checkout' like '/checkout/complete' and 'checkout/error' are just returning a 404 page.

CodePudding user response:

Your configuration looks too complicated. Can you try this one?

root /home/user/www;
index index.html index.htm;        
location / {
    try_files $uri /index.html;
}         

location /checkout/ {
    root /home/user/builds;
    try_files $uri $uri/ /checkout/index.html;
}

If the /checkout URI won't redirect you to /checkout/, add this:

location = /checkout {
    return 301 /checkout/;
}
  •  Tags:  
  • Related