Multiple Location For Static Location in Nginx Con

2019-05-13 18:28发布

I have a two locations where my app will serve static files, one is /my/path/project/static and the other is /my/path/project/jsutils/static.

I'm having a hard time getting the webserver to look in both directories for static content. Here is my entry for static location in the nginx configuration file for my app.

    location ^~ /static {
        root   /my/path/project/static;
        alias /my/path/project/jsutils/static;
       index  index.html index.htm;
    }

I get an error that says : "alias" directive is duplicate, "root" directive was specified earlier.

I'm not sure how to go about having nginx look in both these paths for static content.

Thank you in advance for any help.

标签: nginx
4条回答
孤傲高冷的网名
2楼-- · 2019-05-13 19:07

Just implement your configuration in nginx language:

location /my/path/project/static {
  try_files $uri =404;
}
location /my/path/project/jsutils/static {
  try_files $uri =404;
}
查看更多
Lonely孤独者°
3楼-- · 2019-05-13 19:07

I had the exact same problem and it looks like nginx doesn't like when root is overwritten by an alias. I fixed it by firstly removing the root declaration that was inside the server section and instead declared the root and alias appropriately directly in the location sections (note the commented out lines):

server {
#    root /usr/share/nginx/html;
    location /logs/ {
        root /home/user/develop/app_test;
        autoindex on;
    }
    location /logs2/ {
#        root /home/user/branches/app_test;
        alias /home/user/branches/app_test/logs/;
        autoindex on;
    }
}
查看更多
欢心
4楼-- · 2019-05-13 19:08
location ^~ /static {
    root /my/path/project/static;
    index index.html index.htm;
    try_files $uri $uri/ @secondStatic;
}

location @secondStatic {
    root /my/path/project/jsutils/static;
}

So first the file will be searched in /my/path/project/static and if that could not be found there, the secondStatic location will be triggered where the root is changed to /my/path/project/jsutils/static.

查看更多
混吃等死
5楼-- · 2019-05-13 19:20

You may use try_files (http://wiki.nginx.org/HttpCoreModule#try_files). Assuming that you static files are in /my/path/project/static and /my/path/project/jsutils/static. you can try this:

location ^~ /static {
   root   /my/path/project;
   index  index.html index.htm;
   try_files $uri $uri/ /jsutils$uri /jsutils$uri/ =404;
}

Let me know if it works. Thanks!

查看更多
登录 后发表回答