新產品為了效果,做的比較炫,用了很多的圖片和JS,所以前端的性能是很大的問題,分篇記錄前端性能優化的一些小經驗。
第一篇:HTTP服務器
因tomcat處理靜態資源的速度比較慢,所以首先想到的就是把所有靜態資源(JS,CSS,image,swf)
提到單獨的服務器,用更加快速的HTTP服務器,這里選擇了nginx了,nginx相比apache,更加輕量級,
配置更加簡單,而且nginx不僅僅是高性能的HTTP服務器,還是高性能的反向代理服務器。
目前很多大型網站都使用了nginx,新浪、網易、QQ等都使用了nginx,說明nginx的穩定性和性能還是非常不錯的。
1. nginx 安裝(linux)
http://nginx.org/en/download.html 下載最新穩定版本
根據自己需要的功能先下載對應模板,這里下載了下面幾個模塊:
openssl-0.9.8l,zlib-1.2.3,pcre-8.00
編譯安裝nginx:
./configure
--without-http_rewrite_module
--with-http_ssl_module
--with-openssl=../../lib/openssl-0.9.8l
--with-zlib=../../lib/zlib-1.2.3
--with-pcre=../../lib/pcre-8.00
--prefix=/usr/local/nginx
make
make install
2、nginx處理靜態資源的配置
#啟動GZIP壓縮CSS和JS
gzip on;
# 壓縮級別 1-9,默認是1,級別越高壓縮率越大,當然壓縮時間也就越長
gzip_comp_level 4;
# 壓縮類型
gzip_types text/css application/x-javascript;
# 定義靜態資源訪問的服務,對應的域名:res.abc.com
server {
listen 80;
server_name res.abc.com;
# 開啟服務器讀取文件的緩存,
open_file_cache max=200 inactive=2h;
open_file_cache_valid 3h;
open_file_cache_errors off;
charset utf-8;
# 判斷如果是圖片或swf,客戶端緩存5天
location ~* ^.+.(ico|gif|bmp|jpg|jpeg|png|swf)$ {
root /usr/local/resource/;
access_log off;
index index.html index.htm;
expires 5d;
}
# 因JS,CSS改動比較頻繁,客戶端緩存8小時
location ~* ^.+.(js|css)$ {
root /usr/local/resource/;
access_log off;
index index.html index.htm;
expires 8h;
}
# 其他靜態資源
location / {
root /usr/local/resource;
access_log off;
expires 8h;
}
}
3、nginx 反向代理設置
# 反向代理服務,綁定域名www.abc.com
server {
listen 80;
server_name www.abc.com;
charset utf-8;
# BBS使用Discuz!
# 因反向代理為了提高性能,一部分http頭部信息不會轉發給后臺的服務器,
# 使用proxy_pass_header 和 proxy_set_header 把有需要的http頭部信息轉發給后臺服務器
location ^~ /bbs/ {
root html;
access_log off;
index index.php;
# 轉發host的信息,如果不設置host,在后臺使用request.getServerName()取到的域名不是www.abc.com,而是127.0.0.1
proxy_set_header Host $host;
# 因Discuz! 為了安全,需要獲取客戶端User-Agent來判斷每次POST數據是否跟第一次請求來自同1個瀏覽器,
# 如果不轉發User-Agent,Discuz! 提交數據就會報"您的請求來路不正確,無法提交"的錯誤
proxy_pass_header User-Agent;
proxy_pass http://127.0.0.1:8081;
}
# 其他請求轉發給tomcat
location / {
root html;
access_log off;
index index.jsp;
proxy_pass http://127.0.0.1:8080;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
nginx詳細配置參考:http://wiki.nginx.org/
PS:如果安裝提示GCC not found,運行下面命令安裝就可以(apt-get install build-essential),僅限debian