1. Installation and uninstallation of NGINX
1.1.Install NGINX
apt-get install nginx
1.2.NGINX operation commands
service nginx start #启动
service nginx reload #重新加载配置文件
service nginx restart #重启
service nginx status #查看运行状态
1.3. Uninstall NGINX
apt-get remove nginx nginx-common # 卸载删除除了配置文件以外的所有文件。
apt-get purge nginx nginx-common # 卸载所有,包括删除配置文件。
apt-get autoremove # 在上面命令结束后执行,主要是卸载删除Nginx的不再被使用的依赖包。
apt-get remove nginx-full nginx-common #卸载删除两个主要的包。
2.NGINX configuration
2.1. Turn on gzip compression
Add the following configuration to the http {} block of nginx.conf to enable gzip compression.
gzip on;
# 开启 gzip_static
# gzip_static 开启后可能会报错,需要安装相应的模块, 具体安装方式可以自行查询
# 只有这个开启,前端打包的 .gz 文件才会有效果,否则不需要开启 gzip 进行打包
gzip_static on;
gzip_proxied any;
gzip_min_length 1k;
gzip_buffers 4 16k;
# 如果 nginx 中使用了多层代理,必须设置这个才可以开启 gzip
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary off;
gzip_disable "MSIE [1-6]\.";
2.2. Configure a website service and support cross-domain access to the backend API
server {
listen 8080; #网站端口
server_name www.myservice.com; #网站名称
location / {
root /opt/gnss/mysystem/dist; #存储前端打包的文件目录
index index.html; #默认页面
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://localhost:8080/; #后台API地址
}
}
try_files description:
- Search for existing files in the specified file order and use the first found file for request processing
- The search path is based on the given root or alias as the root path.
- If none of the given files are matched, the uri given in the last parameter will be requested again, which is the new location match.
- If it is format 2, if the last parameter is = 404, and if none of the given files are matched, the response code of 404 will be returned.
If we do not configure it here, a 404 error will be reported when the page is refreshed in the system.
Regarding the location /api/ in the configuration, the API here is not defined arbitrarily by us. It needs to be constrained with the front end. When it is used to match the front-end request interface, the access interface specified is in the format: /api/xxxxx, then this request will be Agent:
http://localhost:8080/xxxxx
In this way, the front end does not need to set the specific URL address of the interface when requesting the interface. It only needs to pass a constrained "api" prefix to make the interface request.