【问题标题】:Serving static website in nginx, wrong path for static files在 nginx 中提供静态网站,静态文件的路径错误
【发布时间】:2019-08-04 06:50:09
【问题描述】:

我正在尝试使用 nginx 来提供给我的静态网站。它的文件夹结构是这样的:

static_website/
    index.html
    www.example.com/
    resources.example.com/
    uploads.example.com/

根目录中的index.html 文件是httrack 生成的文件,它只包含到www.example.com/index.html 的重定向。 在文件夹www.example.com 中是所有html 文件,在另外两个文件夹中是cssjavascriptimage 文件。

这里是nginx配置:

server {
    index index.php index.html index.htm;

    server_name example.com;

    location / {
        root /var/www/static_website/www.example.com;
        try_files $uri $uri/ =404;
        index index.html;
    }

}

我可以浏览页面,但没有加载 css、javascript 和图像文件。 html中的一个css文件的路径是这样的:

href="../resources.example.com/style.css"

我设法让这个工作的唯一方法是拥有这样的网址:

example.com/www.example.com/

这样,所有路径都是正确的。我想避免这种情况,只需使用 example.com。 有没有办法做到这一点?

【问题讨论】:

  • 尝试添加另一个匹配所有资源文件的location,例如:location ~ \.(css|js|jpg|png|svg)$ { root /var/www/static_website; }
  • 谢谢,就是这样。如果您将其添加为答案而不是评论,我可以将其标记为已接受

标签: nginx nginx-config


【解决方案1】:

看起来该网站最初是打算使用像 //example.com/www.example.com/ 这样的丑陋 URL 来操作的。

但是相对于/,资源的路径相对URI 应该可以正常工作,您只需要提供一个与/resources.example.com/ 匹配的location 块。

例如:

location / {
    root /var/www/static_website/www.example.com;
    try_files $uri $uri/ =404;
    index index.html;
}
location /resources.example.com/ {
    root /var/www/static_website;
}

我最初评论说你应该试试这个:

location ~ \.(css|js|jpg|png|svg)$ { 
    root /var/www/static_website;
}

这实现了类似的目标,但 Nginx 将比正则表达式位置更有效地处理前缀位置。

【讨论】:

    【解决方案2】:

    我想与其他遇到类似问题的人分享我在这个问题上的经验,因为解决方案对我来说不是那么明显

    我的设置和问题尤其与我用来利用 TLS 而不是在我的 2 个站点之一的源服务器上处理它的 cloudlflare 设置有关。如果您从支持加密的 CDN 为您的站点提供服务,并且您在源上使用 nginx,请考虑以下设置:

    # static1.conf
    { server_name static1.com; root: /var/www/static1/public; listen 80; listen 443; }
    
    # static2.conf - no tls setup in nginx, figured id let cloudflare handle it
    { server_name static2.com; root: /var/www/static2/public; listen 80; }
    

    static1 在源头设置了letsencrypt 来处理tls 连接

    static2 是在原点设置的,没有任何 tls 配置

    从左到右,这里是适当的 cloudlfare TLS 模式,它允许我通过 nginx 访问正确的文件

    fullflexible 的区别在于 full 模式让源端处理证书。

    最初我将 static2 站点错误配置为已满,它缺少 443 的监听指令,导致 nginx 改为服务于 static1。

    我意识到最初的问题与 cdn 或 cloudflare 无关,但这种方案/协议不匹配花费了我几个小时,我希望能帮助其他人免于类似的痛苦

    老实说,我很惊讶 nginx 不坚持匹配 server_name 并且 oit 隐式匹配方案作为后备(或至少看起来),即使没有指定 default_server - 并且在日志中没有任何有意义的消息要引导!调试 nginx 有时是一场噩梦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 2015-10-19
      • 2021-09-03
      相关资源
      最近更新 更多