nginx配置:处理React项目中带有哈希值的index.html文件
React应用打包后,index.html文件名通常会包含哈希值,例如index.a1b2c3d4.html。本文介绍如何在Nginx中正确配置,以处理这些带有哈希值的index.html文件。
问题:如何动态匹配哈希值?
传统的Nginx配置,例如:
location / { root html/demo; index index.html; try_files $uri $uri/ /index.html; }
无法直接处理index.a1b2c3d4.html这样的文件名。
解决方案:使用Nginx正则表达式
以下Nginx配置使用正则表达式和try_files指令,优雅地解决了这个问题:
立即学习“前端免费学习笔记(深入)”;
server { listen 80; location / { root html/demo; try_files $uri $uri/ @hashed; } location @hashed { rewrite ^/(.*)$ /$1/index.[0-9a-f]+.html last; try_files $uri =404; } }
配置说明:
-
location /: 处理所有请求。try_files首先尝试寻找精确匹配的资源($uri),然后尝试寻找目录($uri/),如果都失败,则跳转到名为@hashed的location块。
-
location @hashed: 专门处理带有哈希值的index.html文件。
-
*`rewrite ^/(.)$ /$1/index.[0-9a-f]+.html last;**: 这是关键部分。它使用正则表达式index.[0-9a-f]+.html匹配文件名。^/(.*)$捕获除了index.a1b2c3d4.html以外的路径,$1代表捕获的路径,然后将其与匹配的index文件名组合。last`标志表示继续处理后续指令。
-
try_files $uri =404;: 尝试查找重写后的文件,如果找不到则返回404错误。
-
此配置能够动态匹配各种带有哈希值的index.html文件,例如index.a1b2c3d4.html, index.e5f6g7h8.html等,确保React应用能够正确加载。 记住将html/demo替换为你的实际项目根目录。