You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nginx配置中修改根路径,将服务映射到/webapp子路径?

配置步骤

1. 新建自定义Nginx站点配置文件

在项目根目录创建default.conf文件,提供两种常用配置方案,选其中一种即可:

方案1:路径重写(推荐,地址栏保持/webapp前缀不变)

server {
    listen       8080;
    server_name  localhost;

    root   /usr/share/nginx/html;
    index  index.html index.htm;

    # 匹配/webapp前缀的请求
    location ^~ /webapp {
        # 去掉/webapp前缀后转发到根路径处理
        rewrite ^/webapp(/.*)?$ $1 break;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

方案2:目录别名

server {
    listen       8080;
    server_name  localhost;

    root   /usr/share/nginx/html;
    index  index.html index.htm;

    location ^~ /webapp {
        alias /usr/share/nginx/html;
        try_files $uri $uri/ /index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

2. 修改Dockerfile

更新后的Dockerfile内容如下,新增配置文件复制步骤:

FROM nginx:latest

# 复制静态页面
COPY index.html /usr/share/nginx/html
# 复制自定义Nginx配置覆盖默认配置
COPY default.conf /etc/nginx/conf.d/default.conf

EXPOSE 8080

3. 重新构建并运行容器

执行以下命令更新镜像并启动:

  • 构建镜像:docker build -t webapp .
  • 启动容器:docker run -p 8080:8080 webapp:latest

配置完成后,访问http://localhost:8080/webapp就会和访问根路径返回完全一致的内容。

内容的提问来源于stack exchange,提问作者manchanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:36:07