nginx 配置實現埠轉發
阿新 • • 發佈:2019-02-02
最近在部署一個小程式的後臺,但是小程式呼叫的介面是不能帶埠號的,那麼如果伺服器上面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;
}
}