想起夕阳下的奔跑,那是我逝去的青春

0%

Mac下Nginx-Nodejs配置

由于nodejs的特性,无法加载静态文件,可以使用nginx代理静态文件

nodejs

你需要安装nodejs,网上很多教程,安装好了之后,使用以下命令来查看 node 的版本号

1
node -v

nginx.conf配置

首先安装好 nginx,一般在 /usr/local/ect/nginx/目录下,
可以使用 vim 编辑 nginx.conf

1
2
1.access_log  /usr/local/etc/nginx/access.log;
2.error_log /usr/local/etc/nginx/error.log;

两个都是日志文件,有时候你的nginx一些报错啊之类的,你可以在这个日志文件里查看一些信息。
,现在来配置 node 在nginx 里的 server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server {
listen 80;
server_name rogue.nginx.com;

proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_buffering on;

location / {
proxy_pass http://127.0.0.1:3000/;
}

location /static/ {
alias /Users/rogueandy/Documents/sourcetree_projects/node_server/static/;
index index.html;
}
}

解释一下以上的代码, listen端口,一般nginx默认的端口是80,不需要,当你在输入链接地址的时候,默认的80端口不需要键入,

1
2
3
4
5
server_name rogue.nginx.com
代表你的域名地址,配置好了这个之后,你还需要在
/etc/hosts
文件里,添加一行代码
127.0.0.1 rogue.nginx.com,添加域名到hosts

其他的 proxy代码则是一些基本设置

1
proxy_pass http://127.0.0.1:3000/;

这行代码,是本地默认的 node 的代码,反向代理的地址。
现在,比如在我的项目里,有个静态的 css 文件,具体的地址是

1
/Users/rogueandy/Documents/sourcetree_projects/node_server/static/common/reset.css

以上是我的css文件的完整地址,然后,我需要在配置nginx的时候,把这个地址,配置到nginx.conf里,看以下的代码

1
2
3
4
location /static/ {
alias /Users/rogueandy/Documents/sourcetree_projects/node_server/static/;
index index.html;
}

/static/ 这个代表着访问地址的一个类似 api,alias里面代表的是,你映射到的地址的目录,而 index 由于 alias 是绝对地址,你可以忽略,那么,现在可以写出我的浏览器打开的完整的css的地址

1
rogue.nginx.com/static/common/reset.css

在本地的浏览器输出这个地址,则会打开我本地的reset.css文件。