【问题标题】:Add context path for an app on nginx在 nginx 上为应用添加上下文路径
【发布时间】:2017-09-01 16:07:28
【问题描述】:

Nginx 将根目录中的所有静态内容服务到根 URL。例如,如果根内容位置配置为 /usr/share/nginx/html,其中包含一个文件 /usr/share/nginx/html/foo.html,则 url http://localhost/foo.html 将提供该 html 文件。我想在 URL 中添加一个上下文路径前缀,以便 http://localhost/myapp/foo.html 应该服务于 /usr/share/nginx/html/foo.html 文件。

我尝试更改位置并添加别名,但结果为 404。

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
  }

  location /myapp/ {
    alias   /usr/share/nginx/html/;
  }

我还希望http://localhost/myapp 应该服务于/usr/share/nginx/html/index.html

我正在使用 nginx 的 1.12.1-alpine docker 镜像

【问题讨论】:

    标签: nginx nginx-location


    【解决方案1】:

    试试这个

      index  index.html index.htm;
      location / {
        root   /usr/share/nginx/html;
      }
    
      location /myapp/ {
        alias   /usr/share/nginx/html/;
      }
    

    如果这不起作用,请在下面尝试

      index  index.html index.htm;
      location / {
        root   /usr/share/nginx/html;
      }
    
      location /myapp/ {
        alias   /usr/share/nginx/html/;
        try_files $uri $uri/ =404;
      }
    

    Edit-1

    如果你希望它在没有尾随 / 的情况下工作,那么你应该在下面使用

    location ~ /app(/.*)?$ {
       alias   /usr/share/nginx/html/;
       try_files $uri $uri/ =404;
    }
    

    【讨论】:

    • 感谢您的回复 - 我正在尝试使用斜杠,因为我也在问题中写了它。
    • 配置 100% 正确。我在本地测试过。我猜您的 nginx 配置中还有一些其他默认配置,这可能是问题所在。在您的nginx.conf 文件夹所在的文件夹中添加find . -name "*.conf" 的输出
    • 经过一番尝试后奏效了。唯一不带斜杠 (http://localhost/myapp) 的根 url 返回 404,其中 http://localhost/myapp/ 返回 index.html
    • 您介意解释一下为什么 OP 的 conf 返回 404 吗?我不明白问题出在哪里
    • 我认为 index index.html 不在外面,这就是原因。
    猜你喜欢
    • 2017-06-09
    • 2013-12-22
    • 2014-05-07
    • 1970-01-01
    • 2019-04-10
    • 2021-10-10
    • 2011-02-15
    • 2021-08-10
    相关资源
    最近更新 更多