首页 > 解决方案 > nginx 服务器:如何从 URL 中删除第一个目录

问题描述

有人可以帮我从 URL 中删除第一个目录名称吗?

我的图像位置是_data/hotel/3/15377/hotel_image.jpg

但是图像路径由于代码中的相对 URL 而发生了变化,它变成了这样的东西。

example.com/france/_data/hotel/3/15377/hotel_image.jpg example.com/usa/_data/hotel/3/15377/hotel_image.jpg example.com/india/_data/hotel/3/15377/hotel_image.jpg

他们是否有可能从上述 URL 中删除动态国家名称

标签: nginxurl-rewritingnginx-location

解决方案


如果你只想重写这个特定的 URL,你可以location在你的配置中使用这个块:

location ~ /[a-z]+/_data/hotel/3/15377/hotel_image.jpg {
    try_files /_data/hotel/3/15377/hotel_image.jpg;
}

如果要重写所有导致 的 URL /<country>/_data/...,可以使用:

location ~ /[a-z]+/_data/(.+) {
    try_files /_data/$1;
}

或进行更严格的 URL 检查:

location ~ /(?:france|usa|india)/_data/(.+) {
    try_files /_data/$1;
}

推荐阅读