【问题标题】:I can't serve static by nginx我不能通过 nginx 提供静态服务
【发布时间】:2013-05-20 03:58:39
【问题描述】:

我有以下 nodejs 结构,它位于 /home/ubuntu/project 目录中:

 sever
 site
   |-css
   |  |-styles.css
   |-img
   |  |-sprite.png
   |-js
     |-script.js

我正在尝试通过 nginx 提供静态资产,所以我写了以下位置:

upstream myapp_upstream {
    server 127.0.0.1:3000;
    keepalive 64;
}

server {
    listen 80;

    server_name www.myapp.com;

    error_page 400 404 500 502 503 504 /50x.html;
    location  /50x.html {
            internal;
            root /usr/share/nginx/www;
    }

    location ~ ^/(images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico|home/|html|xml) {
        root /home/ubuntu/project/site;
        access_log off;
        expires max;
    }

    location / {
        proxy_redirect off;
        proxy_set_header   X-Real-IP            $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_set_header   Host                   $http_host;
        proxy_set_header   X-NginX-Proxy    true;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_pass         http://myapp_upstream;
        proxy_intercept_errors on;
    }
}

但是当我尝试在浏览器中打开我的网站时,我在所有请求的资产上都出现了失败状态。有什么问题?

编辑: 例如,我的 css 路线是:

http://www.myapp.com/css/styles.css

【问题讨论】:

    标签: node.js ubuntu nginx


    【解决方案1】:

    嗯,

    / 添加到根路径。

    root /usr/share/nginx/www;
    

    应该是

    root /usr/share/nginx/www/;
    

    对资产使用alias,例如:

    alias /home/ubuntu/project/site/; (again, add the last /)
    

    这对我来说是一团糟:

    location ~ ^/(images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico|home/|html|xml)
    

    你应该检查这些http://wiki.nginx.org/NginxHttpCoreModule#location

    我在您的站点地图中没有看到这些文件夹images/, javascript/, stylesheets/, flash/, media/, static/ and home/

    这两个|html|xml 都在寻找路线/html/xml 而不是.html.xml 文件。

    那就试试吧:

    location ~ ^/(robots.txt|humans.txt) {
        alias /home/ubuntu/project/site/;
        access_log off;
        expires max;
    }
    
    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {  //add here all the file extensions needed.
        alias /home/ubuntu/project/site/;
        access_log off;
        expires max;     
    }
    

    【讨论】:

    • 嗯。这似乎可行,但现在我遇到了另一个问题。当我尝试像 myapp.com/css/styles.css 这样请求 css 时,我会以 403 错误回复到 myapp.com/css/styles.css
    • 是的,我通过在末尾添加 root 代替别名和 '/' 解决了这个问题
    猜你喜欢
    • 2010-12-01
    • 2011-01-27
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 2016-11-01
    相关资源
    最近更新 更多