忘记说了一个很重要的事情,当你修改完conf/nginx.conf文件的时候,一定要重启Nginx,在Nginx安装目录下执行命令:nginx -s reload
如果你还不会简单的搭建nginx静态资源服务器,那么推荐你看一下我的上一篇文章《nginx静态资源服务器(一)》
一般请求都是不会那么简单,通过是项目来请求的,比如:http://localhost:80/projectName/image/123 来访问图片,那么我们就需要对请求的URL重写。
下面举个简单的例子:http://localhost:80/projectName/image/123 这个地方是没有后缀的图片格式,我们就需要修改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/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/image/(.*)$ /images/$1.jpg last;
这个$1 代表则是image/后面的(.*)正则表达式的全部内容,因为浏览器访问的时候是不带有后缀的,所有给他默认添加一个.jpg的后缀。
至于如果用户是带有后缀的123.jpg的情况下,请你们自己修改测试,自己动手才能学的更快!