How do you serve static files from an nginx server

2019-01-18 03:06发布

问题:

My current nginx config is this:

upstream nodejs {
    server 127.0.0.1:3000;
}

server {
    listen 8080;
    server_name localhost;
    root ~/workspace/test/app;
    index index.html;

    location / {
        proxy_pass http://nodejs;
        proxy_set_header Host $host ; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

I'm very very new to nginx, but at the very least I know that nginx is better than node/express at serving static files. How can I configure the server so that nginx serves the static files?

回答1:

I solved it using this new configuration:

upstream nodejs {
    server localhost:3000;
}

server {
    listen 8080;
    server_name localhost;
    root ~/workspace/test/app;

    location / {
        try_files $uri @nodejs;
    }

    location @nodejs {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_pass http://nodejs;
        proxy_set_header Host $host ; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Thanks to the following Stack Overflow post:


How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.



回答2:

You'll probably want another location block within your server for the static files.

location /static {
  alias /path/to/static/files;
}

This uses the alias directive. Then you can hit files at localhost:8080/static/some_file.css

P.S. You don't need the root or index that you have set currently. (root is similar to alias with a slight difference in usage)



标签: node.js nginx