天天看點

跨域通路方法-Nginx反向代理

1. nginx安裝

(1) 安裝pcre

下載下傳連結:https://sourceforge.net/projects/pcre/files/latest/download?source=files

下載下傳後解壓壓縮包,進入解壓後檔案夾的目錄,打開終端。

運作指令:$ sudo ./configure --prefix=/usr/local
        $ sudo make $ sudo install
           

(2) 安裝nginx

下載下傳連結:

Linux:http://nginx.org/download/nginx-1.10.1.tar.gz

windows:http://nginx.org/download/nginx-1.10.1.zip

下載下傳後解壓壓縮包,進入解壓後檔案夾的目錄,打開終端。

運作指令:$ sudo ./configure --prefix=/usr/local/nginx
 --with-cc-opt="-Wno-deprecated-declarations"
        $ sudo make $ sudo install

配置環境變量:
運作指令: $ touch ~/.bash_profile
        $ open ~/.bash_profile
編輯bash_profile檔案,向PATH新增nginx變量:
    export PATH=$PATH:/usr/local/nginx/sbin
           

2. nginx操作

(1) 啟動nginx:

運作指令:$ nginx

打開浏覽器http://localhost,看到以下頁面則表明nginx運作正常

                    Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.
For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.
           

Thank you for using nginx.

(2) 關閉nginx:

運作指令:$ nginx -s stop
           

(3) 重新開機nginx:

運作指令:$ nginx -s reload
           

3. nginx 反向代理配置

(1) 進入nginx的conf目錄:

運作指令:$ cd /usr/local/nginx/conf
           

(2) 修改nginx.conf檔案:

運作指令:$ vi nginx.conf
修改如下内容:
   server {
    listen       9000;
    server_name  localhost;
    autoindex off;
    index index.html index.htm index.php;
    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        #root   html;
        proxy_pass http://localhost:8080/;
        index  index.html index.htm;
    }

    location /BCYS-Market-biz/ {
        #rewrite ^.+api/?(.*)$ /BCYS-Market-biz/$1 break;
        proxy_pass http://120.76.97.189:21080;

    }
  }

 儲存後退出
           

(3) 重新開機nginx

參考資料:

  1. 用nginx的反向代理機制解決前端跨域問題:http://www.w2bc.com/Article/86876
  2. nginx配置location總結及rewrite規則寫法:http://seanlook.com/2015/05/17/nginx-location-rewrite/

繼續閱讀