系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > server > anz > 详细页面

Nginx代理同域名前后端分离项目的完整步骤

时间:2020-10-18来源:www.pcxitongcheng.com作者:电脑系统城

前后端分离项目,前后端共用一个域名。通过域名后的 url 前缀来区别前后端项目。

以 vue + php 项目为例。直接上 server 模块的 nginx 配置。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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 访问前端页面。

例如:

访问文章列表接口

?
1 GET https://demo.com/api/posts

访问上传的图片

?
1 GET https://demo.com/uploads/xxx.jpg

访问前端首页

?
1 GET https://demo.com/

访问文章页面

?
1 GET https://demo.com/posts

PS:alias 路径末尾一定要有 / 。

总结

到此这篇关于Nginx代理同域名前后端分离项目的文章就介绍到这了

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载