1.Nginx 是什么
Nginx 是一个用C语言写的http以及反向代理 web服务器.
名词解释(正向,反向)
正向以及反向,主要判断方式就是
浏览器是否知道自己访问的是代理服务器.
正向: 浏览器设置代理服务器,然后把请求发送给代理请求服务器,然后代理服务器发送给目标服务器,代理接受目标服务器响应之后,解析完,再把结果返归给浏览器
反向:浏览器直接发起请求,代理服务器接收后,发给目标服务器,然后返回结果给代理,代理再把解析后结果发送给浏览器.
使用场景
1.反向代理、2.负载均衡、3.动静分离
2.Nginx 如何使用
命令:
./nginx 启动
./nginx -s reload 重新加载conf文件
./nginx -s stop 关闭nginx
配置:
conf配置一共分三个部分:全局 ,event, http
以下是一个conf demo例子示范配置:
负载均衡配置例子: /tomcatServer
反向代理配置例子: /test
动静分离(静态资源)配置例子: /static
#第一部分 大块配置:全局区
#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;
#第二大部分大块配置:event区
events {
# 支持单个worker进程最大的并发数
worker_connections 1024;
}
#第三部分大块配置,最主要的配置:http区
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;
# 使用代理,负载均衡
upstream tomcatServer {
consistent_hash $request_uri;
server localhost:8081;
server localhost:8082;
}
# 需要启动服务的配置
server {
#监听80端口
listen 80;
#监听 www.luacasnginx.com ip
server_name www.lucasnginx.com;
#charset koi8-r;
#access_log logs/host.access.log main;
#匹配相对路径
location / {
root html;
index index.html index.htm;
}
# 配置静态资源路径,在服务器的static文件夹下,alias与root有区别.下面会区分
location ^~/static {
alias /static/;
autoindex on;
}
#配置普通路径,若访问www.lucasnginx.com/tomcat 即反向代理去访问上面upstream的 #tomcatserver
location /tomcat {
proxy_pass http://tomcatServer/ ;
}
location /loginProject {
proxy_pass http://tomcatServer/LoginProject/;
}
location /test {
proxy_pass http://127.0.0.1:8080;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
注意点
静态资源配置:
ROOT 与alias 区别.用上面的 例子去说明
若使用root而不是alias的话.配置如下
location ^~/static {
root /static/;
autoindex on;
}
在浏览器访问的话,http://www.lucasnginx.com/static/login.html,表示想访问服务器上static文件夹里面的login.html文件;访问后会发现404。因为使用root的话,匹配了的url也会变成你要访问的路径内容,即 /static/static/login.html(实际是nginx自己解析出来的路径),但实际上我想用url识别到static后,把后面的url才当做具体要访问的路径,所以用alias
浏览器URL | 关键字 | 实际访问服务器路径 |
---|---|---|
http://www.lucasnginx.com/static/login.html | root | /static/static/login.html |
http://www.lucasnginx.com/static/login.html | alias | /static/login.html |