背景:
(推薦教程:nginx教程)
最近在部署一個(gè)小程序的后臺(tái),但是小程序調(diào)用的接口是不能帶端口號(hào)的,那么如果服務(wù)器上面80端口已經(jīng)被其他程序占用,就只能采用端口轉(zhuǎn)發(fā)或者虛擬目錄,我采用的是端口轉(zhuǎn)發(fā),或者說(shuō)當(dāng)在一臺(tái)主機(jī)上需要部署多個(gè)web應(yīng)用,并且需要能在80端口訪問(wèn)這些web時(shí),就可以采用這種方法,也可以叫做nginx反向代理用于實(shí)現(xiàn)負(fù)載均衡。
具體介紹:
加入服務(wù)器域名是test.com,那么你可以通過(guò)test.com/news在80端口訪問(wèn)新聞應(yīng)用,但是服務(wù)器上分配的是其他端口,如8081。
對(duì)應(yīng)的nginx配置如下:
80端口的配置: 訪問(wèn)test.com/news => 127.0.0.1:8081 ,這里有一個(gè)需要注意的地方是轉(zhuǎn)發(fā)的url最后需要加上’/’,這相當(dāng)指定了url’/’,如果代理服務(wù)器地址中是帶有URL的,此URL會(huì)替換掉 location 所匹配的URL部分。
test.com/news/api,訪問(wèn)的是ip:8081/api;而如果代理服務(wù)器地址中是不帶有URI的,則會(huì)用完整的請(qǐng)求URL來(lái)轉(zhuǎn)發(fā)到代理服務(wù)器test.com/news/api,訪問(wèn)的是ip:8081/news/api。
server { listen 80; # listen [::]:80 default_server; server_name test.com root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } location /news{ proxy_pass http:test.com:8081/; } }
8081端口的配置: 與平時(shí)配置沒(méi)什么差別
server { listen 8081; server_name localhost; root /var/www/project; location / { index index.php index.html index.htm; if ( !-e $request_filename){ rewrite ^(.*)$ /index.php?s=/$1 last; break; } } #error_page 500 502 503 504 /50x.html; #location = /50x.html { #root /usr/share/ngixn/html; #} #我部署的是PHP項(xiàng)目,這里配置PHP解析 location ~ .php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; include /etc/nginx/fastcgi.conf; } }