Nginx 反向代理,流量转发到固定内网 IP 方法
主配置文件:
1 user nginx; 2 worker_processes 1; 3 4 error_log /var/log/nginx/error.log warn; 5 pid /var/run/nginx.pid; 6 7 events { 8 worker_connections 1024; 9 } 10 11 http { 12 include /etc/nginx/mime.types; 13 default_type application/octet-stream; 14 15 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 16 '$status $body_bytes_sent "$http_referer" ' 17 '"$http_user_agent" "$http_x_forwarded_for"'; 18 19 access_log /var/log/nginx/access.log main; 20 21 sendfile on; 22 #tcp_nopush on; 23 24 keepalive_timeout 65; 25 26 gzip on; 27 28 ################# 29 30 proxy_connect_timeout 300; 31 proxy_send_timeout 300; 32 proxy_read_timeout 300; 33 proxy_buffer_size 16k; 34 proxy_buffers 4 32k; 35 36 proxy_set_header Host $host; 37 proxy_set_header X-Real-IP $remote_addr; 38 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 39 40 #proxy_set_header X-Forwarded-For $remote_addr; 41 proxy_set_header Connection Close; 42 43 server_names_hash_max_size 1024; 44 server_names_hash_bucket_size 1024; 45 46 # Default cache parameters for use by virtual hosts 47 48 # Set the cache path to tmpfs mounted disk, and the zone name 49 50 # Set the maximum size of the on disk cache to less than the tmpfs file system size 51 52 proxy_cache_path ./cache levels=1:2 keys_zone=pscms:100m max_size=800m; 53 54 proxy_temp_path ./proxy; 55 56 ############# 57 58 include /etc/nginx/conf.d/*.conf; 59 }
网站配置文件:
1 upstream web_server { 2 #sticky; 3 server 192.168.203.23; 4 server 192.168.203.24; 5 server 192.168.203.25; 6 # ip_hash; 7 } 8 9 server { 10 listen 80; 11 server_name localhost; 12 charset utf-8; 13 access_log /var/log/nginx/21.log main; 14 15 location / { 16 if ( $remote_addr ~* ^(.*)\.(.*)\.(.*)\.193$){ 17 proxy_pass http://192.168.203.22; 18 break; 19 } 20 21 proxy_set_header Host $http_host; 22 proxy_redirect off; 23 proxy_pass http://web_server; 24 proxy_set_header Host $host; 25 proxy_set_header X-Real-IP $remote_addr; 26 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 27 } 28 }