安裝nginx
環境:macos
mac環境下是使用的brew安裝nginx
1.終端輸入 brew search nginx 查找nginx
2.安裝指令 brew install nginx
安裝完成后會在終端中看到一些nginx的安裝信息
3.配置nginx
3.1 終端下進入目錄 cd /usr/local/
3.2 打開nginx配置文件所在目錄 open nginx/
配置文件為 nginx.conf
3.4 啟動nginx 指令為:
brew services start nginx
重啟指令:
brew services restart nginx
到此nginx安裝完畢
下面介紹利用nginx解決前端頁面訪問后端接口跨域問題
跨域問題配置
1.進入目錄 /usr/local/nginx ,修改配置文件nginx.conf,關鍵配置內容如下
listen 80; #原為8080,避免沖突,更改為80 server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { proxy_pass http://127.0.0.1:8848; # 前端靜態頁面地址,本人使用的HBuilderX編輯器,其工程默認端口為8848,可根據自己的項目情況修改 proxy_redirect default; #設置主機頭和客戶端真實地址,以便服務器獲取客戶端真實IP proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /apis { # 自定義nginx接口前綴 rewrite ^/apis/(.*)$ /$1 break; # 監聽所有/apis前綴,是則轉發后台api接口地址 include uwsgi_params; proxy_pass http://127.0.0.1:9099; # 后台api接口地址 #設置主機頭和客戶端真實地址,以便服務器獲取客戶端真實IP proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
保存配置后,終端輸入指令 brew services restart nginx 重啟nginx
注:如果啟動失敗報錯需要超級管理員權限,可先在終端輸入sudo -s 以管理員身份執行后續重啟操作
相應的前端ajax調用接口地址改為如下
$.ajax({ type:"POST", url:"/apis/xxx/xxx",//根據監聽的apis前綴,指向后端接口 data:{'xxx':'xxx'}, success:function (data) { }
最后瀏覽器地址欄輸入自己的前端工程地址 http://127.0.0.1:80/projectname/xxx.html
文末小福利免費視頻資源網站:www.sousuohou.com