Nginx反向代理解決跨域問題訪問後臺接口(同一個服務器)+部署springboot項目(前後端分離)

前言:博主已經將自己的vue項目部署在nginx上邊,服務器是阿里雲服務器,今天是要部署springboot後臺並實現前臺請求轉發到後臺,踩了很多坑,記錄一下。

一、服務器環境

  • 阿里雲服務器
    • jdk1.8
    • docker(以下是容器)
      • Redis
      • Rabbitmq
      • mysql8.x

二、服務器配置jdk環境

該步驟請查看:服務器配置jdk1.8環境並永久性運行

三、部署springboot

在這裏插入圖片描述
雙擊package即可進行打包,博主設置的是jar
生成之後如下
在這裏插入圖片描述
然後我們直接將該jar包往服務器上一丟(隨便找個文件夾,或者自己建一個)
cd 到jar包位置,執行以下命令

$ nohup java -jar 包名.jar >log.txt &

// 這種方法會把日誌文件輸入到你指定的文件中,沒有則會自動創建。並且進程會在後臺運行。
// 不要忘記後邊的  &

我們查看一下端口情況,我的佔用的是8001端口,執行netstat -anp |grep 8001,看到如下
在這裏插入圖片描述
此時,後臺已經跑起來了,並且有一些tcp連接隨時待命

四、修改Nginx配置

方案一

在沒有設置代理的情況下,客戶端請求到nginx,nginx服務器是不會進行轉發的,接下來我們配置一下,vim /etc/nginx/nginx.conf或者拷貝到本地修改再上傳
在這裏插入圖片描述

# 核心配置
 server {
        listen       8080;
        server_name  xxxxxxx;
        # root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
	    root /dist;
	    index index.html;
	    try_files $uri $uri/ /index.html;
        }
        
		location /api {
			add_header Access-Control-Allow-Origin *;
    		add_header Access-Control-Allow-Methods 'GET, POST, DELETE, PUT, OPTIONS';
    		add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
			if ($request_method = 'OPTIONS') {
     				return 204;
   			}
			rewrite ^/api/(.*)$ /$1 break;
			proxy_pass http://xxxxxxx:8001;
		}
}
  • 修改完之後,重啓nginx,nginx -s reload,如果啓動失敗,報.pid文件的錯,比如:
nginx: [error] open() "/run/nginx.pid" failed (2: No such file or directory)

也就是沒有改文件,我們找到報錯目錄,並在其下新建nginx.pid文件,然後nginx -s stop關閉服務,然後nginx -c /etc/nginx/nginx.conf直接以配置文件重啓,注意,nginx.pid所在的路徑必須和配置文件中配置的pid文件路徑一樣,我這裏是/run/nginx.pid

  • 然後就可以訪問了
  • 當瀏覽器發送ip+8080請求時,nginx響應前端資源,在頁面內,我們點擊按鈕,或者提交表單等操作請求服務器時,nginx檢測到api字樣則進行轉發處理,添加上請求頭刪除api字樣,然後轉發到後臺接口進行處理

附:nginx.conf

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
	
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       8080;
        server_name  xxxxxx;
        # root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
	    root /dist;
	    index index.html;
	    try_files $uri $uri/ /index.html;
        }
		
		location /api {
			add_header Access-Control-Allow-Origin *;
    		add_header Access-Control-Allow-Methods 'GET, POST, DELETE, PUT, OPTIONS';
    		add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
			if ($request_method = 'OPTIONS') {
     				return 204;
   			}
			rewrite ^/api/(.*)$ /$1 break;
			proxy_pass http://xxxxxx:8001;
		}

        error_page 404 /404.html;
            location = /40x.html {
        }

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

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers PROFILE=SYSTEM;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}


方案二

這個方案我沒有使用過,只是理論上可行
具體思路是:

  • (前後端都在同一個服務器)添加一個server,監聽一個端口比如8888端口,vue中axios的baseurl請求端口改成8888,然後添加代理,進行轉發到8001端口

以上都爲博主個人理解,如有不對,麻煩指出
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章