其实就是一个轻量级的服务器,能够很好的处理反向代理和负载均衡;能够很好的处理静态资源;因此很适合咱们前端使用,也很简单。
咱们主要用来作接口转发(以及一些其余事情)。javascript
启动css
sudo nginxhtml
测试配置文件(也能够用来查看配置文件的路径) 前端
sudo nginx -t java
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfulnginx
从新加载配置文件web
sudo nginx -s reloadvim
其余(中止,退出,重启)缓存
sudo nginx -s (stop|quit|reopen)服务器
nginx的关键在于配置文件的设置,里面参数不少,能够参见文档。
这里只介绍咱们可能会用到的。
vim /etc/nginx/nginx.conf # 设置用户组 #user nobody; # 占用内核数,通常设置为服务器最高内核 worker_processes 1; # error log 存放位置 #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { # 每个worker进程能并发处理的最大链接数 worker_connections 1024; } http { include 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 logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; # 开启gzip压缩 gzip on; # gzip默认不压缩javascript、图片等静态资源文件 gzip_types text/plain application/x-javascript text/css text/javascript; #nginx上传限制,默认为1M; client_max_body_size 6m; # 引入其余配置文件 include /etc/nginx/conf.d/*.conf; #### 重点在这个里面 #### server { listen 80; # 访问的Domain server_name 10.142.78.40; # 根目录 root E:\work; # 文件夹索引,生产环境要关闭 autoindex on; # 匹配到/的时候默认加载index.html 而后在找index.htm index index.html index.htm; # 这2行须要加进来,否则页面的中文可能会出现乱码 default_type ‘text/html’; charset utf-8; # header 容许_字符 underscores_in_headers on; location ~(/usrcenter){ # 匹配到usrcenter, 转发到http://10.142.78.40:8787/usrcenter proxy_pass http://10.142.78.40:8787; } location /o2blog_wx/ { # 当访问xxxx/o2blog_wx的时候转发到服务器上的http://127.0.0.1:3000 # 经过rewrite字段重写,将o2blog_wx进行正则匹配替换 # 也就是xxxx/o2blog_wx/hello =》 http://127.0.0.1:3000/hello proxy_pass http://127.0.0.1:3000; rewrite ^/o2blog_wx/(.*) /$1 break; } # 不让dist的东西去匹配/ 里面的内容 location ~(/dist){ # 关闭静态资源缓存,方便dbeug;生产环境不要用 expires off; # expires 365d; } # 将/下面的URL 都重写到/index.html location / { rewrite ^ /index.html break; index index.html index.htm; } ## 设置302 跳转 location /o2blog_wx/ { # 当匹配到http://aotu.jd.com/o2blog_wx/的时候会跳转到http://aotu.jd.com/wxblog return 302 http://aotu.jd.com/wxblog } error_log /var/log/nginx/html_error.log; # 将404 和50X 重定向到 对应的报错页面 error_page 404 /404.html; error_page 500 502 503 504 /50x.html; } }
https
环境切换
在nginx里面拿cookie;根据cookie跳转到不一样的环境接口;很方便的测试接口
set $env_id "1.1.1.1"; if ( $http_cookie~* "host_id=(\S+)(;.*|$)") { set $env_id $1; } location / { proxy_set_header Host $host; proxy_pass http://$env_id:80; }
内容劫持
nginx_http_footer_filter 是淘宝开发的一个nginx模块;能够在文件的底部添加文字;好比往html里面添加小广告等等~呵呵~~
CDN combo
利用nginx_http_concat,将请求合并,经过这样的方式http://example.com/??style1.c...访问合并后的资源。(也是阿里系的经常使用作法)
适配PC与移动web
经过判断UA,作302跳转到 pc的路径和H5的路径
ps:查看端口是否被占用:
sudo lsof -i :8090