因爲公司內網有多臺服務器的http服務要映射到公司外網靜態IP,若是用路由的端口映射來作,就只能一臺內網服務器的80端口映射到外網80端口,其餘服務器的80端口只能映射到外網的非80端口。非80端口的映射在訪問的時候要域名加上端口,比較麻煩。而且公司入口路由最多隻能作20個端口映射。確定之後不夠用。
而後發現能夠在內網搭建一個nginx反向代理服務器,將nginx反向代理服務器的80映射到外網IP的80,這樣指向到公司外網IP的域名的HTTP請求就會發送到nginx反向代理服務器,利用nginx反向代理將不一樣域名的請求轉發給內網不一樣機器的端口,就起到了「根據域名自動轉發到相應服務器的特定端口」的效果,而路由器的端口映射作到的只是「根據不一樣端口自動轉發到相應服務器的特定端口」。html
本次實驗目標是作到:在瀏覽器中輸入xxx123.tk能訪問到內網機器192.168.10.38的3000端口,輸入xxx456.tk能訪問到內網機器192.168.10.40的80端口。java
vim nginx.confios
worker_processes 1; error_log logs/error.log; pid logs/nginx.pid; worker_rlimit_nofile 65535; events { use epoll; worker_connections 65535; } http { include mime.types; default_type application/octet-stream; include /usr/local/nginx/conf/reverse-proxy.conf; sendfile on; keepalive_timeout 65; gzip on; client_max_body_size 50m; #緩衝區代理緩衝用戶端請求的最大字節數,能夠理解爲保存到本地再傳給用戶 client_body_buffer_size 256k; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; proxy_connect_timeout 300s; #nginx跟後端服務器鏈接超時時間(代理鏈接超時) proxy_read_timeout 300s; #鏈接成功後,後端服務器響應時間(代理接收超時) proxy_send_timeout 300s; proxy_buffer_size 64k; #設置代理服務器(nginx)保存用戶頭信息的緩衝區大小 proxy_buffers 4 32k; #proxy_buffers緩衝區,網頁平均在32k如下的話,這樣設置 proxy_busy_buffers_size 64k; #高負荷下緩衝大小(proxy_buffers*2) proxy_temp_file_write_size 64k; #設定緩存文件夾大小,大於這個值,將從upstream服務器傳遞請求,而不緩衝到磁盤 proxy_ignore_client_abort on; #不容許代理端主動關閉鏈接 server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
server { listen 80; server_name xxx123.tk; location / { 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; proxy_pass http://192.168.10.38:3000; } access_log logs/xxx123.tk_access.log; } server { listen 80; server_name xxx456.tk; location / { 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; proxy_pass http://192.168.10.40:80; } access_log logs/xxx456.tk_access.log; }
在瀏覽器中輸入xxx123.tk的時候訪問的內網服務器192.168.10.38的3000端口,輸入xxx456.tk訪問192.168.10.40的80端口的做用。若是想對後端機器作負載均衡,像下面這配置就能夠把對nagios.xxx123.tk的請求分發給內網的131和132這兩臺機器作負載均衡了。nginx
upstream monitor_server { server 192.168.0.131:80; server 192.168.0.132:80; } server { listen 80; server_name nagios.xxx123.tk; location / { 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; proxy_pass http://monitor_server; } access_log logs/nagios.xxx123.tk_access.log; }
以前沒配置下面這段,訪問時候偶爾會出現504 gateway timeoutvim
proxy_connect_timeout 300s; proxy_read_timeout 300s; proxy_send_timeout 300s; proxy_buffer_size 64k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; proxy_ignore_client_abort on;