react router项目部署nginx 配置问题

背景:项目中使用了reactreact-router开发,在部署到nginx服务器时遇到了以下问题

history

history url样例 特点
hash history /#/user/profile 不需要服务器支持
browser history /user/profile react-router官方推荐,需要服务器支持(因为是SPA项目,url切换时需要服务器始终返回index.html)

nginx配置

如下介绍使用browser history模式部署到nginx服务器

部署到nginx根目录

访问路径:http://localhost/

# nginx配置
location / {
    root   html;
    index  index.html;
    # url 切换时始终返回index.html
    try_files $uri /index.html;
}

部署到nginx子目录

假设部署到/app目录下,访问路径:http://localhost/app

# 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;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,269评论 19 139
  • Page 1:nginx 服务器安装及配置文件详解 CentOS 6.2 x86_64 安装 nginx 1.1 ...
    xiaojianxu阅读 8,620评论 1 41
  • 第一章 Nginx简介 Nginx是什么 没有听过Nginx?那么一定听过它的“同行”Apache吧!Ngi...
    JokerW阅读 32,849评论 24 1,002
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,638评论 25 709
  • 小河北岸 老木屋前 信箱子里 一封素笺 泪已湿了半张 他回忆起 曾爱的模样 模糊了,清晰了,消失了... 再也看不...
    曾有个男孩阅读 237评论 0 3