如果你的项目满足第一篇和第二篇文章介绍的,那么恭喜你,解决问题了,但是很多项目并不是一下子就事先搭建nginx静态服务器的,都是在问题出现之后,才进行架构重构的。
之前我们遇到这样的一个问题,通过不同机构,获取该机构下的某张图片,请求的url大致是这样的:http://localhost/projectName/img/10000/dept/1 ,其中10000表示机构ID,1表示该机构部门下的图片1.jpg ,遇到这样的问题,我们也很尴尬,因为图片存放在本地并不是根据结构来的。
还记得我们第一章说的 root C:\image; 的注释吗? 如果不改变请求的url,那么就是要存在C:\image\img\10000\dept\1.jpg 这样的文件,但是事实上却不是这样的,而是 C:\image\images\10000\1.jpg,这样就导致之前的方式不能直接效仿了,而且我们一般推荐把所有的静态资源都存放到固定格式下面,而不是随每个项目再创建文件,这样不利于维护,我们通过重写URL和正则表达式可以达到满足的效果。
还是老规矩:我们就需要修改nginx.conf文件
#user nobody; worker_processes 1;#推荐worker数为cpu核数,避免cpu不必要的上下文切换 events { #表示每个worker进程所能建立连接的最大值 #一个nginx最大的连接数max=worker_connections*worker_processes; #对于http请求本地资源最大并发数量为max #如果http作为反向代理,最大并发数为max/2。因为每个并发会建立与客户端的连接和与后端服务的连接,会占用两个连接。 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; keepalive_timeout 65; server { listen 80; server_name localhost; #charset koi8-r; access_log logs/host.access.log main; location / { root html; index index.html index.htm; } # serve static files(css|js|image..) # location ~* ^/projectName/img/ { rewrite ^/projectName/img/(\d+)/dept/(\d+)$ /images/$1/$2.jpg last; break; } location ~ ^/projectName/image/ { rewrite ^/projectName/image/(.*)$ /images/$1.jpg last; break; } location ~ ^/(images|javascript|js|css|flash|media|static)/ { root C:\image; access_log on; expires 30d; } #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; } } }
其中特别重要的是这句话:
rewrite ^/projectName/img/(\d+)/dept/(\d+)$ /images/$1/$2.jpg last;
1)首先通过正则表达式将请求的url匹配上
2)将匹配上的url 重定向为 /images/$1/$2
3) $1和$2 分别指的是 /projectName/img/(\d+)/dept/(\d+) 中的第一个(\d+)和第二个(\d+),依次对应