简体   繁体   中英

NgInx forbidden error for static content nodejs app reverse proxy

I am using NgInx reverse proxy for my expressjs website with HTTPS. website is getting accessed with https without any issue and requests are getting at Nodejs server but problem is with Static content.

All static contents(JS, CSS, Images, fonts etc.) are throwing 403 forbidden error .

Below is my ngInx configuration file content:

server {
    listen  80;
    listen 443 ssl;
    ssl on;
    ssl_certificate /home/ec2-user/certs/myapp.bundle.crt; 
    ssl_certificate_key /home/ec2-user/certs/myapp.key;

    root /home/ec2-user/myapp;

    server_name example.com;
    access_log /var/log/nginx/nginx.vhost.access.log;
    error_log /var/log/nginx/nginx.vhost.error.log;

    location / {
       #try_files $uri $uri/ /index.php?$args ;
       #try_files $uri $uri/ =404;
        proxy_pass https://example.com:3000;
        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;
    }
}

I am using amazon EC2 and CentOS. Please help. Thanks in advance.

location / {
        proxy_pass https://example.com:3000;
        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;
    }

You are redirecting all traffic to to nodejs. Thats means expressjs will serve static content.

To serve static files, use the express.static built-in middleware function in Express.

Pass the name of the directory that contains the static assets to the express.static middleware function to start serving the files directly. For example, use the following code to serve static files in a directory named public:

app.use(express.static('public'))

More info here: https://expressjs.com/en/starter/static-files.html

You are trying to server static files from your NodeJS app which is not right approach since you are using Nginx. Add a below kind of block to you config

location ~ \.(css|gif|png|jpe?g|ico|js|swf|ttf|woff) {
    expires 30d;
    root /home/ec2-user/myapp;
    try_files $uri =404;
}

You might need to adjust the root folder based on how you are using your assets. But if you are using it same as /home/ec2-user/myapp then you can skip adding this line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM