nginx配置方法

在Mac OS X 上编译安装nginx,这也是实习中联调用到的第一个工具,值得mark一下

Posted by Lang Yicong on July 15, 2016
Nginx是一款面向性能设计的HTTP服务器,相较于Apache、lighttpd具有占有内存少,稳定性高等优势。

1. 安装PCRE库

可以在这里下载最新版

cd ~/Download

双击下载的压缩包解压缩,进入相应的文件夹

cd pcre-x.xx
sudo ./configure --prefix=/usr/local
sudo make
sudo make install

2.下载安装nginx

首先在nginx官网下载最新的源码

双击解压缩后,进入目录,配置环境,编译安装:

cd nginx-1.x.x
sudo ./configure --prefix=/usr/local --with-http_ssl_module --with-ld-opt="-L /usr/local/lib"
sudo make
sudo make install

3.启动Nginx

检查PATH环境变量

# ~/.bash_profile export PATH=/usr/local/bin:/usr/local/sbin:$PATH
cd /usr/local/sbin
sudo ./nginx

如果出现错误:

nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] still could not bind()

运行:

sudo killall nginx

来强制停止Nginx,如果不能起作用,就尝试下面的命令(stackoverflow查到的,这个问题搞了半天才解决)

pkill -9 nginx

最后访问http://localhost,可以看到如下画面,则说明nginx启动成功:

welcome to nginx

需要停止Nginx的时候运行

sudo nginx -s stop

4.配置和重新启动

重要的事情说三遍!用mac终端,不要用iterm!用mac终端,不要用iterm!用mac终端,不要用iterm!

sudo修改config文件

vim /usr/local/conf/nginx.conf

http模块内加入include语句,方便修改server

"include /Users/{yourusername}/nginx/nginx.conf;"

然后用文本编辑器修改配置文件模块

sudo open /Users/sherry/nginx/nginx.conf

server{}块定义了虚拟主机,下面是参考的server写法

server {
    listen 8081;   #本地访问的端口
    server_name localhost;  #本地访问需要输入的url
    location / {
        root /Users/sherry/getui/git/data-report-management/src;
        #无需转发,自动搜寻index.html
    }
    #通过以上配置,在浏览器输入localhost:8081即可访问index.html

    location ^~ /dataReport/ {  #/dataReport/下的内通过建立虚拟服务器访问
        proxy_set_header Host 192.168.2.159; #http_host
        proxy_pass http://192.168.2.159:8081; #后端主机和端口
    }
    
    #更多location配置
}

s重启nginx

sudo /usr/local/sbin/nginx -s reload

访问:http://localhost:8081 即可登录

根据后端接口文档,现在浏览器访问: http://localhost(主机名):8081(端口号)/dataReport/user/addUser.do 即可得到返回数据