Nginx使用教程
1 概述
nginx是俄罗斯人开发的一个开源的,支持高性能、高并发的 Web 服务和代理服务软件。
官网地址:https://nginx.org/
2 用法
2.1 部署静态资源(location)
Nginx作为高性能web容器可以用于部署静态资源
例如:此处我们使用域名的方式来感受最大程度模拟生产真实场景(并未购买真实域名,只是测试。域名在满足命名规范的前提下,随意命名即可)
- 修改本地hosts文件
web请求网页过程:先找本地hosts缓存,然后请求DNS服务器
windows:C:\Windows\System32\drivers\etc\hosts
linux:在/etc目录下
添加如下配置:
# 以下的含义是如果请求下面的域名则访问127.0.0.1
127.0.0.1 www.xuecheng-plus.com file.xuecheng-plus.com ucenter.xuecheng-plus.com teacher.xuecheng-plus.com
- 下载nginx
- 修改conf配置文件
server {
listen 80;
server_name www.xuecheng-plus.com localhost;
#rewrite ^(.*) https://$server_name$1 permanent;
#charset koi8-r;
ssi on;
ssi_silent_errors on;
#access_log logs/host.access.log main;
location / {
alias D:/itcast2022/xc_edu3.0/code_1/xc-ui-pc-static-portal/;
index index.html index.htm;
}
#静态资源
location /static/img/ {
alias D:/itcast2022/xc_edu3.0/code_1/xc-ui-pc-static-portal/img/;
}
location /static/css/ {
alias D:/itcast2022/xc_edu3.0/code_1/xc-ui-pc-static-portal/css/;
}
location /static/js/ {
alias D:/itcast2022/xc_edu3.0/code_1/xc-ui-pc-static-portal/js/;
}
location /static/plugins/ {
alias D:/itcast2022/xc_edu3.0/code_1/xc-ui-pc-static-portal/plugins/;
add_header Access-Control-Allow-Origin http://ucenter.xuecheng-plus.com;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET;
}
location /plugins/ {
alias D:/itcast2022/xc_edu3.0/code_1/xc-ui-pc-static-portal/plugins/;
}
#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;
}
}
server_name www.xuecheng-plus.com localhost;
指的是如果请求www.xuecheng-plus.com 域名则访问localhost。
location /static/img/ {
alias D:/itcast2022/xc_edu3.0/code_1/xc-ui-pc-static-portal/img/;
}
指的是如果满足路径匹配/static/img/
的话,则请求:/itcast2022/xc_edu3.0/code_1/xc-ui-pc-static-portal/img/下的文件
2.2 反向代理(server)
为了实现负载均衡,有时我们不会直接让浏览器去请求服务器,而是让中间商
nginx
去请求
例如,我们配置nginx代理访问文件服务器
#文件服务 upstream释义:上游
upstream fileserver{
server 192.168.101.65:9000 weight=10;
}
server {
listen 80;
server_name file.xuecheng-plus.com;
#charset koi8-r;
ssi on;
ssi_silent_errors on;
#access_log logs/host.access.log main;
location /video {
proxy_pass http://fileserver;
}
location /mediafiles {
proxy_pass http://fileserver;
}
}
修改配置文件之后,记得重新加载nginx
nginx.exe -s reload
通过http://file.xuecheng-plus.com/video/视频文件地址 访问视频
通过http://file.xuecheng-plus.com/mediafiles/图片文件地址 访问图片
2.3 负载均衡(upstream weight)
假如我们的文件服务部署了多台,我们需要根据不同的服务器性能来修改服务器的处理请求占比
修改conf配置文件:
upstream fileserver{
server 192.168.101.65:9000 weight=10;
server 192.168.101.66:9000 weight=20;
server 192.168.101.67:9000 weight=20;
}
# 重新加载配置文件
nginx.exe -s reload