配置nginx动静分离全步骤
1、目的
高并发环境下,大量请求从服务器后端获取资源,给后台服务器造成了巨大的压力。因此,在发布代码时,需要将后端的静态资源放到nginx,形成动态文件和静态文件分离。静态文件就从nginx服务器上获取,动态文件就从后端服务器获取。
2、服务器加载静态资源的链路方式
(1)用户请求接口:
可以在hosts文件夹下设置:
192.168.52.130 gulimall.com
IP地址:代表nginx所在的服务器ip
域名代表要访问的接口;
(2)192.168.52.130服务器,接收到了80端口的请求,需要对gulimall.com这个域名进行处理。
配置文件如下:
[root@localhost conf]# vim nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
upstream gulimall{
server 10.49.103.92:88; ##对gulimall进行处理,路由到服务器的网关
}
server{ ##解析域名,映射到80端口
listen 80;
server_name gulimall.com
location / {
proxy_set_header Host $host;
proxy_pass http://gulimall;
}
}
include /etc/nginx/conf.d/*.conf;
}
cp default.conf gulimall.conf
cat gulimall.conf
server {
listen 80;
server_name gulimall.com;
#charset koi8-r;
#access_log /var/log/nginx/log/host.access.log main;
location /static/{
root /usr/share/nginx/html;
}
location / {
proxy_set_header Host $host;
proxy_pass http://gulimall;
}
#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 /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
docker restart nginx;
gulimall.com经过nginx路由到了服务器的网关服务,网关对gulimall.com进行断言
- id: gulimall_host_route
uri: lb://gulimall-product
predicates:
- Host=gulimall.com,item.gulimall.com
经过nacos,路由到了gulimall-product服务,gulimall-product的服务,再从nginx进行获取静态文件,而不用从后端服务器获取。
nginx服务器存储静态文件的地址:
gulimll-product的html里边只需要:
<img src="/static/index/img/top_find_logo.png" alt=""> 即可获取到nginx的静态资源。