l2y*_*sho 5 nginx nginx-location
我有一个示例 Web 服务器,在 www 目录中只有一个 index.html 文件。我可以使用以下配置设置 nginx:
location /subfolder {
alias /data/www;
try_files $uri $uri/ /index.html;
}
Run Code Online (Sandbox Code Playgroud)
In browser I can see correct response on my local domain test.local/subfolder, also test.local/subfolder/something returns a default nginx page (it is normal because root is not set)
if I change a configuration to
location /subfolder {
alias /data/www;
try_files $uri $uri/ /index.html =404;
}
Run Code Online (Sandbox Code Playgroud)
response to test.local/subfolder is still correct, but test.local/subfolder/something and all URI with /subfolder prefix return a index.html of correct response also status is 200 not 404. If I remove /index from try_files I get the same result
I wonder how nginx process request with =404 fallback, but cant find any information, not even in a official docs.
UDAPTE:
I found out that a alias directive should end with an / but still dont get a =404 functionality and purpose because a status is still 200ok
Dan*_*nin 10
该try_files指令仅支持以下语法:
try_files file ... uri;
try_files file ... =code;
Run Code Online (Sandbox Code Playgroud)
它不支持:
try_files file ... uri =code;
Run Code Online (Sandbox Code Playgroud)
file和uri这里的区别在于,对于file参数,NGINX 会在继续下一个参数之前检查它们是否存在;因为uri,不会。
如果最后一个参数具有 a 的形式=code,则它的所有先前参数都是files(检查是否存在)。
由此,您可以得出结论,使用请求 URI/foo/bar和此配置:
root /var/www;
location /foo/ {
try_files $uri $uri/ =404;
}
Run Code Online (Sandbox Code Playgroud)
...如果file存在任何s,则不会触发 404 错误:
/var/www/foo/bar/var/www/foo/bar/目录(如果您已autoindex启用)/var/www/foo/bar/index.html(或index.php等)(由于 的值index)只有当以上都不存在时,NGINX 才会触发 404 错误。
You should define the root of your server, then the default indexes and then add the =404 to try_files:
server {
server_name example.com;
root /var/www/html/example.com;
index index.html index.htm index.php;
# This is optional - if you want a customized 404 error page
error_page 404 /404.html;
location /subfolder {
try_files $uri $uri/ =404;
}
}
Run Code Online (Sandbox Code Playgroud)
The difference between root and alias is that root appends location to get the absolute path in the filesystem while alias excludes the location. So for example when you try to fetch http://example.com/subfolder/filename.txt
server_name example.com;
root /var/www/html/example;
location /subfolder {
try_files $uri $uri/ =404;
}
Run Code Online (Sandbox Code Playgroud)
will return the contents of /var/www/html/example/subfolder/filename.txt (if it exists) while
server_name example.com;
location /subfolder {
alias /var/log;
try_files $uri $uri/ =404;
}
Run Code Online (Sandbox Code Playgroud)
will return the contents of /var/log/filename.txt (if it exists)
| 归档时间: |
|
| 查看次数: |
11351 次 |
| 最近记录: |