【问题标题】:Make only 1 root file accessible, and serve it for all requests仅可访问 1 个根文件,并为所有请求提供服务
【发布时间】:2013-10-20 16:30:23
【问题描述】:

我实际上有这个工作,但我想知道我是否以最有效的方式这样做,或者我是否可以对我的 conf 文件进行任何改进。这是我正在尝试做的事情:

  1. 如果从根目录请求任何文件,我们应该始终提供“index.html”。不应访问其他文件,并且请求其他任何文件都应视为您请求“index.html”。目前我正在使用重写,但重定向也可以,而且可能更可取。
  2. 可以请求“/css”或“/js”下的任何文件,从那些不存在的目录请求文件应返回 404。

这是我当前的工作配置文件:

server {
  listen 80;
  server_name www.example.com;
  client_max_body_size 50M;

  root /var/www/mysite;

  location = /index.html {
  }

  # map everything in base dir to one file
  location ~ ^/[^/]*$ {
    rewrite ^/[^/]*$ /index.html;
  }

  location ~ ^/css/ {
  }

  location ~ ^/js/ {
  }
}

更新

我的最终 conf 文件在负载测试下速度更快,并且比原始文件更简单,在这里:

server {
  listen 80;
  server_name example.com;

  root /var/www/register;

  location = /index.html {
  }

  # Default location, request will fallback here if none other
  # location block matches
  location / {
    rewrite ^.*$ /index.html redirect; # 'root' location '/'
  }

  location /css/ {
  }

  location /js/ {
  }

}

【问题讨论】:

  • 虽然您的解决方案在技术上是正确的,但我建议将除 index.html(和 /css/、/js/)之外的所有内容移出 /var/www/mysite。 Nginx 是一个网络服务器,它的工作就是向网络提供文件。其他一切都是 hack ;)

标签: nginx


【解决方案1】:

我不确定我是否正确,但请检查此答案,您总是希望服务器 index.html 所以它应该是默认位置 location /

server {
    server_name example.com www.example.com;
    client_max_body_size 50M;
    root /var/www/mysite;
    index index.html;
    location / {
        try_files index.html =404;
    }
    location /(css|js) {
        try_files $uri =404;
    }
}

【讨论】:

  • 感谢您的回复。有几件事:位置指令不会像为 css/js 部分编写的那样工作——我相信你需要添加与~ 匹配的正则表达式,但我相信这比我上面更新的解决方案要慢。不需要 index 指令。最后一点,在我的负载测试中,try_files 解决方案的平均速度比上面更新的解决方案慢了大约 100 毫秒。
  • 哦,是的,我忘了添加正则表达式部分,是的,如果我将它们分成两个位置可能会更快,但我一直认为try_files 比重写更快,或者至少他们就是这样总是在文档中说..
  • 对不起,我相信 try_files 比 rewrite 更快——但是对于大多数请求都不会发生,也就是说,index.html 将是请求的文件。我应该在 OP 中澄清这一点。所以无论如何,我正在优化最常见类型的请求的速度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
相关资源
最近更新 更多