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

4次阅读

共计 1067 个字符,预计需要花费 3 分钟才能阅读完成。

在 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 的映射!

正文完
 0