Nginx支持 React browser router

修改nginx配置文件,添加try_file配置如下,即可实现对 React browser router 的支持。

location / {
    root /var/www/mysite;
    try_files $uri /index.html;
}

但是该方式也会存在缺点,只要/index.html存在,服务端就不会响应404,即使客户端请求了实际不存在的JS/CSS/图片文件。

要使非HTML请求实际资源不存在时响应404,方法是:若请求的资源不是HTML,则放弃尝试后备文件。

location / {
    root /var/www/mysite;
    set $fallback_file /index.html;
    if ($http_accept !~ text/html) {
        set $fallback_file $uri;
    }
    try_files $uri $fallback_file;
}

要使得try_files不影响index和/与autoindex,方法是:若请求的路径是目录,则放弃尝试后备文件。

location / {
    root /var/www/mysite;
    index index.html;
    autoindex on;
    set $fallback_file /index.html;
    if ($http_accept !~ text/html) {
        set $fallback_file /null;
    }
    if ($uri ~ /$) {
        set $fallback_file $uri;
    }
    try_files $uri $fallback_file;
}

 

posted @ 2019-03-06 16:33  wavemelody  阅读(2102)  评论(0编辑  收藏  举报