Nginx-反響代理Tomcat
阿新 • • 發佈:2019-01-26
- 反向代理概念
先說正向代理,比如要訪問youtube,但是不能直接訪問,只能先找個翻牆軟體,通過翻牆軟體才能訪問youtube. 翻牆軟體就叫做正向代理。
所謂的反向代理,指的是使用者要訪問youtube,但是youtube悄悄地把這個請求交給bilibili來做,那麼bilibili就是反向代理了。
在當前教程指的就是訪問nginx,但是nginx把請求交給tomcat來做。 - 啟動tomcat
首先啟動多個Tomcat 中埠號是8111的tomcat - 修改nginx.conf
然後修改nginx.conf,主要是30-42行
location / 表示處理所有請求location / { proxy_pass http://127.0.0.1:8111; }
proxy_pass http://127.0.0.1:8111; 表示把請求都交給http://127.0.0.1:8111來處理#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { 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; keepalive_timeout 65; #gzip on; server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { proxy_pass http://127.0.0.1:8111; } #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; # } #} }
- 重啟nginx並訪問
使用如下命令重啟 nginxnginx -s reload
然後訪問地址:
就會觀察到已經反向代理到tomcat了http://127.0.0.0/
- 意義何在
既然直接通過127.0.0.1:8111/login.jsp 可以訪問,那麼幹嘛要通過127.0.0.1/login.jsp 去反向代理到tomcat呢? 為什麼不直接使用tomcat呢?
因為nginx在處理靜態檔案的吞吐量上面比tomcat好很多,通常他們倆配合,不會把所有的請求都如本例所示的交給tomcat, 而是把靜態請求交給nginx,動態請求,如jsp, servlet,ssm, struts等請求交給tomcat. 從而達到動靜分離的效果。 接下來就會講解如何進行動靜分離。