2018-09-06
运维
0

目录

重定向
try_files
静态资源类型压缩、缓存、跨域、防盗
文件压缩
浏览器缓存
跨域
防盗链配置

本篇主要是自己学习Nginx 重定向、try_files、静态资源压缩、缓存、跨域、防盗后的文章记录

重定向

image.png

image.png

nginx
server { listen 2999; server_name localhost; location / { root opt; index 1.html; if ($http_user_agent ~* Chrome) { # ~*为不区分大小写的正则匹配 rewrite ^/1.html /2.html; } if (!-f $request_filename) { # -f为判断路径是否存在 rewrite ^/(.*)$ http://www.baidu.com redirect; } } location ~ ^/3\.html{ rewrite ^/3\.html /1.html redirect; } }

try_files

nginx
server { listen 81; server_name localhost; root opt; index 1.html; location / { root opt; try_files $uri @page; # opt目录下,若$uri存在,则拿取opt目录下的文件。否则去@page下查询该路径 } location @page { proxy_pass http://localhost:7071; } }

静态资源类型压缩、缓存、跨域、防盗

文件压缩

image.png

nginx
# 对文本有较好的压缩,对图片压缩影响较小。也可以用来压缩js,css文件。 location ~ .*\.(jpg|gif|png|txt)$ { gzip on; gzip_http_version 1.1; # http协议版本 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; #支持的压缩格式 root opt; }

浏览器缓存

image.png

nginx
# 会在response同时设置Cache-Control: max-age和Expires # 如果request设置Cache-Control: max-age,则responese的Cache-Control无效 location ~ .*\.html$ { expires 24h; root opt; }

跨域

image.png

nginx
location ~ .*\.html$ { add_header Access-Control-Allow-Origin http://localhost:8088; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; root opt; }

防盗链配置

image.png

nginx
# none 允许不带referers信息的访问(referers为日志信息,如http://localhost) # blocked 允许referers的信息不是标准的带http信息协议头的进行访问 location ~ .*\.(js|css)$ { root opt; valid_referers none blocked localhost; if ($invalid_referer) { return 403; } }

本文作者:BARM

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!