Nginx配置---解決History路由報錯問題


目錄

1. 功能描述
2. 代碼實現

一、功能描述

  • 實現
    • vue項目中使用history模式的路由時,解決訪問深層級的路由返回404的問題。
    • nginx配置了ssl證書的情況下,解決history路由刷新報404的問題。
  • 版本:nginx/1.16.1。

二、代碼實現

nginx.conf中相關配置:

    server {
        listen       80;
        server_name  <your-server-name>;

        # http 轉成 https,配置了ssl證書時啟用
        return 301 https://$host$request_uri;

        # 解決history路由刷新問題
        location / {
            # index.html文件在服務器中的存儲目錄
            root /data/www;  # /data/www需要修改為你服務器中的目錄
            index index.html index.htm;
            
            #資源訪問失敗后定向到index.html
            try_files $uri $uri/ /index.html;
        }

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
    
    # SSL證書配置
    server {
        listen       443 ssl;
        server_name  <your-server-name>;

        ssl_certificate <your_ssl_certificate_filepath>;
        ssl_certificate_key <your_ssl_certificate_key_filepath>;
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
        ssl_prefer_server_ciphers on;

        # 解決http轉https后路由報錯問題
        location / {
            root /data/www;
            index index.html index.htm;
            try_files $uri $uri/ /index.html;
        }

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

三、最終效果

demo地址


免責聲明!

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



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