简体   繁体   中英

How to configure Nginx to serve always one static file for all locations matching pattern?

I have one laravel application served over nginx, and another application just with react that creates a static site that uses only client side routing react-router.

So far so good, now I want to achieve the following :

all urls with pattern domain.com/admin/[whateverhere] should be served the following static html file

/var/www/html/admin_app/public/index.html (react static admin app) instead of being handled by

/var/www/html/users_app/public/index.php (the laravel app)

This is my nginx configuration only for this part, that does not work but returns 404:

   location /admin/ {
      root /var/www/html/admin_app/public;
      index index.html;
      try_files $uri index.html;
    }

The rest of config is just ssl, and main domain.

I don't want the laravel app to handle /admin/projects /admin/users routes, but I want all of these to go to just that index.htlm file which is a static react app, with client side router only.

By checking nginx looks, I see that it tries to read non existing html file. not the one I specify at /var/www/html/admin_app/public/index.html

 2020/12/01 15:30:31 [error] 6#6: *8 open() "/etc/nginx/htmlindex.html" failed (2: No such file or directory),

I have no idea why nginx tries to open this /etc/nginx/htmlindex.html file...

There are two potential solutions...

First, using a regular expression location with a root and try_files directive:

location ~ ^/admin(/.*)$ {
    root /var/www/html/admin_app/public;
    try_files $1 /index.html =404;
}

The regular expression location is evaluated in order, so the placement within the configuration file is significant. Place near the beginning of the server block to avoid unwanted side effects. See this document for details.

Note that the =404 is never reached, it just exists to that /index.html is not the last parameter of the try_files statement. See this document for details.


Alternatively, using a prefix location with an alias directive:

location ^~ /admin/ {
    alias /var/www/html/admin_app/public/;
    if (!-e $request_filename) { rewrite ^ /admin/index.html last; }
}

Both the location value and alias value should end with a / , or neither end with a / .

The alias and try_files directives do not work well together due to this long term issue , hence the if block. See this caution on the use of if within a location block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM