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()
})

最终我们返回的页面结果为:
image.png

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

你可能感兴趣的:(node.jsnginx)