假设项目包含前端vue,后台管理系统admin,后端接口api
一、分别部署,采用不同域名
前端域名:vue.shop.test
后端地址:shop.test/admin
接口地址:shop.test/api
1.在前端项目服务器的 nginx 下,根目录指向目标文件夹
server
{
listen 80;
server_name vue.shop.test;#域名
index index.php index.html index.htm default.php default.htm default.html;
root /www/wwwroot/vue.shop.test/dist;#根目录
...
}
2.反向代理到接口地址
#意思就是只要含有"api"的请求,都转发到接口地址去请求
location /api
{
add_header 'Access-Control-Allow-Origin' '*';
proxy_pass http://shop.test/api;
}
3.后端项目配置跨域
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
}
二、分别部署,采用相同域名
# demo.conf
server
{
listen 80;
server_name demo.com; # 配置项目域名
index index.html index.htm index.php;
# 默认访问前端项目
location / {
# 前端打包后的静态目录
alias /path/dist/;
#解决页面刷新404问题
try_files $uri $uri/ /index.html;
}
# 后端项目
location ~* ^/(api|admin) {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP-INFO-START PHP引用配置,可以注释或修改,写法 1 和写法 2 任意一种都可以
# 1.宝塔写法 include enable-php-80.conf;
location ~ \.php(.*)$
{
root /path/public/;
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi-80.sock;
fastcgi_index index.php;
include fastcgi.conf;
include pathinfo.conf;
}
# 2.一般写法,使用 nginx 默认提供的配置,加上 `root` 相关配置即可
location ~ \.php(.*)$ {
root /path/public/;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
#PHP-INFO-END
# 前端静态资源处理
location ^~ /images/ {
alias /path/dist/images/;
}
# 后端静态资源处理
location ^~ /vendor/ {
alias /path/public/vendor/;
}
location ^~ /storage/ {
alias /path/public/storage/;
}
}
网友评论