Nginx代理同域名前后端分離項(xiàng)目的完整步驟
前后端分離項(xiàng)目,前后端共用一個(gè)域名。通過域名后的 url 前綴來區(qū)別前后端項(xiàng)目。
以 vue + php 項(xiàng)目為例。直接上 server 模塊的 nginx 配置。
server
{
listen 80;
#listen [::]:80 default_server ipv6only=on;
server_name demo.com; # 配置項(xiàng)目域名
index index.html index.htm index.php;
# 1.轉(zhuǎn)給前端處理
location /
{
# 前端打包后的靜態(tài)目錄
alias /home/wwwroot/default/vue-demo/dist/;
}
# 2.轉(zhuǎn)給后端處理
location /api/ {
try_files $uri $uri/ /index.php?$query_string;
}
# 3.最終php在這里轉(zhuǎn)給fpm
location ~ [^/]\.php(/|$)
{
# 后端項(xiàng)目目錄
root /home/wwwroot/default/demo/public/;
#fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
include pathinfo.conf;
}
# 4.處理后端的靜態(tài)資源
location /public/ {
alias /home/wwwroot/default/demo/public/uploads/;
}
#error_page 404 /404.html;
access_log /home/wwwlogs/access.log main;
}
簡(jiǎn)單解釋
- 當(dāng)域名后存在 /api/ 前綴時(shí),將轉(zhuǎn)給后端處理;
- 當(dāng)域名后存在 /uploads/ 前綴時(shí),訪問后端的靜態(tài)資源。
- 由于 location 精準(zhǔn)匹配的原則,除以上之外的訪問都會(huì)被轉(zhuǎn)到第一處 location 訪問前端頁面。
例如:
訪問文章列表接口
GET https://demo.com/api/posts
訪問上傳的圖片
GET https://demo.com/uploads/xxx.jpg
訪問前端首頁
GET https://demo.com/
訪問文章頁面
GET https://demo.com/posts
PS:alias 路徑末尾一定要有 / 。
總結(jié)
到此這篇關(guān)于Nginx代理同域名前后端分離項(xiàng)目的文章就介紹到這了,更多相關(guān)Nginx代理同域名前后端分離項(xiàng)目?jī)?nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信