nginx + nodejs配置

 手机用户2502916857 发布于 2023-02-08 18:31

我的当前nginx配置有问题.我想要做的是:

对于没有任何路径的请求,获取index.html(有效)

直接获取现有文件(有效)

如果请求的文件或路径实际上不存在,则向nodejs发送代理请求(404)

我在stackoverflow上尝试了几种配置,但它们都不符合我的需求.

这是我目前的配置:

# IP which nodejs is running on
upstream app_x {
    server 127.0.0.1:3000;
}

# nginx server instance
server {
listen 80;
server_name x.x.x.x;
#access_log /var/log/nginx/x.log;

root /var/www/x/public;

location / {
    root /var/www/x/public;
    index index.html index.htm index.php;
}

location ^/(.*)$ {
    if (-f $request_filename) {
        break;
    }
    proxy_set_header Host $http_host;
    proxy_pass http://127.0.0.1:3000;
}
}

mekwall.. 12

我想我弄明白你要做什么.正确的方法是try_files与命名位置一起使用.

尝试使用以下配置:

# IP which nodejs is running on
upstream app_x {
    server 127.0.0.1:3000;
}

# nginx server instance
server {
    listen 80;
    server_name x.x.x.x;
    #access_log /var/log/nginx/x.log;

    location / {
        root /var/www/x/public;
        index index.html index.htm index.php;
        try_files $uri $uri/ @node;
    }

    location @node {
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://app_x;
    }
}

注意:当你有一个上游定义时,你应该在你的proxy_ pass.此外,在代理时,始终添加X-Forwarded-For标头.

1 个回答
  • 我想我弄明白你要做什么.正确的方法是try_files与命名位置一起使用.

    尝试使用以下配置:

    # IP which nodejs is running on
    upstream app_x {
        server 127.0.0.1:3000;
    }
    
    # nginx server instance
    server {
        listen 80;
        server_name x.x.x.x;
        #access_log /var/log/nginx/x.log;
    
        location / {
            root /var/www/x/public;
            index index.html index.htm index.php;
            try_files $uri $uri/ @node;
        }
    
        location @node {
            proxy_set_header Host $http_host;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_pass http://app_x;
        }
    }
    

    注意:当你有一个上游定义时,你应该在你的proxy_ pass.此外,在代理时,始终添加X-Forwarded-For标头.

    2023-02-08 18:33 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有