- 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 路径末尾一定要有 / 。