博主最近在優化一個javaweb項目,該項目之前一直都是使用tomcat處理用戶請求的,無論靜態還是動態的東西,一律交給tomcat處理。tomcat主要是負責處理servlet的,靜態的文件還是交給nginx處理,nginx對靜態文件的處理比tomcat不是只快了一點,并且Nginx的使用對項目并發能力有很大的提升。下面主要記錄下主要的配置過程:
實驗環境:windows
實驗工具:Nginx、tomcat
windows下安裝Nginx非常簡單,去官網下載壓縮包解壓后并且雙擊解壓目錄下的nginx.exe程序即可。然后在瀏覽器輸入localhost可出現下圖,即表示nginx已經在工作。
nginx的工作流程是:對外,nginx是一個服務器,所有的請求都先請求到nginx,然后再由nginx對內網進行請求的分發到tomcat,然后tomcat處理完請求后將數據發送給nginx,然后由nginx發送給用戶,整個過程對用戶的感覺就是nginx在處理用戶請求。既然這樣子,nginx肯定需要進行配置,主要的配置文件是conf文件夾下的nginx.conf,因為我主要是進行了靜態與動態分離,所以沒有進行靜態文件緩存,也沒有進行負載均衡的配置。
#user nobody;worker_processes 2;#error_log logs/error.log;#error_log logs/error.log notice;#error_log logs/error.log info;#pid logs/nginx.pid;events { #nginx默認最大并發數是1024個用戶線程 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; #tcp_nopush on; #keepalive_timeout 0; #http1.1在請求完之后還會保留一段時間的連接,所以這里的timeout時長不能太大,也不能太小, #太小每次都要建立連接,太大會浪費系統資源(用戶不再請求服務器) keepalive_timeout 65; #gzip on; server { #nginx監聽80端口 listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; #這里的/表示所有的請求 #location / { #將80端口的所有請求都轉發到8080端口去處理,proxy_pass代表的是代理路徑 # proxy_pass http://localhost:8080; # root html; # index index.html index.htm; #} #對項目名進行訪問就去訪問tomcat服務 location /Student_Vote { proxy_pass http://localhost:8080; } #對jsp和do結尾的url也去訪問tomcat服務 location ~ /.(jsp|do)$ { proxy_pass http://localhost:8080; } #對js、css、png、gif結尾的都去訪問根目錄下查找 location ~ /.(js|css|png|gif)$ { root F:/javaweb; } #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; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ /.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ /.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ //.ht { # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #}}
新聞熱點
疑難解答