如何正确处理具有动态结尾的Nginx路由



更具体地说,我在Nginx容器中有React应用程序的静态文件,我想在路由http://localhost/rooms/:id上提供这些文件。ID只是一个整数,该整数决定了浏览器将对后端进行的API调用。我很难告诉Nginx忽略ID,只提供静态文件。

这是我的Nginx配置文件:

http {
include /etc/nginx/mime.types;
gzip on;
gzip_types text/plain text/css application/javascript;

server {
listen 80;
location /rooms/ {
root /var/www/rooms;
index index.html index.htm;
try_files $uri $uri/ =404;
}
location ~* .(js|css)$ {
root /var/www/rooms;
expires 30d;
}
}
}

events { }

如何告诉Nginx忽略/rooms/之后的所有内容?

我想要的最终结果是:

  1. http://localhost/rooms/1为根目录中的静态文件提供服务
  2. http://localhost/rooms/2在根目录中提供相同的静态文件

最好为api调用使用不同的路由,但如果您真的想这样使用它,只需添加索引文件即可尝试文件。您还应该使用根外部位置块。

root /var/www/rooms;
location /rooms/ {
index index.html index.htm;
try_files $uri $uri/ index.html /index.html =404;
}

最新更新