Nginx 和相对路径
Nginx and relative path
在 nginx root 上我们有这样的文件:
- test\
image.jpg
index.html
- ...
在 index.html 处有 link 到 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 (and for http://example.com/test/ ) all will work well, because base for relative path will be http://example.com/test/ 并且我们在此文件夹中有 image.jpg。
将显示 http://example.com/test 页面,但没有图像。
这种情况下最好的解决办法是什么?
我认为你的意思是 $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
文件。
在 nginx root 上我们有这样的文件:
- test\
image.jpg
index.html
- ...
在 index.html 处有 link 到 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 (and for http://example.com/test/ ) all will work well, because base for relative path will be http://example.com/test/ 并且我们在此文件夹中有 image.jpg。
将显示 http://example.com/test 页面,但没有图像。
这种情况下最好的解决办法是什么?
我认为你的意思是 $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
文件。