前后端拆散我的项目,前后端共用一个域名。通过域名后的 url 前缀来区别前后端我的项目。
以 vue + php 我的项目为例。间接上 server 模块的 nginx 配置。
server { listen 80; #listen [::]:80 default_server ipv6only=on; server_name demo.com; # 配置我的项目域名 index index.html index.htm index.php; # 1.转给前端解决 location / { # 前端打包后的动态目录 alias /home/wwwroot/default/vue-demo/dist/; } # 2.转给后端解决 location /api/ { try_files $uri $uri/ /index.php?$query_string; } # 3.最终php在这里转给fpm location ~ [^/]\.php(/|$) { # 后端我的项目目录 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.解决后端的动态资源 location /public/ { alias /home/wwwroot/default/demo/public/uploads/; } #error_page 404 /404.html; access_log /home/wwwlogs/access.log main;}
简略解释
- 当域名后存在 /api/ 前缀时,将转给后端解决;
- 当域名后存在 /uploads/ 前缀时,拜访后端的动态资源。
- 因为 location 精准匹配的准则,除以上之外的拜访都会被转到第一处 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 门路开端肯定要有 / 。