react router項目部署nginx 配置問題

react router項目部署nginx 配置問題

背景:項目中使用了react、react-router開發,在部署到nginx服務器時遇到了如下問題javascript

history

history url樣例 url樣例
hash history /#/user/profile 不須要服務器支持
browser history /user/profile react-router官方推薦,須要服務器支持(由於是SPA項目,url切換時須要服務器始終返回index.html

nginx

以下介紹使用browser history模式部署到nginx服務器php

部署到nginx根目錄

訪問路徑:http://localhost/css

# nginx配置
location / {
    root   html;
    index  index.html;
    # url 切換時始終返回index.html
    try_files $uri /index.html;
}
複製代碼

部署到nginx子目錄

假設部署到/app目錄下,訪問路徑:http://localhost/apphtml

# nginx配置
location /app {
    root   html;
    index  index.html;
    # url 切換時始終返回index.html
    try_files $uri /app/index.html;
}
# 圖片樣式緩存1年
location ~* /app.*\.(js|css|png|jpg)$
{
    access_log off;
    expires    365d;
}
# html/xml/json 文件不緩存
location ~* /app.*\.(?:manifest|appcache|html?|xml|json)$
{
    expires    -1;
}
複製代碼
// package.json
"homepage": "http://localhost/app",
複製代碼
// react-router路由配置
// 注意指定basename
<BrowserRouter basename='/app'>
</BrowserRouter>
複製代碼

開啓nginx的gzip壓縮

# 開啓gzip
gzip on;
 # 啓用gzip壓縮的最小文件,小於設置值的文件將不會壓縮
gzip_min_length 1k;
 # gzip 壓縮級別,1-10,數字越大壓縮的越好,也越佔用CPU時間
gzip_comp_level 1;
 # 進行壓縮的文件類型。javascript有多種形式。其中的值能夠在 mime.types 文件中找到。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
 # 是否在http header中添加Vary: Accept-Encoding,建議開啓
gzip_vary on;
 # 禁用IE 6 gzip
gzip_disable "MSIE [1-6]\.";
複製代碼

總體配置

# nginx.conf總體配置大概以下:
http {
    # 開啓gzip
    gzip on;
    # 啓用gzip壓縮的最小文件,小於設置值的文件將不會壓縮
    gzip_min_length 1k;
    # gzip 壓縮級別,1-10,數字越大壓縮的越好,也越佔用CPU時間,後面會有詳細說明
    gzip_comp_level 1;
    # 進行壓縮的文件類型。javascript有多種形式。其中的值能夠在 mime.types 文件中找到。
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php;
    # 是否在http header中添加Vary: Accept-Encoding,建議開啓
    gzip_vary on;
    # 禁用IE 6 gzip
    gzip_disable "MSIE [1-6]\.";

    server {
        location /app {
            root   html;
            index  index.html;
            # url 切換時始終返回index.html
            try_files $uri /app/index.html;
        }
        # 圖片樣式緩存1年
        location ~* /app.*\.(js|css|png|jpg)$
        {
            access_log off;
            expires    365d;
        }
        # html/xml/json 文件不緩存
        location ~* /app.*\.(?:manifest|appcache|html?|xml|json)$
        {
            expires    -1;
        }
    }
}
複製代碼
相關文章
相關標籤/搜索