一、安装 Nginx
终端执行命令:
brew install nginx
安装之后执行命令:
brew info nginx
出现以下信息:
/usr/local/etc/nginx/nginx.conf (配置文件路径)
/usr/local/var/www (服务器默认路径)
二、访问localhost:8080
open /usr/local/Cellar/nginx //其实这个才是nginx被安装到的目录
会看到一个以当前安装的nginx的版本号为名称的文件夹,这个就是我们安装的nginx根目录啦。进入1.12.2/bin 目录,会看到nginx的可执行启动文件。
同样的,我们在1.12.2/目录下还可以看到一个名字为html的快捷方式文件夹(暂且就这么叫吧),进入该目录我们会发现其实它指向的就是/usr/local/var/www目录,这个在上面我们查看的info信息中有提到(Dcroot)
执行nginx命令,开启服务器
nginx
Nginx 默认8080端口,这时已经可以访问了:
localhost:8080
如果出现欢迎界面,说明安装成功.
二、配置文件终端输入命令:
cat /usr/local/etc/nginx/nginx.conf
显示信息
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
#侦听8080端口
listen 8080;
#定义使用 localhost访问
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#定义服务器的默认网站根目录位置
root html;
#定义首页索引文件的名称
index index.html index.htm;
}
...
...
... (注释代码太多,就不全部贴出来了)
include servers/*;
}
通过配置文件我们可以看到其默认的网站根目录为html(即/usr/local/var/www),而默认的索引文件为index.html 和 index.htm.
手动创建一个index2.html
cd /usr/local/var/www/ //进入到www目录下
touch index2.html //创建一个新的index.html文件
vi index2.html //编辑该文件
在index2中加入代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<div>
<h1>我的nginx欢迎页面</h1>
</div>
</body>
</html>
保存退出.
在浏览器中输入localhost:8080/index2.html
同一网域下访问该文件,将localhost换成自己mac的ip地址
例如IP地址为10.0.0.17,在手机端输入http://10.0.0.17:8080/index2.html
访问到index2.html的内容;
三、nginx常用命令
sudo nginx #打开 nginx
nginx -s reload|reopen|stop|quit #重新加载配置|重启|停止|退出 nginx
nginx -t #测试配置是否有语法错误
nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]
-?,-h : 打开帮助信息
-v : 显示版本信息并退出
-V : 显示版本和配置选项信息,然后退出
-t : 检测配置文件是否有语法错误,然后退出
-q : 在检测配置文件期间屏蔽非错误信息
-s signal : 给一个 nginx 主进程发送信号:stop(停止), quit(退出), reopen(重启), reload(重新加载配置文件)
-p prefix : 设置前缀路径(默认是:/usr/local/Cellar/nginx/1.2.6/)
-c filename : 设置配置文件(默认是:/usr/local/etc/nginx/nginx.conf)
-g directives : 设置配置文件外的全局指令