Nginx动静分离
动静分离
Nginx动静分离是让动态网站里的动态网页根据一定规则把不变的资源和经常变的资源区分开来,动静资源做好了拆分以后,我们就可以根据静态资源的特点将其做缓存操作,这就是网站静态化处理的核心思路。
upstream apptest{ server localhost:8080; server localhost:8090; } server { listen 80; server_name localhost; location / { root /usr/local/nginx/html; index index.html index.htm; } # 所有静态请求都由nginx处理,存放目录为html location ~.(gif|jpg|jpeg|png|bmp|swf|css|js)$ { root /usr/local/nginx/html; } # 所有动态请求都转发给tomcat处理 location ~.(jsp|do)$ { proxy_pass http://apptest; proxy_redirect off; proxy_set_header HOST $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 50m; client_body_buffer_size 512k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 10k; proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k; } error_page 500 502 503 504 /50x.html; location = /50x.html { } }
这样我们就可以吧HTML以及图片和css以及js放到wwwroot目录下,而tomcat只负责处理jsp和请求,例如当我们后缀为gif的时候,Nginx默认会从wwwroot获取到当前请求的动态图文件返回,当然这里的静态文件跟Nginx是同一台服务器,我们也可以在另外一台服务器,然后通过反向代理和负载均衡配置过去就好了,只要搞清楚了最基本的流程,很多配置就很简单了,另外localtion后面其实是一个正则表达式,所以非常灵活.
配置实例:
upstream tomcat7{ server 192.168.100.105:8080; } server { listen 80; server_name www.saneri.com; location / { root /usr/local/nginx/html; index index.html index.htm; } location ~.(gif|jpg|jpeg|png|bmp|swf|css|js)$ { root /usr/local/nginx/html; } location ~.(jsp|do)$ { proxy_pass http://tomcat7; proxy_redirect off; proxy_set_header HOST $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 50m; client_body_buffer_size 512k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 10k; proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k; } location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } log_format access '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" $request_time'; access_log /usr/local/nginx/logs/access.log access;