别名使用--prefix而不是server block的root

时间:2014-08-06 11:19:53

标签: nginx

我正在尝试设置nginx服务器并为我的静态文件添加别名。

server {
    # Listen on localhost:8000;
    listen 8000;

    # Should be the root
    root /Users/rouvenherzog/Documents/projects/nd;

    # host matches localhost
    server_name localhost;

    location / {
        proxy_pass http://localhost:5000;
    }

    location /favicon.ico {
            root /Users/rouvenherzog/Documents/projects/nd/n/n/static/img;
    }

    location ~ /([\w]+)/n/static/(.*) {
            alias n/n/static/$2;
    }

    location ~ /([\w]+)/nb/static/(.*) {
            alias nb/nb/static/$2;
    }
}

请求静态文件时,它会在nginx --prefix文件夹(即/usr/local/Cellar/nginx/1.6.0_1)中查找它们,而不是根文件夹。

例如:

open() "/usr/local/Cellar/nginx/1.6.0_1/n/n/static/neb/js/javascript.js" failed
(2: No such file or directory),
client: 127.0.0.1,
server: localhost,
request: "GET /pages/n/static/neb/js/javascript.js HTTP/1.1",
host: "localhost:8000",
referrer: "http://localhost:8000/pages/n/"

知道为什么吗?

非常感谢!


正如@akawhy建议的那样,使用重写而不是别名可以工作并尊重根路径。

server {
    # Listen on localhost:8000;
    listen 8000;

    # Should be the root
    root /Users/rouvenherzog/Documents/projects/nd;

    # host matches localhost
    server_name localhost;

    location / {
        proxy_pass http://localhost:5000;
    }

    location /favicon.ico {
            root /Users/rouvenherzog/Documents/projects/nd/n/n/static/img;
    }

    location ~ /([\w]+)/n/static/(.*) {
        rewrite ^([\w]+)/n/static/(.*)$ /n/n/static/$2 break;
    }

    location ~ /([\w]+)/nb/static/(.*) {
        rewrite ^([\w]+)/nb/static/(.*)$ /nb/nb/static/$2 break;
    }
}

1 个答案:

答案 0 :(得分:1)

因为您的别名指令使用了相对路径。我认为你应该使用绝对路径。

您可以查看此nginx alias+location directive