当前位置: 首页 > 后端技术 > PHP

Nginx代理同域名前端分离项目

时间:2023-03-29 23:46:48 PHP

前端分离项目,前后端共享一个域名。前后端项目通过域名后的url前缀来区分。以vue+php项目为例。直接进入server模块的nginx配置。服务器{听80;#listen[::]:80default_serveripv6only=on;服务器名称demo.com;#配置项目域名索引index.htmlindex.htmindex.php;#1.转移到前端处理位置/{#前端打包好的静态目录别名/home/wwwroot/default/vue-demo/dist/;#解决页面刷新404问题try_files$uri$uri//index.html;}#2.转移到后端处理位置/api/{try_files$uri$uri//index.php?$query_string;}#3.最终的php转移到这里的fpm位置~[^/]\.php(/|$){#后端项目目录root/home/wwwroot/default/demo/public/;#fastcgi_pass127.0.0.1:9000;fastcgi_passunix:/tmp/php-cgi.sock;fastcgi_indexindex.php;包括fastcgi.conf;包括路径信息.conf;}#4.处理后Staticresourcelocation/public/{alias/home/wwwroot/default/demo/public/uploads/;}#error_page404/404.html;access_log/home/wwwlogs/access.logmain;}简单说明当域名存在时使用/api/前缀,会转发给后端处理;当域名后有/uploads/前缀时,会访问后台的静态资源。由于位置精准匹配的原则,除上述之外的所有访问都会被重定向到第一个位置访问前端页面。例如:访问文章列表界面GEThttps://demo.com/api/posts访问上传的图片GEThttps://demo.com/uploads/xxx.jpg访问前端首页GEThttps://demo.com/访问文章页面GEThttps://demo.com/postsPS:别名路径末尾必须有/。