大网数据广告活动
服务器运维问答

nginx: use try_files to serve file instead of directory

· 52CE 我爱测

My server uses nginx, and my domain serves static html web pages, i.e. http://server.com/download.html For various reasons, I would like that users are able to fetch download.html through the following URLs: http://server.com/dow…

问题原文

原帖链接 · cruppstahl · CC BY-SA 3.0

My server uses nginx, and my domain serves static html web pages, i.e.

http://server.com/download.html

For various reasons, I would like that users are able to fetch download.html through the following URLs:

http://server.com/download.html  (works)
http://server.com/download       (works)
http://server.com/download/      (works not)

I got the first two working, but the last one always returns /404.html.

Is try_files able to do what I want, or do I have to use the rewrite directive instead?

My nginx configuration:

location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri.html $uri/ /404.html;
    # auth_basic "Restricted";
    # auth_basic_user_file /var/www/upscaledb/htpasswd;
}

Thanks, Christoph

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 3.0

If you add a location to rewrite the URI without the trailing slash, then your existing location / and try_files directive can do the rest:

location ~ ./$ { 
    rewrite ^(.+)/$ $1 last; 
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-02-11)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。