3

Static files of expressjs app perfectly working when I browse the site from my server ip:port, but when the app serves from nginx, static file gives 404 . Here is my nginx conf:

upstream project { server localhost:6546; } server { listen 80; server_name example.com; access_log /var/log/nginx/example.com_access.log; error_log /var/log/nginx/example.com_error.log; location / { proxy_pass http://project/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location ~* \.(css|js|gif|jpe?g|png)$ { expires 168h; } 

and here is my expressjs code for static:

app.enable('trust proxy'); app.use(favicon(__dirname + '/public/favicon.ico')); app.use(express.static(__dirname + '/public')); app.set('view engine', 'ejs'); if (app.get('env') === 'production') { app.set('view cache', true); } 

1 Answer 1

3

Although express.js has built in static file handling through some connect middleware, you should never use it. Nginx can do a much better job of handling static files and can prevent requests for non-dynamic content from clogging node processes. here is an example of doing this:

http { ... server { ... location ~ ^/(images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) { root /home/ubuntu/expressapp/public; access_log off; expires max; } ... } } 
Sign up to request clarification or add additional context in comments.

4 Comments

can you explain why should i never use it?
Sure, in short it will use a lot of more machine resources serving those assets from Node than doing it from Nginx, so thinking in production... a way better to solve it this way... don't you think?
I guess you are right. anyways, maybe you can help me aswell :) i'm using your location regex and still getting 404 on static files. do i have to also on my app.js remove the express.static module? i set the root as /var/www/html/test/public and my css file is under /stylesheets. thanks!
mmm hard to help without actually seeing your conf... please open a question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.