作为前端开发者,也很有必要了解一些运维部署知识。
nginx的作用有哪些?
- 负载平衡
- 动静分离
- 反向代理
何为反向代理?
反向代理即是,用户访问nginx服务器,nginx又将请求转发到真正服务器上,为什么用户不能直接访问服务器呢?
原因是:当项目拥有多台服务器的,每台服务器的端口号不一样,无法做到通过一个ip+端口号访问所有服务器,所以我们通过访问nginx服务器的话,可以做到用户无感知的访问网页。
通过proxy
何为动静分离?
对于css、js、图片等一些静态资源,直接请求nginx服务,不再去请求后端服务;
对于接口,请求后端服务
何为负载平衡?
nginx转发请求的时候,对于配置高的服务器会接收到更多的请求,配置低的接受到的请求比较少。通过upstream+proxy
如何部署一个vue静态项目
事前准备:下载一个稳定版本的nginx
修改nginx.conf文件
必须加上这行try_files $uri $uri/ /index.html;
#一些全局配置
#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;
events {
worker_connections 1024;
}
#http 配置
http {
include mime.types;
default_type application/octet-stream;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
#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;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
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;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
# 不同端口配置
server {
listen 8000;
# listen somename:8080;
server_name somename alias another.alias;
location / {
root html;
index index.html index.htm;
}
}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# 做些重写操作
}
一些常见问题参考:
https://blog.csdn.net/qq_42089323/article/details/122979941
https://zhuanlan.zhihu.com/p/448867939