nginx反向代理的指令不須要新增額外的模塊,默認自帶proxy_pass指令,只須要修改配置文件就能夠實現反向代理。php
配置前的準備工做,後端跑項目的ip和端口,也就是說能夠經過http://ip:port能訪問到你的網站。html
upstream test { server ip:port; #部署項目的服&務器ip和端口 } server { listen 80; server_name www.quancha.cn; access_log logs/quancha.access.log main; error_log logs/quancha.error.log; root html; index index.html index.htm index.php; location / { proxy_pass http://test; #Proxy Settings 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_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; proxy_max_temp_file_size 0; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; } }
upstream test1 { server ip1:port;#部署項目的服&務器ip和端口 } upstream test2 { server ip2:port;#部署項目的服&務器ip和端口 } server { listen 80; #access_log logs/host.access.log main; location /test1 { proxy_pass http://test1; index index.html index.htm; } } server { listen 80; #access_log logs/host.access.log main; location /test2 { proxy_pass http://test2; index index.html index.htm; } }
在nginx中配置proxy_pass代理轉發時,若是在proxy_pass後面的url加/,表示絕對根路徑;若是沒有/,表示相對路徑,把匹配的路徑部分也給代理走。nginx
假設下面四種狀況分別用 http://192.168.1.1/proxy/test.html 進行訪問。後端
location /proxy/ { proxy_pass http://192.168.1.1/; }
訪問URL:http://192.168.1.1/test.html網站
location /proxy/ { proxy_pass http://192.168.1.1; }
訪問URL:http://192.168.1.1/proxy/test.htmlurl
location /proxy/ { proxy_pass http://192.168.1.1/test/; }
代理到URL:http://192.168.1.1/teset/test.htmlspa
location /proxy/ { proxy_pass http://192.168.1.1/test; }
代理到URL:http://192.168.1.1/testtest.html代理