关于node.js:nginx的安装配置使其可以访问nodejs

在windows下装置非常简单
在http://nginx.org/en/download…. 下载压缩包(只有1.6M)
下载后解压,而后执行nginx.exe文件,OK!

在浏览器里输出 http://localhost:80/ 呈现nginx欢送界面!

启动nginx:
start nginx
nginx.exe
进行nginx:
nginx.exe -s stop
nginx.exe -s quit

能够写个stop.bat批处理文件:

nginx.exe -s stop

留神:第一次运行stop的时候会报个错:
nginx: [error] CreateFile() “E:\nginx\nginx-1.9.3/logs/nginx.pid” failed
意思是log文件未创立,执行上面的语句创立即可:

nginx -c conf/nginx.conf

装置nginx后,就能够反向代理拜访咱们的nodejs啦!这也是nginx的次要用法。

批改nginx的conf目录下的nginx.conf文件来配置咱们的网站!

看下nginx.conf的默认配置

server {
    listen       80;
    server_name  localhost;

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

listen 80 示意nginx监听的是80端口,也就是网站的默认拜访端口。server_name 能够设为域名或IP。
location里的root示意根目录,默认为nginx目录下的html子目录。
index示意如果不指定网页文件名,默认拜访的网页是index.html。

咱们当初指定一个路由到nodejs的get申请:
在配置文件里减少如下配置:

    location /getcode/
    {
        proxy_pass http://127.0.0.1:6060/code/;
    }

proxy_pass指向的就是代理路由,即如果咱们在浏览器中拜访http://localhost/getcode/ ,nginx就会指向拜访http://127.0.0.1:6060/code/ 。

下一步咱们在nodejs里应用express来回应这一get申请:

var app = express();
app.get('/code', function(req, res) {
    res.send('hello code!');
    res.end()
})

最终咱们返回的页面后果为:

*在理论的运行环境下部署,server_name设置为外网IP,proxy_pass设置为内网IP,这样实现了从外网IP到内网IP的映射!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理