【问题标题】:Nginx and relative pathNginx 和相对路径
【发布时间】:2023-03-09 17:19:01
【问题描述】:

在 nginx 根目录下我们有这样的文件:

   - test\
       image.jpg
       index.html
   - ...

在 index.html 中有指向 image.jpg 的链接:

<img src='image.jpg'>

在标准 Nginx 配置中,我们有这样的行 (http://nginx.org/ru/docs/http/ngx_http_core_module.html#try_files)

   server {
    server_name example.com;
    ...
    try_files $uri $uri/index.html;
   }

对于 URL http://example.com/test/index.html(和 http://example.com/test/),一切都会正常工作,因为相对路径的基础是 http://example.com/test/,并且我们在此文件夹中有 image.jpg。

http://example.com/test 页面将显示,但没有图像。

在这种情况下,最好的解决方案是什么?

【问题讨论】:

  • 在这种情况下,最好的解决方案是使用index index.html; 指令而不是try_files。在这种情况下,nginx 将从 /test 重定向到 /test/

标签: url nginx relative-path


【解决方案1】:

我认为您的意思是 $uri 带有 I,而不是 $url 带有 L

问题在于try_files 将在$uri/index.html 获取文件,但将URI 保留为/test,因此任何相对URI 都将相对于/ 而不是/test/

如果您要在 HTML 文件中使用相对 URI,则必须在目录引用上强制使用结尾的 /。例如:

index index.html;
try_files $uri $uri/ =404;

这将导致/test 重定向到/test/index 指令将自动尝试子目录中的index.html 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2013-07-14
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多