Nginx:高性能web服务器/反向代理器/缓存服务器
优点:简单稳定、模块化程度高、支持rwrite重写规则
缺点:动态处理差(nginx善于处理静态文件)、rwrite弱
基本使用方法:
查看nginx状态:systemctl status nginx
启动nginx服务:systemctl start nginx 、 nginx
关闭nginx服务:systemctl stop nginx 、 nginx -s stop
显示开启了哪些模块功能:nginx -V
基本目录:
工作目录 /etc/nginx
web目录 /var/www/html 首页文件 是index.nginx - debian.html
/usr/share/nignx/html 首页文件是index.html
日志目录 /var/log/html
命令执行文件:/usr/sbin/nginx
配置文件:
/etc/nginx/nginx.conf
全局配置段
http配置段
server配置段 项目、应用 对应一个域名
location配置段 对应url
关系:http >= server (>= location)
全局配置段HTTP配置段在 /etc/nginx/nginx.conf 所有nginx服务都会生效其中的配置
其他配置段放到指定目录中
每个域名(项目)就是一个server
每个url就是一个location配置段
访问原理:
1 浏览器拆分地址: 地址 + 路径
2 根据地址找nginx服务器
3 把路径交给指定server的location去处理
4 location找到对应文件后返回给浏览器
1中的地址两个目的: 找到网上服务器的地址,找server配置段里的名称进行匹配
配置详情
默认的ubuntu下的nginx会把nginx.conf拆分出来全局配置段和HTTP配置段在nginx.conf中,其他的放到指定的目录中,
server 和location放到了/etc/nginx/sites-enabled/default中,将新建的server location文件放到/etc/nginx/conf.d目录下,
配置文件修改 后:检查语法 nginx -t 重载服务 nginx -s reload
把域名配置到/etc/hosts中。
全局配置段
work_processes
envents >> work_connections
http配置段
sendfile
gzip
server配置段
server{
listen 指定监听地址
serverr_name 指定主机名 -- 一般用项目域名来代替
}
优先级:
listen > server_name
server {
listen 192.168.43.42:99;
server_name www.jf.com;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
location / {
}
}
location
location optional_modifier location_match {……}
optional_modifier(正则和普通) 匹配条件
优先级:
精确 > 优先 > 正则 > 通用
优先正则和普通正则区别:
优先正则匹配到合适的即结束,普通正则匹配到合适的条件时会继续向后匹配,并选最后一个
关于url尾部的/有如下注意事项;
对于访问网站域名后面的路径(http://jf.com/other/),尾部的‘/’很重要,
匹配样式 URL尾部的‘/’表示目录,没有‘/’表示文件,而且文件找不到的话,会发生重定向
/other/:表示服务器会自动去该目录下找对应的默认文件,
/other: 表示服务器会先去找other文件,找不到的话会将other当成目录,重定向到/other/,去该目录下找默认文件
root /var/www/html 一般会在两个地方出现,一是location 二是server中,表示该server下的所有location都来该目录下找文件
try_files $uri $uri/ =404 首先尝试去root规定的目录下去找url文件,如果没有uri文件就去uri目录下去找默认文件 ,若都没有则返回404
try_files 1.html 2.html /6.html 如果能找到指定的文件1/2.html,那么就返回相应内容,否则的话返回6.html的内容
alias 和root的区别
alias : 表示一个绝对路径,而且必须以“/”结尾,常用在location中
root : 表示location 匹配内容的相对路径 长用在server中
效果一:
location /img/ {
alias /var/www/image/;
}
访问http://localhost/img/,nginx找/var/www/image/目录下的文件
效果二:
location /img/ {
root /var/www/image;
}
访问http://localhost/img/, nginx找/var/www/image/img/目录下的文件