Nginx支持 React browser router

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

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

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

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

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,方法是:若请求的路径是目录,则放弃尝试后备文件。code

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;
}
相关文章
相关标签/搜索