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

前后端分离项目,前后端共用一个域名。通过域名后的 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/;
        #解决页面刷新404问题
        try_files $uri $uri/ /index.html;
    }

    # 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;
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 lzdong@foxmail.com

×

喜欢就点赞,疼爱就打赏