Nginx nodejs 站点静态内容-404 错误,但通过 ip 直接访问时有效

Nginx nodejs 站点静态内容-404 错误,但通过 ip 直接访问时有效

我正在尝试将 nginx 与我的 nodejs 网站一起使用,但我遇到了 nginx 配置问题。最初我无法显示我的 css 或图像,但我通过添加以下内容解决了这个问题:

位置 /images { 根路径到我的项目图像文件夹 }

但是,我在访问网站上的其他页面时遇到了问题。我有一个登录系统,当用户登录时,网站会将他们带到“mydomainname.com/home”,但当发生这种情况时,我会收到 404 错误。在我的 nodejs 代码中,我通过以下方式将用户发送到主页:

//should be logged in so show main search page
    app.get('/home', function(req, res) {
        if (req.session.user == null){
            // if user is not logged-in redirect back to login page //
            res.redirect('/');
        }   else{
            res.sendFile(path.join(__dirname + '/FrontEnd/home.html'));
        }
    });

我的项目结构如下:

ProjectNameFolder:
1. public
  1.1 FrontEnd
    1.1.1 login.html
    1.1.2 home.html
  1.2 Lots of other javascript files, some for front-end some for server

如果我通过在浏览器中输入它的 IP 直接连接到我的服务器,一切都会正常工作,但我猜这是绕过了 nginx。

Nginx配置:

location /css {
  root /home/adam/NodeProject/public/FrontEnd/;
}
location /images {
  root /home/adam/NodeProject/public/FrontEnd/;
}
location / {
  try_files $uri $uri/ = 404;
  proxy_pass http://localhost:8888;
  .... other proxy stuff, like setting headers
}

抱歉,如果这有点冗长,我已尽力提供尽可能多的清晰度。

编辑-根据要求的服务器块:

Server {
listen 80;
listen [::]:80;
server_name mydomain.com www.mydomain.com
return 301 https://$host$request_uri;
}

server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
root /home/adam/NodeProject/public/;
index index.php index.html index.jpg
server_name mydomain.com www.mydomain.com;
ssl_certifiate /home/adam/SSL/public.crt;
ssl_certificate_key /home/adam/SSL/mydomain.com.key;
        location ~ \.js {
                add_header Content-Type application/x-javascript;
        }

        location ~ \.(css|png|jpg|jpeg|gif|ico|html|woff|woff2|ttf|svg|eot|otf)$ {
                add_header "Access-Control-Allow-Origin" "*";
                expires 1M;
                access_log off;
                add_header Cache-Control "public";
        }

location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                #try_files $uri $uri/ =404;
                #try_files $uri $uri/ /FrontEnd/ =404;
                #try_files $uri
                #       /$server_name$uri
                #       /shared$uri;

                index login.html home.html;

                try_files $uri $uri/ =404;

                proxy_pass http://MY_SERVER_IP:8888;
                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 ~ \.js {
                add_header Content-Type application/x-javascript;
        }
}

相关内容