背景:
(推薦教程:nginx教程)
最近在部署一個小程序的后臺,但是小程序調用的接口是不能帶端口號的,那么如果服務器上面80端口已經被其他程序占用,就只能采用端口轉發或者虛擬目錄,我采用的是端口轉發,或者說當在一臺主機上需要部署多個web應用,并且需要能在80端口訪問這些web時,就可以采用這種方法,也可以叫做nginx反向代理用于實現負載均衡。
具體介紹:
加入服務器域名是test.com,那么你可以通過test.com/news在80端口訪問新聞應用,但是服務器上分配的是其他端口,如8081。
對應的nginx配置如下:
80端口的配置: 訪問test.com/news => 127.0.0.1:8081 ,這里有一個需要注意的地方是轉發的url最后需要加上’/’,這相當指定了url’/’,如果代理服務器地址中是帶有URL的,此URL會替換掉 location 所匹配的URL部分。
test.com/news/api,訪問的是ip:8081/api;而如果代理服務器地址中是不帶有URI的,則會用完整的請求URL來轉發到代理服務器test.com/news/api,訪問的是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端口的配置: 與平時配置沒什么差別
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項目,這里配置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; } }