Nginx 小白篇

425 阅读1分钟

前言

开发完成后,前端打包后,无法本地验证怎么办?

使用nginx部署的时候,你就可以在本地先进行部署查看,提高上线的成功率

了解nginx后,在运维部署的时候,与运维对话找bug时,底气也稍微足点(至少不是啥也不会),还能从运维那偷师

安装

使用brew安装 nginx (homebrew)

brew update
brew search nginx
brew install nginx

运行

在终端运行 nginx启动nginx服务,此时打开http://127.0.0.1:8080即可打开页面

nginx初始主页的文件在/usr/local/var/www 文件夹下 看到的欢迎页面就是 /usr/local/var/www/index.html文件

对应的配置文件地址在/usr/local/etc/nginx/nginx.conf

配置

# nginx默认使用8080端口 如果发现端口被占用了,可以杀掉使用使用改端口的进程,也可以修改/usr/local/etc/nginx/nginx.conf 下的

http {
    server {
       listen       8081;
       server_name  localhost; 
       location / {
           index index.html index.htm;
           try_files $uri $uri/ /index.html;
       }
    }
}

其他配置(在location中加)

# 开启gzip
   gzip on;
   gzip_types text/css text/javascript application/javascript image/jpeg image/png image/gif;
   gzip_buffers 4 8k;
   gzip_min_length 1k;
   gzip_comp_level 9;
   gzip_vary on;
   gzip_proxied off;
   gzip_static on;
   error_log   /var/log/nginx/admin.error.log;
   access_log  /var/log/nginx/admin.access.log;
           
           
   expires -1;                          # 首页一般没有强制缓存
   add_header Cache-Control no-cache;
   add_header "Access-Control-Allow-Origin" $http_origin;   # 全局变量获得当前请求origin,带cookie的请求不支持*
   add_header "Access-Control-Allow-Methods" "*";  # 允许请求方法
   add_header "Access-Control-Allow-Headers" "*";  # 允许请求的 header

nginx 常用命令

  • 开启 nginx
  • 重启nginx nginx -s reload ,每次修改配置后需要重启才生效
  • 关闭nginx nginx -s stop