当前位置: 首页 > 后端技术 > Node.js

nginx的安装配置允许它访问nodejs

时间:2023-04-03 16:20:18 Node.js

windows下安装很简单,在http://nginx.org/en/download....下载压缩包(只有1.6M),下载后解压,然后执行nginx.exe文件,OK!在浏览器输入http://localhost:80/,出现nginx欢迎界面!启动nginx:startnginx或nginx.exe停止nginx:nginx.exe-sstop或nginx.exe-squit可以写一个stop.bat批处理文件:nginx.exe-sstop注意:第一次运行stop时会报错:nginx:[error]CreateFile()"E:\nginx\nginx-1.9.3/logs/nginx.pid"failed表示日志文件还没有创建,执行下面语句创建:nginx-cconf/nginx.conf安装好nginx后,就可以反向代理访问我们的nodejs了!这也是nginx的主要用法。修改nginx的conf目录下的nginx.conf文件来配置我们的网站!查看nginx.conf的默认配置server{listen80;服务器名称本地主机;位置/{根html;indexindex.htmlindex.htm;}...listen80表示nginx监听80端口,这是网站默认访问的端口。server_name可以设置为域名或IP。location中的root表示根目录,默认为nginx目录下的html子目录。index表示如果不指定网页文件名,默认访问的网页是index.html。我们现在指定一个路由到nodejs的get请求:在配置文件中添加如下配置:location/getcode/{proxy_passhttp://127.0.0.1:6060/code/;}proxy_pass指向代理路由,即如果我们在浏览器中访问http://localhost/getcode/,nginx会指向访问http://127.0.0.1:6060/code/。接下来,我们在nodejs中使用express来响应这个get请求:varapp=express();app.get('/code',function(req,res){res.send('hellocode!');res.end()})最后我们返回的页面结果是:*在实际运行环境中部署,server_name设置为外网IP,proxy_pass设置为内网IP,这样从外网映射IP到内网IP就实现了!