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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM