天天看點

nginx開啟端口轉發到tomcat, 實作前後端分離部署

一. 首先你得安裝好nginx和tomcat

說說我的配置

系統: centos7(其實哪個系統沒啥關系)

給nginx配置設定了80端口, 給tomcat配置設定了8080端口

二. 配置Nginx

我的配置:

外網隻能通路80端口, 也就是隻能通路nginx

前端的請求直接由nginx相應, 資料請求交給tomcat去做

我的資料接口都以 xxx.com/data 開頭, 将其交給tomcat

nginx的配置檔案是在 nginx主目錄/conf/nginx.conf

進入該檔案, 該檔案的結構

worker_processes  1;
events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    # 在此處添加, 要加在它前面
   
    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

    # XXX不能在這添加XXX
}
           

在上述位置添加如下配置, 每行後面有分号, 然後重新開機nginx(如果報錯,請檢查格式是否比對)

server {
        listen       80;
        server_name  test_local;

        location /data {
            proxy_pass http://localhost:8080/;
        }
    }
           

這裡的意思是讓 比對 /data 的url通路都轉發到 proxy_pass指定的位置去, 注意要加到前面, 否則都讓本來的 / (比對所有)搶去了

重新開機後就可以了!

demo.com/data 比對到tomcat的 => / 

demo.com/data/students 比對到tomcat的 => /student

繼續閱讀