windows下nginx配合nodejs进行反向代理

2021/6/5 7:24:42

本文主要是介绍windows下nginx配合nodejs进行反向代理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文原创,转载请附上原作者链接!https://www.cnblogs.com/LSWu/articles/14848324.html

1.安装node.js

        从node.js官网上下载node.js的LTS安装包,然后正常安装即可,安装完成后,node.js自带的npm工具也会相应的安装好。然后在命令行下输入node -v和npm -v,返回如下信息说明安装成功。

1 lishanwu@Lenovo-PC MINGW64 ~/Desktop/nodejs_test
2 $ node -v
3 v14.16.1
4 
5 lishanwu@Lenovo-PC MINGW64 ~/Desktop/nodejs_test
6 $ npm -v
7 6.14.12

2.安装nginx服务器

  从nginx官网上下载对应windows的LTS的nginx压缩包,然后解压到目标目录即可,然后双击ngnix.exe,或者在当前目录下打开命令行,输入nginx.exe ,即可启动nginx服务器。然后在浏览器上输入localhost,看到如下画面则认为nginx已经安装完成。如果想关闭nginx,则在命令行下输入nginx -s stop即可关闭nginx服务器,重启服务器则使用nginx -s reload

 

 

 注意如果在git下,则使用./nginx.exe来启动服务器,使用./nginx.exe -s stop来停止服务器,使用./nginx.exe -s reload来重启服务器。

3.配置nginx进行反代理

  nginx的解压后有一个conf目录,下面存放着很多匹配文件,想要让nginx进行反代理服务,需要对nginx.conf文件进行配置。修改nginx.conf文件如下所示

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        
        #这里简单设置一下反向代理
        location /api/ {
            proxy_pass http://192.168.x.xxx:4000; #我的本机ipv4地址,最好不要用localhost或者127.0.0.1,血的教训<-_->
        }
     #我的nodejs所在主机的ip为192.168.xxx.x:4000    
     #我的nginx所在主机的ip为192.168.xxx.x,将这里改为自己的本机ip,我不想被网络攻击,所以不能贴出我的ip


        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

  然后重启nginx服务器,注意在进程管理器中确保在重启前关闭nginx的进程,然后再启动nginx服务器。

 

4.编写nodejs后端的测试代码,然后启动nodejs服务

  main.js如下所示

var express = require('express');
var app = express();
var fs = require("fs");

app.get('/api/test0', function (req, res) {
    console.log(req.url);
    res.setHeader("Content-Type", "text/html;charset=utf-8")
    res.end( "<h2>accessed test0</h2>" ); 
})

app.get('/api/test1', function (req, res) {
    res.setHeader("Content-Type", "text/html;charset=utf-8")
    res.end( "<h2>accessed test1</h2>" );
})

app.get('/api/test1/setting', function (req, res) {
    res.setHeader("Content-Type", "text/html;charset=utf-8")
    res.end( "<h2>this is setting of test1</h2>" );
})

var server = app.listen(4000, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("应用实例,访问地址为 http://%s:%s", host, port)
})

 

  启动nodejs前需要下载express依赖包,使用npm install  --save express,然后node main.js启动nodejs服务(注意不要关了,否则nginx无法访问)。

5.测试

  在浏览器中输入http://localhost/api/test0 ,可以看到如下所示的结果,说明通过nginx反代理成功访问到nodejs,注意这里没有加端口号,默认通过80端口访问nginx。

 

   然后在浏览器中输入http://localhost/api/test1 ,可以看到如下所示结果

 

   接着再输入http://localhost/api/test1/setting,可以看到如下结果

 

 

  从上面可以看到,通过访问不同的url可以将其通过nginx反向代理到nodejs中,nodejs并将处理的结果返回给nginx,然后nginx再将结果返回个浏览器。方向代理有一个很大的好处就是可以实现负载均衡和跨域访问。

 

6.总结

  在使用nginx进行反代理的时候很容易将其反代理的ip或域名设为127.0.0.1或localhost,经过多次试验发现,当设置为localhost后,需要刷新页面两次才有返回结果,这显然不正常,而使用127.0.0.1后,有多次直接返回404,所以为了确保每次都能正常访问,最好将nginx的反代理的ip设为本机ip,例如192.168.xxx.x,域名则设置为备案后的域名(大陆),对于本机,在windows下使用ipconfig命令查看ip地址,linux下使用ifconfig查看ip地址。网上的教程大多都是直接设置localhost或者127.0.0.1,笔者强烈建议将其设置为本机ip

 



这篇关于windows下nginx配合nodejs进行反向代理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程