静态资源拆分
将项目中静态资源【wwwroot】拆分到其他文件夹中,新建一个StaticResource文件夹,如图:
因项目中没有了静态资源文件,导致页面布局混乱,如图:
所以需要在Nginx服务器中配置静态文件,配置代码如下:
location ~ \.(ico|js|css|png|jpg|mp4)$ {
root 静态资源路径;
}
整体配置如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location / {
proxy_pass http://Demo.Application;
}
location ~ \.(ico|js|css|png|jpg|mp4)$ {
root D:/StaticResource/wwwroot;
}
}
upstream Demo.Application{
least_conn;
server localhost:5000;
server localhost:5001;
}
}
运行结果如图:
按照以上的nginx配置,动态数据与静态资源还是共享CPU资源的 ,那么依然没有解决当并发量过大,动态资源将cpu和内存等资源耗尽,导致静态资源无法访问的问题,所以我们要将动态数据和静态资源放在不同的虚拟主机中,配置代码如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 801;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location / {
proxy_pass http://Demo.Application;
}
}
server {
listen 80;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location / {
proxy_pass http://localhost:801;
}
location ~ \.(ico|js|css|png|jpg|mp4)$ {
proxy_pass http://localhost:802;
}
}
server {
listen 802;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~ \.(ico|js|css|png|jpg|mp4)$ {
root D:/StaticResource/wwwroot;
}
}
upstream Demo.Application{
server localhost:5001;
}
}
按照以上的建立两个不同的虚拟机,但是还在一个Nginx当中,还是会存在资源竞争的问题,所以要将动态数据和静态资源放在不同的Nginx当中,【推荐使用这种方式】实现如下:
-
Nginx 1 动态数据 配置文件如下
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 801;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location / {
proxy_pass http://Demo.Application;
}
}
upstream Demo.Application{
server localhost:5001;
}
}
-
Nginx2 静态资源 配置文件如下
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 802;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~ \.(ico|js|css|png|jpg|mp4)$ {
root D:/StaticResource/wwwroot;
}
}
}
-
Nginx3 合并资源配置文件如下
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location / {
proxy_pass http://localhost:801;
}
location ~ \.(ico|js|css|png|jpg|mp4)$ {
proxy_pass http://localhost:802;
}
}
}